diff --git a/.agents/skills/formshot-rendering/references/tools.md b/.agents/skills/formshot-rendering/references/tools.md index 648e9f75..bb8e5f14 100644 --- a/.agents/skills/formshot-rendering/references/tools.md +++ b/.agents/skills/formshot-rendering/references/tools.md @@ -1,12 +1,12 @@ # formshot tools -Generated from the engine's command catalogue (formshot 0.4.0) by `./formshot agents sync`; do not edit by hand. +Generated from the engine's command catalogue (formshot 0.6.0) by `./formshot agents sync`; do not edit by hand. ## Contents -- Scene: `scene.add_group`, `scene.add_part`, `scene.add_primitive`, `scene.add_light`, `scene.add_cutaway`, `scene.remove`, `scene.rename`, `scene.set_transform`, `scene.set_visible`, `scene.set_locked`, `scene.set_ray_visibility`, `scene.set_part_colour`, `scene.set_metadata`, `scene.set_pivot`, `scene.set_light`, `scene.set_cutaway`, `scene.reparent`, `scene.duplicate`, `scene.import`, `scene.summary`, `scene.meshes`, `scene.mesh_data` +- Scene: `scene.add_group`, `scene.add_part`, `scene.add_primitive`, `scene.add_light`, `scene.add_cutaway`, `scene.remove`, `scene.rename`, `scene.set_transform`, `scene.set_visible`, `scene.set_locked`, `scene.set_ray_visibility`, `scene.set_part_colour`, `scene.set_metadata`, `scene.set_pivot`, `scene.set_part_mesh`, `scene.set_light`, `scene.set_cutaway`, `scene.reparent`, `scene.duplicate`, `scene.import`, `scene.summary`, `scene.meshes`, `scene.mesh_data`, `scene.retessellate` - Mesh: `mesh.add`, `mesh.remove` -- Materials: `material.create`, `material.set_params`, `material.set_type`, `material.assign`, `material.rename`, `material.remove` +- Materials: `material.create`, `material.set_params`, `material.set_type`, `material.set_slot`, `material.clear_slot`, `material.set_graph`, `material.label_add`, `material.label_set`, `material.label_remove`, `material.label_move`, `material.assign`, `material.rename`, `material.remove`, `material.types`, `material.node_kinds`, `material.program`, `material.preview_maps`, `material.get`, `material.labels` - Texture: `texture.add`, `texture.remove` - Cameras: `camera.add`, `camera.set`, `camera.set_active`, `camera.remove`, `camera.frame` - Environment: `environment.set` @@ -18,8 +18,12 @@ Generated from the engine's command catalogue (formshot 0.4.0) by `./formshot ag - App: `app.version`, `app.catalogue` - Selection: `selection.set`, `selection.clear` - History: `history.undo`, `history.redo`, `history.begin_group`, `history.end_group`, `history.abandon_group`, `history.barrier` -- Files: `file.new`, `file.open`, `file.save`, `file.import`, `file.close`, `file.export_image`, `file.export_model`, `file.snapshot`, `file.recover_list`, `file.recover` +- Files: `file.new`, `file.open`, `file.save`, `file.import`, `file.close`, `file.export_image`, `file.export_model`, `file.snapshot`, `file.recover_list`, `file.recover`, `file.reimport` - Viewing: `view.bounds`, `view.pick`, `view.frame` +- Import: `import.probe`, `import.start`, `import.status`, `import.cancel` +- Cad: `cad.status`, `cad.parts` +- Handoff: `handoff.inspect`, `handoff.open` +- Library: `library.list`, `library.get`, `library.favorite`, `library.recent`, `library.apply`, `library.save`, `library.remove`, `library.thumbnail`, `library.thumbnails` - Nodes: `node.set_visible`, `node.set_locked`, `node.rename`, `node.remove` - Undo: `undo` - Redo: `redo` @@ -144,6 +148,14 @@ Set or clear a node's gizmo pivot (local space). - `id`: integer; required; range 1 to inf; Node - `pivot`: value; Local pivot, null clears +## scene.set_part_mesh + +Make a part show another existing mesh in place, keeping its id, name, material, transform and metadata; its old mesh is removed when nothing else uses it. + +- `id`: integer; required; range 1 to inf; Part +- `mesh`: integer; required; range 1 to inf; Existing mesh the part shows from now on (add it first with mesh.add) +- `remove_unused`: boolean; default true; Remove the old mesh when no other part uses it + ## scene.set_light Change a light node's settings; give only the fields to change. @@ -196,10 +208,12 @@ Remove a mesh no part uses. ## material.create -Create a material. +Create a material, from a material type's preset when type is given. - `key`: integer; range 1 to inf; Key; allocated when absent -- `material`: object; fields name, params, textures, type_id +- `material`: object; fields graph, labels, name, params, slots, textures, type_id +- `name`: string; Name; the type's name when absent +- `type`: string (generic | plastic | plastic_clear | metal | metal_brushed | paint | paint_metallic | glass | glass_thin | liquid | gem | rubber | fabric | ceramic | diffuse | emissive | wood | stone); Start from this material type's preset (ignores material) ## material.set_params @@ -210,10 +224,71 @@ Change a material's surface parameters; give only the fields to change. ## material.set_type -Change a material's catalogue type id. +Change a material's type; keep false resets parameters and graph to the type's preset. -- `key`: integer; required; range 1 to inf; Material -- `type_id`: string; required; Catalogue type id +- `keep`: boolean; default true; Keep parameters and graph; false resets them to the type's preset +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `type_id`: string; required; Material type id (alias: type); see material.types + +## material.set_slot + +Drive a material input with an image texture (an existing texture or a new path); give only the slot fields to change. + +- `colour_space`: string; Colour-space hint for the new texture +- `input`: string (base_color | base_metalness | specular_weight | specular_roughness | coat_weight | coat_roughness | emission_color | geometry_opacity | normal | bump | displacement); required; Input the texture drives +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `path`: string; Image file to add as a new texture in the same step (instead of slot.texture) +- `slot`: object; Only the slot fields to change; a new slot starts from the defaults; fields channel, colour_space, fallback, filter, flip_y, invert, multiply, projection, range, strength, texture, transform, wrap + +## material.clear_slot + +Remove the texture slot of a material input; the constant applies again. + +- `input`: string (base_color | base_metalness | specular_weight | specular_roughness | coat_weight | coat_roughness | emission_color | geometry_opacity | normal | bump | displacement); required; Input +- `key`: integer; required; range 1 to inf; Material (alias: material) + +## material.set_graph + +Replace a material's node graph, or remove it with null. + +- `graph`: value; required; The whole graph; null removes it +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `merge`: boolean; default false; Merge into the previous merging set_graph of this material until history.barrier, so a value drag is one undo step + +## material.label_add + +Add a label (an image projected onto the parts wearing the material), optionally adding its image file in the same step; answers the new label id. + +- `colour_space`: string; Colour-space hint for the new texture +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `label`: object; Label fields over the defaults (0.1 m square facing +Z, 10 mm deep); fields colour_space, depth, id, metalness, name, normal, opacity, origin, rotation, roughness, size, texture, two_sided, up, visible +- `path`: string; Image file to add as the label's texture in the same step + +## material.label_set + +Change a label; give only the fields to change (path replaces its image with a new texture). + +- `colour_space`: string; Colour-space hint for the new texture +- `id`: integer; required; range 1 to inf; Label id +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `label`: object; Only the label fields to change; fields colour_space, depth, id, metalness, name, normal, opacity, origin, rotation, roughness, size, texture, two_sided, up, visible +- `path`: string; Image file to add as the label's new texture in the same step + +## material.label_remove + +Remove a label from a material. + +- `id`: integer; required; range 1 to inf; Label id +- `key`: integer; required; range 1 to inf; Material (alias: material) + +## material.label_move + +Move a label within its material's list; later labels print over earlier ones. + +- `id`: integer; required; range 1 to inf; Label id +- `index`: integer; required; range 0 to inf; New position; later labels print over earlier ones +- `key`: integer; required; range 1 to inf; Material (alias: material) ## material.assign @@ -402,9 +477,17 @@ Start a new document, empty or from a template (empty-studio, product-white, stu ## file.open -Open a .fshot project, or a model file as a new document. +Open a .fshot project, or a model file as a new document with the file.import options (camera framed). -- `path`: string; required; A .fshot project or a model file +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `merge`: boolean; default false; Put everything the file holds under one group +- `name`: string; Name for the imported group (the original file name) +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y ## file.save @@ -414,12 +497,18 @@ Save the document as .fshot to path, or to its own path. ## file.import -Import a model (glb, gltf, obj, stl, ply) with clean-up as one undoable step. +Import a model (glb, gltf, obj, stl, ply, 3mf, fbx, step, iges) with clean-up as one undoable step; units, up_axis, stand_on_floor, center, merge and cad_quality are optional, and every node made carries source.path and source.node metadata. -- `frame`: boolean; Frame the camera on the result (default: only when the document was empty) +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `frame`: boolean; Frame the camera on the result (default: only when the document had no parts) +- `merge`: boolean; default false; Put everything the file holds under one group - `name`: string; Name for the imported group (the original file name) -- `options`: object; fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group -- `path`: string; required; Model file: glb, gltf, obj, stl or ply +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y ## file.close @@ -598,6 +687,224 @@ Move the active camera, keeping its view direction, so the given nodes (or every - `nodes`: array of ['string', 'integer']; Node ids (decimal strings or numbers) - `width`: number; range 1 to inf; Viewport width in pixels (aspect only); the document's when absent +## import.probe + +Read a model file without changing the document: {format, units_declared, units_guess, unit_guessed, up_axis, bounds: {min, max, size} in file units and size_m (the size in metres at units_guess), triangles, meshes, nodes, materials, textures, images_in_file (images stored inside the model), texture_slots, warnings}. + +- `path`: string; required; Model file to read +- `worker`: boolean; default true; STEP and IGES: also open the file with the CAD worker (bodies, groups, colours, size; a few seconds); false answers from the file's header alone + +Note: read-only. + +## import.start + +Start importing a model in the background with the file.import options and return {job}; the read and clean-up run on a worker, and the document changes (one undo step) on the first engine call after the worker finishes. Follow it with import.status. + +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `frame`: boolean; Frame the camera on the result (default: only when the document had no parts) +- `merge`: boolean; default false; Put everything the file holds under one group +- `name`: string; Name for the imported group (the original file name) +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y + +## import.status + +An import job's progress: {job, state (running, done, failed, cancelled, or stale when the document was replaced while it ran and nothing was applied), stage (reading, validating, welding, normals, instancing, placing, converting, then waiting while a history group is open, done), fraction (0 to 1 over the whole import), path, seconds, result (the file.import reply) when done, error {message, code} when failed}; without job, {jobs: [...]} for every job of this session. + +- `job`: ['integer', 'string']; Job id from import.start + +Note: read-only. + +## import.cancel + +Cancel a running import job; the document stays exactly as it was. Answers the job's status with cancelled true when it was still running. + +- `job`: ['integer', 'string']; required; Job id from import.start + +## file.reimport + +Read the source files of the given imported nodes again (every imported node when none): parts match by source.node, then by unique name, then by identical shape; matched parts keep their materials and transforms and take the new shape, new parts are added, parts gone from the file are hidden (marked source.missing), all as one undo step. Answers {matched, added, hidden, updated, files: [{path, matched, added, hidden, updated, warnings, report (the clean-up report of the re-read), error?}]}. + +- `nodes`: array of ['string', 'integer']; Imported nodes (or groups holding them) whose files to read again; every imported node when absent + +## cad.status + +Whether the CAD worker that opens STEP and IGES files is installed, where, and which release; probe starts it once to check. + +- `probe`: boolean; Start the worker and ask its version (takes a few seconds) + +Note: read-only. + +## scene.retessellate + +Rebuild the meshes of CAD parts from their kept STEP or IGES source at a new quality; each part keeps its id, name, placement, material, visibility and selection (scene.set_part_mesh); one undo step. + +- `nodes`: array of ['string', 'integer']; Parts or groups whose CAD parts are rebuilt; every CAD part when absent +- `quality`: value; required; Tessellation of STEP and IGES surfaces: a preset, or chord (fraction of the model's diagonal) and angle (degrees) + +## cad.parts + +Parts imported from STEP or IGES files, with their kept source, original path, quality, unit and up axis; nodes limits the answer to the parts under those nodes. + +- `nodes`: array of ['string', 'integer']; Parts or groups to look under; every part when absent + +Note: read-only. + +## handoff.inspect + +Tell what a file or folder another Form app wrote is (a GoF folder from FormSculpt or FormFabric, a FormSurface export folder of maps, a FormCAD, FormSculpt or FormFabric model) and what it holds, without changing the document. + +- `item`: ['string', 'integer']; For a GoF folder: the entry's file name, id or name; the newest entry meant for FormShot (target any or formshot) when omitted. +- `path`: string; required; Absolute path of the file or folder: a GoF folder (holding gof.json), a FormSurface export folder or one of its files, or a model file. +- `read`: boolean; default true; Read the model too, to count meshes, triangles, materials and textures. + +Note: read-only. + +## handoff.open + +Open what another Form app handed over, as a new document or added to the current one as one undo step; every node that arrives records source.app, source.path and source.node in its metadata, and FormSurface's maps arrive as texture references by role and colour space. + +- `as`: string (new | add); default "add"; new replaces the document with a new one holding the hand-off; add puts it into the current document as one undo step. +- `frame`: boolean; Frame the camera on the scene afterwards; by default when the document had no parts before, or for a new document. +- `item`: ['string', 'integer']; For a GoF folder: the entry's file name, id or name; the newest entry meant for FormShot (target any or formshot) when omitted. +- `path`: string; required; Absolute path of the file or folder: a GoF folder (holding gof.json), a FormSurface export folder or one of its files, or a model file. + +## material.types + +The material types (id, name, category, default parameters, the parameters each page shows with ranges and units, preset graph) and the measured metal colours. + +- no parameters + +Note: read-only. + +## material.node_kinds + +Material graph node kinds with their input and output sockets, defaults and settings, and the material inputs slots and graph outputs may drive. + +- no parameters + +Note: read-only. + +## material.program + +A material's compiled program: whether it is constant, the instructions, constants, outputs, textures it samples and its encoded size. + +- `key`: integer; range 1 to inf; Material (alias: material) +- `material`: integer; range 1 to inf; Same as key + +Note: read-only. + +## material.preview_maps + +Small base colour, roughness, metalness and normal maps of a material baked in uv space by the CPU interpreter (base64 PNG), for the window's raster material view. + +- `key`: integer; range 1 to inf; Material (alias: material) +- `material`: integer; range 1 to inf; Same as key +- `size`: integer; default 128; range 16 to 512; Map width and height in pixels + +Note: read-only. + +## material.get + +One material's full JSON (name, type, params, texture keys, slots, graph, labels), the document's texture references by key, and a summary of its compiled program. + +- `key`: integer; range 1 to inf; Material (alias: material) +- `material`: integer; range 1 to inf; Same as key + +Note: read-only. + +## material.labels + +A material's labels in print order, each with its image path and pixel size (null when unknown), for the window's label list. + +- `key`: integer; range 1 to inf; Material (alias: material) +- `material`: integer; range 1 to inf; Same as key + +Note: read-only. + +## library.list + +List material library presets by shelf (all, favorites, recent, user), category and search words, ranked when searching, with category counts and library warnings. + +- `category`: string; Category name (Metal) or folder (metal), any case +- `limit`: integer; range 1 to inf; At most this many presets +- `offset`: integer; default 0; range 0 to inf; Skip this many presets first +- `query`: string; Words matched against name, tags, category and type, case- and accent-insensitive; results ranked +- `shelf`: string (all | favorites | recent | user); default "all"; all, favorites, recent (most recent first) or user (the user's own presets) + +Note: read-only. + +## library.get + +One library preset: its file, its source and the material applying it would make. + +- `id`: string; required; Preset id (metal/gold-polished, user/my-red) + +Note: read-only. + +## library.favorite + +Mark or unmark a library preset as a favourite (kept in the user's library state). + +- `id`: string; required; Preset id +- `on`: boolean; default true; true marks it a favourite, false unmarks it + +## library.recent + +The library presets applied most recently, newest first. + +- no parameters + +Note: read-only. + +## library.apply + +Apply a library preset to parts as one undo step: builds its material (or reuses an identical one) and assigns it to the parts the scope reaches (part, group or same_material). + +- `id`: string; required; Preset id +- `nodes`: array of ['integer', 'string']; required; Node ids the preset is dropped on (parts or groups) +- `scope`: string (part | group | same_material); default "part"; part: the parts in the given nodes; group: every part of their parent group; same_material: every part wearing the same material as a given part + +## library.save + +Save a document material as one of the user's own library presets (user/). + +- `category`: string (Metal | Plastic | Glass | Paint | Rubber | Fabric | Wood | Stone | Ceramic | Liquid | Gem | Emissive); required; Library category +- `material`: integer; required; range 1 to inf; Material key of the document material to save +- `name`: string; Preset name (the material's name when absent) + +## library.remove + +Delete one of the user's own library presets; built-in presets cannot be removed. + +- `id`: string; required; Id of one of the user's own presets (user/...) + +## library.thumbnail + +A preset's thumbnail (the material ball under the studio, CPU path traced, cached as PNG by preset hash and size); a missing one is queued on a background worker. + +- `id`: string; required; Preset id +- `inline`: boolean; default false; Add the PNG as base64 when it is ready +- `retry`: boolean; default false; Queue again a thumbnail whose render failed +- `size`: integer; default 128; range 64 to 512; Width and height in pixels +- `timeout`: integer; default 120; range 1 to 600; Seconds to wait at most +- `wait`: boolean; default false; Wait for a missing thumbnail to be rendered (otherwise it is queued and the reply says queued) + +Note: read-only. + +## library.thumbnails + +Queue the thumbnails of several presets on the background worker, in the order given, and report each one's state. + +- `ids`: array of string; required; Preset ids, most wanted first +- `size`: integer; default 128; range 64 to 512; Width and height in pixels + +Note: read-only. + ## node.set_visible Same as scene.set_visible ({id, visible} -> {ids: [id], visible}). @@ -638,16 +945,30 @@ Same as file.new ({path?, title?, template?} unchanged). Same as file.open ({path} unchanged). -- `path`: string; required; A .fshot project or a model file +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `merge`: boolean; default false; Put everything the file holds under one group +- `name`: string; Name for the imported group (the original file name) +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y ## document.import Same as file.import ({path, name?, options?} unchanged). -- `frame`: boolean; Frame the camera on the result (default: only when the document was empty) +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `frame`: boolean; Frame the camera on the result (default: only when the document had no parts) +- `merge`: boolean; default false; Put everything the file holds under one group - `name`: string; Name for the imported group (the original file name) -- `options`: object; fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group -- `path`: string; required; Model file: glb, gltf, obj, stl or ply +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y ## document.save diff --git a/.claude/skills/formshot-harness/SKILL.md b/.claude/skills/formshot-harness/SKILL.md index b1f2464a..f43a3e5f 100644 --- a/.claude/skills/formshot-harness/SKILL.md +++ b/.claude/skills/formshot-harness/SKILL.md @@ -1,15 +1,15 @@ --- name: formshot-harness -description: "Guides work on formshot, the Form-family 3D product renderer by nodemode-ai: Rust engine workspace (fsh-*), CPU and GPU (wgpu, WGSL) path tracers, the live viewport (WebGL2 raster modes, the WebAssembly engine on WebGPU), layered materials, the .fshot project file, MCP tools, FastAPI service, Tauri desktop. Use whenever a task touches the document, commands, undo, the render snapshot, the BVH, BSDFs, sampling, tone mapping, glTF or OBJ import, the .fshot format or journal, the command registry or catalogue, the MCP endpoint or consent, the agent dock, the window shell, Home, the workspace, the service, the Tauri sidecar, doctor and notices runs, version bumps (0.x from 0.4.0), or any file under native/, frontend/src, backend/app, src-tauri or setup/. Enforces project laws (SEDO, zero DOM flicker, z-index tokens, no tests). Not for formsculpt or formsurface." +description: "Guides work on formshot, the Form-family 3D product renderer by nodemode-ai: Rust engine workspace (fsh-*), CPU and GPU (wgpu, WGSL) path tracers, the live viewport (WebGL2 raster modes, the WebAssembly engine on WebGPU), layered materials, the .fshot project file, MCP tools, FastAPI service, Tauri desktop. Use whenever a task touches the document, commands, undo, the render snapshot, the BVH, BSDFs, sampling, tone mapping, model import (glTF, OBJ, 3MF, FBX, STEP, IGES), hand-offs, material types, slots and graphs, the material library, the .fshot format or journal, the command registry or catalogue, the MCP endpoint or consent, the agent dock, the window shell, Home, the workspace, the service, the Tauri sidecar, doctor and notices runs, version bumps (0.x from 0.6.0), or any file under native/, frontend/src, backend/app, src-tauri or setup/. Enforces project laws (SEDO, zero DOM flicker, z-index tokens, no tests). Not for formsculpt or formsurface." license: Apache-2.0 metadata: nodemode.author: nodemode-ai - nodemode.pack-version: "0.4.0" + nodemode.pack-version: "0.6.0" --- # Formshot Harness -formshot is the Form family's 3D product renderer by nodemode-ai (Apache-2.0): open a model, drag materials onto parts, light it, watch a physically based picture converge, then render stills, animations and variants. It is modeled on its siblings formsurface (shell and service), formsculpt (launcher, setup and engine bridge) and formvis (the shared dock). Current state: v0.2.0, unreleased. The shell, the document and project file, the CPU path tracer and the command line render exist; everything else is planned with the version the plan gives it, and the sub-skills mark it planned. Since then the GPU path tracer (fsh-render-gpu, held to the CPU picture), device choice with a fallback to the CPU, the live viewport (WebGL2 raster modes, picking, gizmo, interaction regimes, an optional WebAssembly engine on WebGPU with a streamed fallback) and the engine-driven crash journal have landed. GPU work has run only on software drivers (lavapipe, SwiftShader, llvmpipe), and the path tracer in the window has not drawn a frame yet. Read the code before trusting a claim here. +formshot is the Form family's 3D product renderer by nodemode-ai (Apache-2.0): open a model, drag materials onto parts, light it, watch a physically based picture converge, then render stills, animations and variants. It is modeled on its siblings formsurface (shell and service), formsculpt (launcher, setup and engine bridge) and formvis (the shared dock). Current state: v0.2.0, unreleased. The shell, the document and project file, the CPU path tracer and the command line render exist; everything else is planned with the version the plan gives it, and the sub-skills mark it planned. Since then the GPU path tracer (fsh-render-gpu, held to the CPU picture), device choice with a fallback to the CPU, the live viewport (WebGL2 raster modes, picking, gizmo, interaction regimes, an optional WebAssembly engine on WebGPU with a streamed fallback) and the engine-driven crash journal have landed. GPU work has run only on software drivers (lavapipe, SwiftShader, llvmpipe), and the path tracer in the window has not drawn a frame yet. After that came import (3MF, FBX, background jobs, reimport, embedded textures), STEP and IGES through FormCAD's kernel worker (fsh-cad), family hand-offs, material types, texture slots, graphs compiled to a material program, and the material library; both path tracers run material programs with textures (loaded by `fsh-commands/src/textures.rs`), image labels, thin film and dispersion. Read the code before trusting a claim here. This pack exists so that an agent entering the repo cold edits the right layer, in the right order, under the project laws, and proves the result. @@ -21,8 +21,8 @@ formshot-harness/ references/evals.md three evaluations and the trigger list sub-skills/[skill-name]/SUB-SKILL.md engine-core scene-document cpu-tracer gpu-tracer materials io-formats - command-registry agent-substrate ui-shell viewport engine-service - desktop-shell verification + cad-and-handoffs material-library command-registry agent-substrate + ui-shell viewport engine-service desktop-shell verification ``` Sub-skill paths resolve as `sub-skills/[skill-name]/SUB-SKILL.md` from this folder. @@ -31,20 +31,22 @@ Sub-skill paths resolve as `sub-skills/[skill-name]/SUB-SKILL.md` from this fold | Area | Location | Role | | --- | --- | --- | -| Rust engine | `native/` (one Cargo workspace, edition 2021, all crates 0.4.0) | everything that knows about scenes, rays and pixels | +| Rust engine | `native/` (one Cargo workspace, edition 2021, all crates 0.6.0) | everything that knows about scenes, rays and pixels | | fsh-core | `native/crates/fsh-core` | maths, Transform, Ray, Aabb, Rgb in ACEScg, typed ids and document keys, units, the deterministic sampler, warps and MIS heuristics; std only | -| fsh-scene | `native/crates/fsh-scene` | the document, the command enum and its table, undo and redo with merge and groups, change levels, selection, `flatten()` to `RenderSnapshot` | +| fsh-scene | `native/crates/fsh-scene` | the document, the command enum and its table, undo and redo with merge and groups, change levels, selection, `flatten()` to `RenderSnapshot`; the 18 material types, texture slots, material graphs, the compiler to programs and the preview bake | | fsh-accel | `native/crates/fsh-accel` | two-level binned-SAH BVH, watertight triangle test, `Intersector` | -| fsh-materials | `native/crates/fsh-materials` | the layered surface BSDF (diffuse, GGX, coat, transmission, fuzz) with energy compensation tables | -| fsh-io | `native/crates/fsh-io` | glTF/GLB and OBJ readers to a raw scene, clean-up, PNG and HDR or EXR writers | -| fsh-format | `native/crates/fsh-format` | the `.fshot` stored ZIP, deterministic save, validated load, atomic write, the command journal and recovery | +| fsh-materials | `native/crates/fsh-materials` | the layered surface BSDF (diffuse, GGX, coat, transmission, fuzz) with energy compensation tables; thin film and dispersion (`film.rs`, `optics.rs`); the material program (25 opcodes, 24 the label projection), the texture sampler and mips, its interpreter, texture pixel types and the ten procedural patterns | +| fsh-io | `native/crates/fsh-io` | glTF/GLB, OBJ, STL, PLY, 3MF and FBX (ufbx, native only) readers to a raw scene with texture slots, clean-up with tangents, `probe`, the Form family hand-off readers (`family/`), PNG and HDR or EXR writers | +| fsh-cad | `native/crates/fsh-cad` | STEP and IGES through FormCAD's kernel worker (a child process, JSON lines): locate, client, quality, `.mesh` parsing, colours and shared shapes, file scans; native only | +| fsh-format | `native/crates/fsh-format` | the `.fshot` stored ZIP, deterministic save, validated load, atomic write, embedded textures named by SHA-256, kept CAD sources, the command journal and recovery | | fsh-render-cpu | `native/crates/fsh-render-cpu` | the CPU path tracer (the specification engine), progressive passes, develop, the a-trous denoiser | | fsh-render-gpu | `native/crates/fsh-render-gpu` | the GPU path tracer on wgpu 30: one WGSL megakernel, software BVH and ray-query traversal, refusals, bands, readback; held to fsh-render-cpu's picture (the planned-for-0.3.0 tracer, now built) | -| fsh-commands | `native/crates/fsh-commands` | the one catalogue (88 entries) and `dispatch(session, name, args)` over an engine session; device choice and the GPU fallback ladder, interaction regimes, render jobs and the render region, picking and framing, the crash journal | +| fsh-commands | `native/crates/fsh-commands` | the one catalogue (121 entries), the texture loader (`textures.rs`) and `dispatch(session, name, args)` over an engine session; device choice and the GPU fallback ladder, interaction regimes, render jobs and the render region, picking and framing, the crash journal; command groups in `src/ext/` (import with jobs and reimport, cad, handoff, materials, library with its thumbnail worker) | | fsh-cli | `native/crates/fsh-cli` | `formshot-engine`: render (`--device`), info, convert, devices, bench, catalogue, dispatch (`--journal`) over stdin JSON lines | | fsh-py, fsh-wasm | `native/crates/fsh-py`, `fsh-wasm` | PyO3 module `fsh_py` and the wasm-bindgen package (session, service mirror, `create_viewport` on WebGPU), both outside the default members | -| Frontend | `frontend/` (vanilla TypeScript, Vite, port 5300) | `src/shell/` frame, registry, menus, Home, settings, dock adapter; `src/ui/` workspace and viewport; `src/engine/` client, streamed render loop, `raster/` (WebGL2), `gpu/` (WebGPU engine), `pkg/` (built wasm, ignored); `src/dock/` shared dock | -| Backend | `backend/app/` (FastAPI, 127.0.0.1:8300) | window key and local guard, projects library, engine bridge (with the journal folder), render routes, mesh and snapshot byte routes, `/mcp`, consent, the agent bus | +| Frontend | `frontend/` (vanilla TypeScript, Vite, port 5300) | `src/shell/` frame, registry, menus, Home, settings, dock adapter; `src/ui/` workspace and viewport, `import/`, `cad/`, `handoff/`, the Material page (`pages/material.ts`, `material/`), the graph editor (`graph/`), the library panel (`library/`); `src/engine/` client, streamed render loop, `raster/` (WebGL2), `gpu/` (WebGPU engine), `pkg/` (built wasm, ignored); `src/dock/` shared dock | +| Backend | `backend/app/` (FastAPI, 127.0.0.1:8300) | window key and local guard, projects library, engine bridge (with the journal folder), render routes, mesh and snapshot byte routes, `/mcp`, consent, the agent bus; `routers/` imports (uploads, sweep), cad (worker fetch), handoff (watcher, offers), textures, library (thumbnails) | +| Material presets | `assets/library/` | 249 preset JSON files and the generated `materials/index.json`, bundled as a Tauri resource | | Sidecar entry | `backend/formshot_engine.py` | PyInstaller entry, frozen as `formshot-engine-backend` | | Desktop | `src-tauri/` (Tauri 2) | splash, sidecar start, window key, main window, `.fshot` association, updater | | Dispatcher | `./formshot`, `./build_app` and `setup/` | one script per task | @@ -53,10 +55,12 @@ Sub-skill paths resolve as `sub-skills/[skill-name]/SUB-SKILL.md` from this fold ``` fsh-core <- fsh-scene, fsh-accel, fsh-materials +fsh-scene -> fsh-materials (the program types; re-exported as fsh_scene::fsh_materials) fsh-io, fsh-format -> fsh-core, fsh-scene +fsh-cad -> fsh-core, fsh-io (and FormCAD's kernel worker as a child process, never linked) fsh-render-cpu -> fsh-core, fsh-scene, fsh-accel, fsh-materials (rayon) fsh-render-gpu -> fsh-core, fsh-scene, fsh-accel, fsh-materials, fsh-render-cpu (wgpu, bytemuck; pollster natively) -fsh-commands -> every crate above (fsh-render-gpu natively only) +fsh-commands -> every crate above (fsh-render-gpu and fsh-cad natively only) fsh-cli, fsh-py, fsh-wasm -> fsh-commands; fsh-cli also fsh-io; fsh-wasm on wasm32 also fsh-render-gpu (WebGPU) backend/app/engine.py -> fsh_py (Binding) or formshot-engine dispatch --journal (Process, JSON lines) backend/app/routers/mcp.py -> the engine catalogue, through consent @@ -95,8 +99,10 @@ These come from the dev-rules operating mode and apply to every sub-skill. | Nodes, meshes, materials as data, cameras, environment, commands, undo, merge, groups, selection, the render snapshot | `sub-skills/scene-document/SUB-SKILL.md` | | The BVH, the CPU path tracer, lights, sky, ground, camera rays, develop, tone maps, denoise, determinism | `sub-skills/cpu-tracer/SUB-SKILL.md` | | The GPU path tracer: WGSL modules, buffer layouts, traversal (BVH or ray queries), refusals, device choice and the CPU fallback, parity with the CPU, software Vulkan runs | `sub-skills/gpu-tracer/SUB-SKILL.md` | -| BSDF lobes, Fresnel, energy tables, layering | `sub-skills/materials/SUB-SKILL.md` | -| glTF/GLB, OBJ, PNG, HDR or EXR, the `.fshot` file, the journal and recovery | `sub-skills/io-formats/SUB-SKILL.md` | +| BSDF lobes, Fresnel, energy tables, layering; material types, texture slots, graphs and node kinds, the program and its opcodes, procedurals, texture filtering, preview maps | `sub-skills/materials/SUB-SKILL.md` | +| glTF/GLB, OBJ, STL, PLY, 3MF, FBX, import options, units, jobs, reimport, imported textures, PNG, HDR or EXR, the `.fshot` file, the journal and recovery | `sub-skills/io-formats/SUB-SKILL.md` | +| STEP and IGES, fsh-cad, the CAD worker and its fetch, retessellation, hand-offs from FormCAD, FormSculpt, FormSurface and FormFabric | `sub-skills/cad-and-handoffs/SUB-SKILL.md` | +| Material presets in `assets/library`, the `library.*` commands, thumbnails, the library panel | `sub-skills/material-library/SUB-SKILL.md` | | Adding or changing an engine command end to end | `sub-skills/command-registry/SUB-SKILL.md` | | MCP endpoint, stdio bridge, consent, agent configs, skills, the dock and its tabs | `sub-skills/agent-substrate/SUB-SKILL.md` | | Window shell, registry, menus, palette, shortcuts, Home, workspace, settings, tokens, icons, languages | `sub-skills/ui-shell/SUB-SKILL.md` | diff --git a/.claude/skills/formshot-harness/sub-skills/cad-and-handoffs/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/cad-and-handoffs/SUB-SKILL.md new file mode 100644 index 00000000..4f3e7a07 --- /dev/null +++ b/.claude/skills/formshot-harness/sub-skills/cad-and-handoffs/SUB-SKILL.md @@ -0,0 +1,37 @@ +--- +name: cad-and-handoffs +description: "Changes how formshot reads STEP and IGES through FormCAD's kernel worker (fsh-cad: locate, the JSON-lines client, quality presets, the .mesh file, colours and shared shapes, STEP and IGES file scans, probe), the CAD branch of import and jobs, kept sources, scene.retessellate and scene.set_part_mesh, the worker fetch (backend/app/routers/cad.py, setup/cad_worker, ./formshot cad), the CAD Import page and re-tessellate dialog, and hand-offs from FormCAD, FormSculpt, FormSurface and FormFabric (fsh_io::family, handoff.* commands, the watcher and consent prompt). Load for any CAD or hand-off change." +--- + +# CAD and Hand-offs + +## Purpose + +Own `native/crates/fsh-cad`, `native/crates/fsh-commands/src/ext/cad.rs` and `ext/handoff.rs`, `native/crates/fsh-io/src/family/`, `backend/app/routers/cad.py` and `handoff.py`, `setup/cad_worker`, and `frontend/src/ui/cad/` and `ui/handoff/`. Hands back a CAD or hand-off change that keeps the engine off the network, keeps part ids through retessellation, and asks the person before anything another program sent changes the document. + +## Preconditions + +STEP and IGES are read by FormCAD's kernel worker (OpenCascade 8.0.1, release `occt-8.0.1`), a child process speaking JSON lines (`hello`, `xde_read`, `tessellate`, `shutdown`; protocol 2), never linked. Its source and protocol are in FormCAD's `kernel/` folder; FormCAD is another repository, read-only from here. `docs/IMPORT.md` describes the user-facing behaviour; `native/HASHOUT_LOG.md` § fsh-cad and § fsh-commands, `backend/HASHOUT_LOG.md` and `frontend/HASHOUT_LOG.md` § CAD and hand-offs hold the decisions and what ran. Only Linux x86_64 has run. The worker sends no progress, no face colours, no IGES colours and no instance matrices; fsh-cad's `scan.rs` reads colours from the file and `read.rs` derives sharing by matching tessellations. + +## Procedure + +1. Read the logs above, then `fsh-cad/src/lib.rs` and the module you touch. +2. The engine never downloads. The worker is found by `FORMSHOT_CAD_WORKER`, beside the program, then `/formshot/workers//`; the service and `./formshot cad fetch` install it there after checking the pinned record (`RELEASE`, `RECORD_SHA256` in cad.py), `SHA256SUMS` and every file. A new worker release changes those two constants and nothing else. +3. Every worker call goes through `Worker::call` with a timeout and the `Watch`; cancel and timeout kill the child. Worker starts wait `fsh_cad::hello_timeout()` (`FORMSHOT_CAD_HELLO_TIMEOUT`, 120 s by default). The window learns which parts are CAD from `cad.parts`, not from node metadata in a snapshot; a save writes only the sources some part names. Keep `fsh-cad` out of the wasm32 tree (fsh-commands depends on it natively only). +4. CAD reads produce a `fsh_io::RawScene` in metres, Z up, and go through the shared clean-up with instancing off; nodes carry `source.path`, `source.node`, and parts `source.cad`, `cad.mesh`, `cad.quality`, `cad.unit`, `cad.up`. Keep `Engine::import`'s CAD branch at its top and the job path in `ext/import/jobs.rs`. +5. Retessellation and re-import swap meshes with `mesh.add` plus `scene.set_part_mesh`, so part ids, materials, selection and shared meshes survive; never rebuild a part. +6. Kept sources (`fshot:sources/.`, at most 64 MiB) live in `Preserved::sources` and in the session folder; a change keeps saves without sources byte-identical to older ones. +7. Hand-offs: readers in `fsh_io::family` recognise what each app writes (GoF manifests, FormSurface map names and templates, writers' generator lines). Anything that arrives on its own is held by the service and offered in the window (deny, once, always per app); only the window's own choice or an agent under MCP consent opens it. No URL scheme, no new file association. A hand-off is one undo step and records `source.app` and the other `source.*` keys. +8. FormCAD, FormSculpt, FormSurface and FormFabric are not edited from here; a missing feature on their side is written down as an ask in the log. + +## Gate + +Done when `cargo clippy -p fsh-cad -p fsh-commands --all-targets -- -D warnings` is clean and `cargo check --target wasm32-unknown-unknown -p fsh-commands` passes; with the real worker fetched into a scratch `FORMSHOT_CACHE`, a STEP and an IGES sample imported through `formshot-engine dispatch` (and through `import.start` with a cancel), saved, reopened and resaved identically, and retessellated with part ids unchanged and undo exact; a hand-off change ran `handoff.inspect` and `handoff.open` on real exports of the sending app, and the prompt was seen in a browser. + +## Hands back + +The samples and their licences, triangle counts per quality, timings, whether the real worker or a stand-in answered, and what was not run (platforms, Tauri). + +## Owned resources + +None bundled. Related: `sub-skills/io-formats/SUB-SKILL.md`, `sub-skills/engine-service/SUB-SKILL.md`, `sub-skills/ui-shell/SUB-SKILL.md`. diff --git a/.claude/skills/formshot-harness/sub-skills/command-registry/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/command-registry/SUB-SKILL.md index b7ddc21e..092d1426 100644 --- a/.claude/skills/formshot-harness/sub-skills/command-registry/SUB-SKILL.md +++ b/.claude/skills/formshot-harness/sub-skills/command-registry/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: command-registry -description: "Adds or changes a formshot engine command end to end: the fsh-scene command table or an fsh-commands session command, its JSON schema and change level, the catalogue, dispatch through formshot-engine and fsh_py, the MCP tool list, the palette's engine. entries, agents sync and docs. Load when adding a tool, a render or document command, a menu item that runs the engine, or changing dispatch." +description: "Adds or changes a formshot engine command end to end: the fsh-scene command table, an fsh-commands session command or a command group module in fsh-commands/src/ext, its JSON schema and change level, the catalogue, dispatch through formshot-engine and fsh_py, the MCP tool list, the palette's engine. entries, agents sync and docs. Load when adding a tool, a render or document command, a menu item that runs the engine, or changing dispatch." --- # Command Registry @@ -11,11 +11,12 @@ Own `fsh-commands`, the single source of truth for every engine action. One regi ## Preconditions -State at 0.2.0: document commands are declared in `fsh-scene`'s `commands!` table; session commands (documents, rendering, history) in `fsh-commands`. Read both before adding one. The catalogue now has 88 entries (39 document, 38 engine, 11 aliases), including the view group (`view.pick`, `view.frame`, `view.bounds`), `scene.meshes`, `scene.mesh_data`, the render device, viewport and region commands and `file.snapshot`, `file.recover_list` and `file.recover`, plus a top-level `envelope` section: every `formshot-engine dispatch` reply carries `meta: {revision, content_revision}`. After adding a command, run `./formshot agents sync`. Window-only commands (`terminal.*`, `chat.*` and the rest) live on the service's bus and never reach the engine. +State at 0.2.0: document commands are declared in `fsh-scene`'s `commands!` table; session commands (documents, rendering, history) in `fsh-commands`. Read both before adding one. The catalogue now has 88 entries (39 document, 38 engine, 11 aliases), including the view group (`view.pick`, `view.frame`, `view.bounds`), `scene.meshes`, `scene.mesh_data`, the render device, viewport and region commands and `file.snapshot`, `file.recover_list` and `file.recover`, plus a top-level `envelope` section: every `formshot-engine dispatch` reply carries `meta: {revision, content_revision}`. After adding a command, run `./formshot agents sync`. The catalogue now has 121 entries (47 document, 38 engine, 25 ext, 11 aliases): command groups added since live one module each in `native/crates/fsh-commands/src/ext/` (`import.rs` with `import/`, `cad.rs`, `handoff.rs`, `materials.rs`, `library.rs` with `library/`), each listing `ExtCommand {name, description, level, mutates, read_only, schema}` in `COMMANDS` and answering in `dispatch` (`None` for other names); `ext::commands()` adds them to the catalogue and `Engine::dispatch_value` routes them. Window-only commands (`terminal.*`, `chat.*` and the rest) live on the service's bus and never reach the engine. ## Procedure -1. Pick the dotted name in an existing group (scene, mesh, material, texture, camera, environment, ground, image, render, units, document, history). The MCP tool name is the same dotted name. +1. Pick the dotted name in an existing group (scene, mesh, material, texture, camera, environment, ground, image, render, units, document, history, import, cad, handoff, library). The MCP tool name is the same dotted name. A command that changes the document as data belongs in `fsh-scene`'s table (undo, journal, merge); a read-only or session-level command of a group goes in that group's `src/ext/` module; a new group gets a new module, reserved as an empty file first when several people work at once, and a line in `ext/mod.rs`'s `commands()` and `dispatch()`. +1a. An ext module reaches the session only through the `pub(crate)` helpers of `engine.rs` (`changed`, `refresh_render`, `import`, `install_editor`, the `State` fields, `note`, `note_begin`, `note_end`, `note_sources`); a command that changes the document runs Editor commands inside them, so it stays one undo step and is journalled. Long work runs on a thread without the session lock and applies on a later dispatch, as `ext/import/jobs.rs` does. 2. Define the args struct with serde; give each field a one-line description so the schema explains itself. 3. Give the highest change level the command can produce; the window refreshes and the renderer restarts from it. 4. Mark read-only commands so the catalogue carries `annotations.readOnlyHint`; the service skips the consent prompt only for those. diff --git a/.claude/skills/formshot-harness/sub-skills/cpu-tracer/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/cpu-tracer/SUB-SKILL.md index a438e2d5..b736e685 100644 --- a/.claude/skills/formshot-harness/sub-skills/cpu-tracer/SUB-SKILL.md +++ b/.claude/skills/formshot-harness/sub-skills/cpu-tracer/SUB-SKILL.md @@ -23,6 +23,7 @@ State at 0.2.0: fsh-accel is built and measured (about 1.6 Mrays/s on 2 threads 6. A change that alters pictures gets a CHANGELOG line written for a person ("glass edges are less noisy"), not a formula. 7. A new draw, light, table or integrator step is recorded in `src/spec.rs` (`DRAW_ORDER` and the exported tables), then ported to the GPU through `sub-skills/gpu-tracer/SUB-SKILL.md`; until it is ported, the GPU engine must refuse the feature so the job stays on the CPU. 8. Never call `std::time::Instant` or spawn threads on a path that runs on wasm32: use the renderer's clock and `Execution::Inline`. +9. At a hit the order is fixed and the GPU copies it: shaded inputs (the program through `Geometry::shade` with the ray-cone footprint, else the constant `program.base` with the tint), regularisation, opacity, then the dispersion hero channel on the evaluated ior, then `Bsdf::new_optics` when the instance has a film. Constant materials never run the interpreter and must render byte-identically to earlier builds. Textures reach the renderer only through `Renderer::set_textures`. ## Gate diff --git a/.claude/skills/formshot-harness/sub-skills/engine-service/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/engine-service/SUB-SKILL.md index 9e7fe95e..3d7e0ad0 100644 --- a/.claude/skills/formshot-harness/sub-skills/engine-service/SUB-SKILL.md +++ b/.claude/skills/formshot-harness/sub-skills/engine-service/SUB-SKILL.md @@ -11,7 +11,7 @@ Own `backend/`. The service never opens a `.fshot` itself and never fakes an eng ## Preconditions -State at 0.2.0: the service ran here with its health, window key, projects, terminals, consent and MCP routes, and against a stand-in engine for the bridge. Not run: the `fsh_py` binding transport, Windows, macOS and the frozen build. Since then: `GET /api/engine/mesh/{key}` (FSHM v1 binary) and `GET /api/engine/snapshot` (`.fshot` bytes with `X-Formshot-Content-Revision`) serve the viewport, the engine keeps its crash journal in `/sessions`, and stored Rendering preferences are re-sent at each engine session start; all ran against the release engine. +State at 0.2.0: the service ran here with its health, window key, projects, terminals, consent and MCP routes, and against a stand-in engine for the bridge. Not run: the `fsh_py` binding transport, Windows, macOS and the frozen build. Since then: `GET /api/engine/mesh/{key}` (FSHM v1 binary) and `GET /api/engine/snapshot` (`.fshot` bytes with `X-Formshot-Content-Revision`) serve the viewport, the engine keeps its crash journal in `/sessions`, and stored Rendering preferences are re-sent at each engine session start; all ran against the release engine. Then came `app/routers/imports.py` (model uploads to `/.imports//` with its own streaming multipart parser, folder scan, the 24-hour sweep in the router's lifespan), `cad.py` (the CAD worker's status and its download checked against a record pinned by SHA-256, with a CLI `main()` behind `./formshot cad`), `handoff.py` (the watcher of the GoF and FormSurface folders, held offers, per-app choices in `/handoff.json`), `textures.py` (slot image uploads, reusing the import parser) and `library.py` (thumbnails served from the engine's cache, polling the engine instead of holding its lock), and optional uv0 and tangent sections in the mesh block (flags in the version word's high half). ## Procedure @@ -21,6 +21,9 @@ State at 0.2.0: the service ran here with its health, window key, projects, term 4. Engine errors map as the bridge does: refused 422, crashed 502, not built 503, timeout 504, each with a sentence. Never answer with made-up data. 5. Settings and environment names: `FORMSHOT_` first, then `FSH_`. 6. Requirements are pinned; a new package gets a row in `NOTICE.md` and is checked by `./formshot notices --check`. +6a. Uploads go through the shared streaming parser in `routers/imports.py` (`receive`, `clean_name`); python-multipart is not a dependency. Anything another program can send (hand-offs) is held for the person's answer in the window, as outside agents are. The engine never touches the network: downloads (the CAD worker) happen here, hash-checked, and reach the engine as files. +6b. Never hold the engine lock for a long engine job: queue it and poll, as the thumbnail route does. +6c. A route that dispatches engine commands on behalf of an outside caller (an agent, MCP) uses `Engine.dispatch_outside(name, args, source)`, which publishes the matching change event so the window follows the edit. 7. Byte routes (meshes, snapshots, frames) answer `application/octet-stream` or the image type with `Cache-Control: no-store`, take the window key or a one-use ticket, and check what the engine sent (magic numbers, base64) before answering. ## Gate diff --git a/.claude/skills/formshot-harness/sub-skills/gpu-tracer/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/gpu-tracer/SUB-SKILL.md index 1bd0c9b0..c8e93e4e 100644 --- a/.claude/skills/formshot-harness/sub-skills/gpu-tracer/SUB-SKILL.md +++ b/.claude/skills/formshot-harness/sub-skills/gpu-tracer/SUB-SKILL.md @@ -21,6 +21,7 @@ State now: the megakernel renders everything the CPU path renders, with parity w 4. Materials stay data: a material edit must never change an override constant or compile a kernel. Run-time switches (adaptive sampling, the render region) are Frame flags, not override constants, so toggling them never compiles; the override constants are only lamps, catcher and normals. On WebAssembly a scene that no compiled kernel covers fails with a `Shader` error until the caller awaits `specialise_async()`. 5. Refusals: a scene the GPU cannot hold or would draw differently gets a `Refusals` entry (Limit or Feature) with a plain message, so the engine sends it to the CPU with that note. 6. Develop on software drivers: `VK_ICD_FILENAMES= formshot-engine devices`, then `render sample out.png --device gpu` and `bench`. `RendererOptions::shader_dir` loads WGSL from a folder without rebuilding. +6a. Material programs, textures and optics: the material record is 160 bytes (program offset and `MAT_PROGRAM`, then thin film and dispersion), Frame 304 (`textures`), vertices are strided 16-byte attribute slots (normal, uv pairs, tangent by instance flags), and textures and program blobs live in `tables`. A new opcode lands in fsh-materials first, then in `program.wgsl` and `GPU_OPCODES`; a new procedural in `procedural.wgsl` and `GPU_PROCEDURALS`; the hit context and ray cone must stay exactly the CPU's (`Geometry::hit_context`). Compare interpreted values with `Program::evaluate` over many random hit contexts, not only pictures. 7. Rationale, measurements and what did not run go to `native/HASHOUT_LOG.md` § fsh-render-gpu. ## Gate diff --git a/.claude/skills/formshot-harness/sub-skills/io-formats/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/io-formats/SUB-SKILL.md index 8aecf182..117742e1 100644 --- a/.claude/skills/formshot-harness/sub-skills/io-formats/SUB-SKILL.md +++ b/.claude/skills/formshot-harness/sub-skills/io-formats/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: io-formats -description: "Changes formshot's file handling: fsh-io (glTF/GLB, OBJ with MTL, STL and PLY readers to a raw scene, the clean-up pass, a GLB writer, PNG and HDR readers and writers, an EXR writer) and fsh-format (the .fshot stored ZIP with manifest, scene JSON, material JSON and binary meshes, deterministic save, validated load, atomic write, the JSONL command journal and recovery). Load for any import, export or project file change." +description: "Changes formshot's file handling: fsh-io (glTF/GLB, OBJ with MTL, STL, PLY, 3MF and FBX readers to a raw scene with texture slots, the clean-up pass with tangents, probe, a GLB writer, PNG and HDR readers and writers, an EXR writer), import options, jobs, reimport and texture embedding in fsh-commands/src/ext/import and fsh-format (the .fshot stored ZIP with manifest, scene JSON, material JSON and binary meshes, deterministic save, validated load, atomic write, the JSONL command journal and recovery). Load for any import, export or project file change." --- # IO Formats @@ -11,7 +11,7 @@ Own the bytes that enter and leave the engine. Hands back a format change that o ## Preconditions -State at 0.2.0: the `.fshot` layout is described in `docs/FILE-FORMAT.md` when that file is present, and in `native/HASHOUT_LOG.md` § fsh-format. glTF/GLB, OBJ, STL and PLY readers exist in fsh-io (`native/HASHOUT_LOG.md` § fsh-io); more importers (3MF, FBX) are planned for 0.5.0 to 0.6.0, STEP and IGES through FormCAD's kernel worker for the same turn, and image and scene exporters for later turns. +State at 0.2.0: the `.fshot` layout is described in `docs/FILE-FORMAT.md` when that file is present, and in `native/HASHOUT_LOG.md` § fsh-format. glTF/GLB, OBJ, STL and PLY readers exist in fsh-io (`native/HASHOUT_LOG.md` § fsh-io); image and scene exporters are planned for later turns. Since then: 3MF (roxmltree and an own ZIP reader) and FBX (ufbx, native only) readers, ear clipping, MikkTSpace tangents in `RawScene::tangents`, instancing under rotation and mirroring, unit guesses with a confidence, `probe`, reader texture slots in the side tables `RawScene::extras` and `RawScene::images`, uvs stored v up by every reader; import options, jobs, re-import and texture embedding in `fsh-commands/src/ext/import/`; texture members named by SHA-256 (old names still load) and kept CAD sources under `sources/` in fsh-format. `docs/IMPORT.md` and `docs/FILE-FORMAT.md` describe them; STEP and IGES belong to `sub-skills/cad-and-handoffs/SUB-SKILL.md`. ## Procedure @@ -21,10 +21,14 @@ State at 0.2.0: the `.fshot` layout is described in `docs/FILE-FORMAT.md` when t 4. `.fshot` saves are stored (no compression), entries in a fixed order with fixed timestamps, so identical documents give identical bytes. A new entry gets a manifest version bump and a loader that still opens the older version. 5. Writes go to a temporary file and are renamed into place. Loads validate everything and refuse with a readable error; they never panic. 6. Never read outside the file's own folder for side files. +7. `RawMesh`, `RawMaterial` and `RawTexture` are built by full struct literals in fsh-commands/src/export.rs and fsh-io/src/family/handoff.rs; put new reader data in a side table on `RawScene` (as `tangents`, `extras` and `images` are) rather than a new field, or change every literal in the same change. +8. Uvs are stored v up (the image's first row at v = 1): a new reader converts on read, `write_glb` converts back. Tangents follow the stored uvs. +9. An import must stay one undo step and must not touch the document before `apply`: reading, cleaning, converting and embedding happen in `prepare`, which also runs on a job thread. Every reader polls `Watch` so cancel works. +10. Add a new material field to `fsh_scene::MATERIAL_FIELDS`, or fsh-format reloads it as a preserved unknown field. A new member kind keeps older files byte-identical on resave and says in `docs/FILE-FORMAT.md` what older engines do with it. ## Gate -Done when `cargo check` is clean for the touched crates, a save, reopen and save of a sample gave identical bytes (compare hashes), and an older sample still opened. +Done when `cargo check` is clean for the touched crates (and `--target wasm32-unknown-unknown` for fsh-io, fsh-format and fsh-commands), a save, reopen and save of a sample gave identical bytes (compare hashes), an older sample still opened, and for a reader change every file of a corpus kept outside the repository imported, saved, was moved to a fresh folder, reopened with its textures and resaved identically, and truncated or bit-flipped copies gave errors, not panics. ## Hands back diff --git a/.claude/skills/formshot-harness/sub-skills/material-library/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/material-library/SUB-SKILL.md new file mode 100644 index 00000000..443e5cb6 --- /dev/null +++ b/.claude/skills/formshot-harness/sub-skills/material-library/SUB-SKILL.md @@ -0,0 +1,37 @@ +--- +name: material-library +description: "Changes formshot's material library: the preset files and generated index in assets/library (format 1, measured and published sources, licences), the library.* engine commands in fsh-commands/src/ext/library (locating the library, strict reading, search, apply with scopes and reuse, favourites, recent, user presets, the CPU thumbnail worker and its cache), the thumbnail routes in backend/app/routers/library.py, the Tauri bundle resource, and the Library panel in frontend/src/ui/library. Load for any preset, library command, thumbnail or panel change." +--- + +# Material Library + +## Purpose + +Own `assets/library/`, `native/crates/fsh-commands/src/ext/library.rs` and `ext/library/`, `backend/app/routers/library.py`, the library entry of `src-tauri/tauri.conf.json`'s bundle resources, and `frontend/src/ui/library.ts` with `frontend/src/ui/library/`. Hands back a library where every number is traceable to a source, a bad file is a warning and never a crash, and applying a preset is one undo step. + +## Preconditions + +`docs/LIBRARY.md` describes the format, sources, commands, thumbnails and panel; `assets/library/README.md` the sources and how numbers were made; `native/HASHOUT_LOG.md` § fsh-commands (library entries), `backend/HASHOUT_LOG.md` and `frontend/HASHOUT_LOG.md` § The material library the decisions and what ran. 249 presets in twelve categories. Presets use the material types of `docs/MATERIALS.md`; wood, stone and metallic paint need their type graph, which the path tracers do not evaluate yet, so their thumbnails show the average tone. + +## Procedure + +1. Read the docs above, then the file you touch. +2. Presets are data, not UI strings: names are not translated. Every `params` key is a `SurfaceParams` field, colours are ACEScg, numbers rounded to 4 places, `emission_color` normalised to luminance 1. Every number is covered by `source.kind` (measured or published, with `reference` and `urls`) or listed in `source.authored` with the reasoning in `notes`. +3. Data: CC0 or public facts only (refractiveindex.info is CC0; cite the original paper too). Never take a preset, name, description or number from another renderer's library. Presets are Apache-2.0, our own work. +4. Ids `/` are permanent: favourites, thumbnails and documents refer to them. Add, never rename. +5. The index is generated; a hand-added preset needs its entry with the file's SHA-256 in category then name order, and the tree stays under 2 MB. +6. Commands are ext commands in `ext/library/`; apply builds defaults, then the type preset, then `params`, then the tuned type graph, reuses an identical material, and runs inside one history group at Region level. Reading stays strict and failures become warnings in `library.list`. +7. Thumbnails render on the background worker with their own document and renderer; never block dispatch or hold the session lock for a render (the service polls). Change the thumbnail scene only with a new `ball-N` look string in `thumbs.rs`, so old pictures are dropped. +8. The panel keeps a fixed pool of tile nodes, requests thumbnails only for tiles in view, and uses `preset.*` window command ids (Home owns `library.*`). + +## Gate + +Done when the library validates (every file parses, ids, categories, types, params and tags valid, the index lists every file with its hash), `library.list` over `FORMSHOT_LIBRARY=assets/library` through `formshot-engine dispatch` answers 249 (or the new count) with no warnings, a changed preset was applied, undone and its thumbnail looked at, `cargo clippy -p fsh-commands --all-targets -- -D warnings` is clean, and a panel change was seen in a browser with no layout shift. + +## Hands back + +The presets touched with their sources, the list and apply output, the thumbnails looked at, and what was not run (the desktop bundle, Tauri). + +## Owned resources + +None bundled. Related: `sub-skills/materials/SUB-SKILL.md`, `sub-skills/command-registry/SUB-SKILL.md`, `sub-skills/ui-shell/SUB-SKILL.md`. diff --git a/.claude/skills/formshot-harness/sub-skills/materials/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/materials/SUB-SKILL.md index 8d6d0dc1..00f9ef1a 100644 --- a/.claude/skills/formshot-harness/sub-skills/materials/SUB-SKILL.md +++ b/.claude/skills/formshot-harness/sub-skills/materials/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: materials -description: "Changes fsh-materials, formshot's layered surface BSDF: SurfaceInputs, EON diffuse, anisotropic GGX with visible-normal sampling, dielectric and F82-tint conductor Fresnel, coat, rough transmission, fuzz, lobe selection, and the directional-albedo tables for energy compensation. Load for any change to how a surface reflects or transmits light." +description: "Changes fsh-materials, formshot's layered surface BSDF: SurfaceInputs, EON diffuse, anisotropic GGX with visible-normal sampling, dielectric and F82-tint conductor Fresnel, coat, rough transmission, fuzz, lobe selection, and the directional-albedo tables for energy compensation; and the material system: types, texture slots, graphs and node kinds, the compiler, the material program and its interpreter, procedural patterns, texture filtering and preview maps. Load for any change to how a surface reflects or transmits light or how a material is described or compiled." --- # Materials @@ -11,7 +11,7 @@ Own `native/crates/fsh-materials`. One surface model, with field meanings that f ## Preconditions -State at 0.2.0: built and measured with a scratch program (white furnace 0.98 to 1.07 across nine presets, sample against pdf agreement within 0.003). Not built: thin film, subsurface, dispersion, coat darkening, measured metals (planned for 0.9.0 to 0.10.0 with advanced transport). Material presets and the node graph are planned for 0.5.0 to 0.6.0. +State at 0.2.0: built and measured with a scratch program (white furnace 0.98 to 1.07 across nine presets, sample against pdf agreement within 0.003). Not built: subsurface and coat darkening (planned with advanced transport). Thin film (Belcour and Barla's Airy reflectance, `film.rs`) and dispersion (a Cauchy law and one hero colour channel per path, `optics.rs`) are built, per material and constant, applied after the program in both tracers. Since then the material system landed, described in `docs/MATERIALS.md`: 18 types as presets of the one model (`fsh-scene/src/types.rs`), texture slots (`slots.rs`), graphs with 18 node kinds (`graph.rs`), the compiler (`compile.rs`) to a `Program` of 24 opcodes (`fsh-materials/src/program.rs`), the interpreter (`interp.rs`), texture pixel types and the `TextureSampler` seam (`texture.rs`), ten procedural patterns in Rust (`procedural/`) and WGSL (`fsh-render-gpu/src/shaders/procedural.wgsl`, not yet included in the kernel), and the preview bake (`preview.rs`). Labels (`fsh-scene/src/labels.rs`, opcode 24) compile after slots and graph. Both tracers run programs: the CPU through `Program::evaluate` in fsh-render-cpu's `Geometry::shade`, the GPU through `program.wgsl` with textures packed by `texpack.rs`; textures are decoded by `fsh_io::decode_image` and loaded by `fsh-commands/src/textures.rs`, sampled by `sample.rs` and `texture.wgsl` identically. `material.preview_maps` samples the session's texture cache too. Images named by path in commands are embedded into the project when the command runs (`textures::embed_command_path`); program-changed normals are clamped in both integrators (`clamp_bent_normal`); procedural Normal outputs compile through a NormalMap step. ## Procedure @@ -21,10 +21,14 @@ State at 0.2.0: built and measured with a scratch program (white furnace 0.98 to 4. Tables are computed by our own integration at first use; never paste a published table. Keep them deterministic for any thread count. 5. `eval`, `sample` and `pdf` must not allocate. 6. `fsh-scene`'s `SurfaceParams` holds the stored fields; a new stored field changes the document, so load `sub-skills/scene-document/SUB-SKILL.md` too. +7. A constant material must stay a constant program whose `base` is bit-identical to `surface_inputs(params, None)`: the zero-cost path and the identity of older renders depend on it. +8. A new opcode changes `Op`, the encoder, the disassembler, `fold` if it is pure, the interpreter, and later the WGSL interpreter; keep every integer in the encoded blob below 2^24 (the GPU reads it from a float buffer) and update `docs/MATERIALS.md`. +9. A new node kind adds a `GraphOp`, its entry in `graph_kinds()` (sockets, defaults, settings), its compile arm and conversion rules; a procedural kind adds the Rust body and the WGSL port with the same pcg3d hashing, checked against each other on a software GPU (floats within 1e-4) and anti-aliased by the footprint. +10. A type's defaults are data the library builds on: change a type only with `docs/MATERIALS.md` and check that the presets of that type (`assets/library`) still mean what they say. ## Gate -Done when `cargo check -p fsh-materials` is clean and a scratch program outside the repo printed the white furnace range and the sample against pdf agreement for the changed lobe. +Done when `cargo check -p fsh-materials` is clean and a scratch program outside the repo printed the white furnace range and the sample against pdf agreement for the changed lobe. For the material system: every type creates, compiles and round-trips; old projects load and resave byte-identically and render byte-identically; `material.program` disassembles the changed case; a procedural change compares CPU and WGSL over thousands of points. ## Hands back diff --git a/.claude/skills/formshot-harness/sub-skills/ui-shell/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/ui-shell/SUB-SKILL.md index 2ed2e937..f90d6d11 100644 --- a/.claude/skills/formshot-harness/sub-skills/ui-shell/SUB-SKILL.md +++ b/.claude/skills/formshot-harness/sub-skills/ui-shell/SUB-SKILL.md @@ -11,7 +11,7 @@ Own `frontend/` outside the viewport. The viewport itself (raster modes, picking ## Preconditions -State at 0.2.0: the frame, Home, the workspace, menus, Preferences and the dock build and type-check; the workspace ran in headless Chrome against a stand-in engine. Planned: the WebGPU viewport with solid, wireframe and material preview modes (0.4.0), the material library contents (0.5.0 to 0.6.0). Since then the viewport's modes landed (raster in WebGL2, the WebGPU engine optional and falling back to streamed frames), Preferences > Rendering gained the device block, Viewport quality and Adaptive sampling, and the `gpuview` i18n namespace was added beside `workspace`. +State at 0.2.0: the frame, Home, the workspace, menus, Preferences and the dock build and type-check; the workspace ran in headless Chrome against a stand-in engine. Planned: the WebGPU viewport with solid, wireframe and material preview modes (0.4.0), the material library contents (0.5.0 to 0.6.0). Since then the viewport's modes landed (raster in WebGL2, the WebGPU engine optional and falling back to streamed frames), Preferences > Rendering gained the device block, Viewport quality and Adaptive sampling, and the `gpuview` i18n namespace was added beside `workspace`. Then came the modules `import` (`src/ui/import/`: the import sheet, uploads, drops, launch opens), `handoff` and `cad` (entries in `src/modules.ts`), the Material inspector page (`src/ui/pages/material.ts` over `src/ui/material/`), the graph editor window (`src/ui/graph/`), the virtual-grid library panel (`src/ui/library/`), and the namespaces `import`, `handoff`, `cad`, `material`, `graph` and `library` (with English placeholders until translated; `labels` is reserved by the stub `src/ui/labels/index.ts`). ## Procedure @@ -23,6 +23,9 @@ State at 0.2.0: the frame, Home, the workspace, menus, Preferences and the dock 6. Icons are inline currentColor SVG in `src/shell/icons.ts`; no icon library. 7. A new string goes into the module's `src/i18n/modules//strings.json` and every language table, then `./formshot i18n check`. 8. Engine calls go through `src/engine/client.ts`; it never touches the DOM. Controls whose command is missing are disabled with the reason as tooltip. +9. A command id another module already registered (the workspace's `file.import`) is taken over in place through `getCommand(id)`, never registered twice (the registry throws). Home owns the `library.*` window ids, so the material library's are `preset.*`. +10. Edits that drag send live commands at most once per frame and close with `history.barrier` or a `history.begin_group`/`end_group` pair, so a drag is one undo step. Overlays (sheets, prompts, the graph window, drag hints) live in `#overlay-root` with a `--z-*` token and reserve their full size before the first paint; long lists are virtual (a fixed node pool rebound in place). +11. Read engine data through engine commands, never by unpacking the project snapshot: the Material page and the graph editor use `material.get`, the CAD module `cad.parts`. A mutating dispatch that answers `change: none` already schedules a summary refresh (one hook in `src/shell/commands.ts`), and outside edits arrive as service events; do not add per-module refresh workarounds. A value drag on a graph sends `material.set_graph {merge: true}` and ends with `history.barrier`. ## Gate diff --git a/.claude/skills/formshot-harness/sub-skills/verification/SUB-SKILL.md b/.claude/skills/formshot-harness/sub-skills/verification/SUB-SKILL.md index c3536b15..55e5f56a 100644 --- a/.claude/skills/formshot-harness/sub-skills/verification/SUB-SKILL.md +++ b/.claude/skills/formshot-harness/sub-skills/verification/SUB-SKILL.md @@ -20,6 +20,7 @@ FormShot has no test suites, by rule, until the owner asks in words. Checks are 3. Renders: `./formshot render sample.glb out.png --samples 256` with `--threads 1` and `--threads 2`; the two files must be identical (compare hashes). 3a. GPU: without a graphics card, point `VK_ICD_FILENAMES` at Mesa's lavapipe ICD file; `./formshot cli devices` must list the adapter, and `./formshot cli bench` must show every GPU within 0.005 mean absolute difference of the CPU (`mad_vs_cpu` in `--json`). Say which drivers ran: software Vulkan and GL prove parity, not speed, and say nothing about Metal, Direct3D 12 or ray-tracing hardware. 3b. Browser engine: `./formshot engine wasm`, then `vite build` with and without `frontend/src/engine/pkg`; in headless Chromium with SwiftShader WebGPU, report whether the kernel compiled or the guard fell back, and read pictures back (a WebGPU canvas is not composited headless). +3c. Import and materials: an import corpus kept outside the repository (licences recorded; never committed) imported, saved, moved to a fresh folder, reopened with every `fshot:` texture present and resaved byte-identically; an older project resaved byte-identically; `material.program` on the changed materials. STEP and IGES need the CAD worker (`./formshot cad fetch` into a scratch `FORMSHOT_CACHE`); say whether the real worker or a stand-in answered. Library: `library.list` without warnings on `assets/library` and a thumbnail looked at. 4. Window: in `frontend/`, `npx tsc --noEmit` and `npm run build`; load the page and watch for console errors. 5. Throttled DOM check: observe mutations on the shell while idle and while the render converges. Expected: no unexpected node churn, no flash, no layout shift. 6. Kit: `./formshot i18n check`, `./formshot notices --check`, `./formshot agents check`. diff --git a/.claude/skills/formshot-rendering/references/tools.md b/.claude/skills/formshot-rendering/references/tools.md index 648e9f75..bb8e5f14 100644 --- a/.claude/skills/formshot-rendering/references/tools.md +++ b/.claude/skills/formshot-rendering/references/tools.md @@ -1,12 +1,12 @@ # formshot tools -Generated from the engine's command catalogue (formshot 0.4.0) by `./formshot agents sync`; do not edit by hand. +Generated from the engine's command catalogue (formshot 0.6.0) by `./formshot agents sync`; do not edit by hand. ## Contents -- Scene: `scene.add_group`, `scene.add_part`, `scene.add_primitive`, `scene.add_light`, `scene.add_cutaway`, `scene.remove`, `scene.rename`, `scene.set_transform`, `scene.set_visible`, `scene.set_locked`, `scene.set_ray_visibility`, `scene.set_part_colour`, `scene.set_metadata`, `scene.set_pivot`, `scene.set_light`, `scene.set_cutaway`, `scene.reparent`, `scene.duplicate`, `scene.import`, `scene.summary`, `scene.meshes`, `scene.mesh_data` +- Scene: `scene.add_group`, `scene.add_part`, `scene.add_primitive`, `scene.add_light`, `scene.add_cutaway`, `scene.remove`, `scene.rename`, `scene.set_transform`, `scene.set_visible`, `scene.set_locked`, `scene.set_ray_visibility`, `scene.set_part_colour`, `scene.set_metadata`, `scene.set_pivot`, `scene.set_part_mesh`, `scene.set_light`, `scene.set_cutaway`, `scene.reparent`, `scene.duplicate`, `scene.import`, `scene.summary`, `scene.meshes`, `scene.mesh_data`, `scene.retessellate` - Mesh: `mesh.add`, `mesh.remove` -- Materials: `material.create`, `material.set_params`, `material.set_type`, `material.assign`, `material.rename`, `material.remove` +- Materials: `material.create`, `material.set_params`, `material.set_type`, `material.set_slot`, `material.clear_slot`, `material.set_graph`, `material.label_add`, `material.label_set`, `material.label_remove`, `material.label_move`, `material.assign`, `material.rename`, `material.remove`, `material.types`, `material.node_kinds`, `material.program`, `material.preview_maps`, `material.get`, `material.labels` - Texture: `texture.add`, `texture.remove` - Cameras: `camera.add`, `camera.set`, `camera.set_active`, `camera.remove`, `camera.frame` - Environment: `environment.set` @@ -18,8 +18,12 @@ Generated from the engine's command catalogue (formshot 0.4.0) by `./formshot ag - App: `app.version`, `app.catalogue` - Selection: `selection.set`, `selection.clear` - History: `history.undo`, `history.redo`, `history.begin_group`, `history.end_group`, `history.abandon_group`, `history.barrier` -- Files: `file.new`, `file.open`, `file.save`, `file.import`, `file.close`, `file.export_image`, `file.export_model`, `file.snapshot`, `file.recover_list`, `file.recover` +- Files: `file.new`, `file.open`, `file.save`, `file.import`, `file.close`, `file.export_image`, `file.export_model`, `file.snapshot`, `file.recover_list`, `file.recover`, `file.reimport` - Viewing: `view.bounds`, `view.pick`, `view.frame` +- Import: `import.probe`, `import.start`, `import.status`, `import.cancel` +- Cad: `cad.status`, `cad.parts` +- Handoff: `handoff.inspect`, `handoff.open` +- Library: `library.list`, `library.get`, `library.favorite`, `library.recent`, `library.apply`, `library.save`, `library.remove`, `library.thumbnail`, `library.thumbnails` - Nodes: `node.set_visible`, `node.set_locked`, `node.rename`, `node.remove` - Undo: `undo` - Redo: `redo` @@ -144,6 +148,14 @@ Set or clear a node's gizmo pivot (local space). - `id`: integer; required; range 1 to inf; Node - `pivot`: value; Local pivot, null clears +## scene.set_part_mesh + +Make a part show another existing mesh in place, keeping its id, name, material, transform and metadata; its old mesh is removed when nothing else uses it. + +- `id`: integer; required; range 1 to inf; Part +- `mesh`: integer; required; range 1 to inf; Existing mesh the part shows from now on (add it first with mesh.add) +- `remove_unused`: boolean; default true; Remove the old mesh when no other part uses it + ## scene.set_light Change a light node's settings; give only the fields to change. @@ -196,10 +208,12 @@ Remove a mesh no part uses. ## material.create -Create a material. +Create a material, from a material type's preset when type is given. - `key`: integer; range 1 to inf; Key; allocated when absent -- `material`: object; fields name, params, textures, type_id +- `material`: object; fields graph, labels, name, params, slots, textures, type_id +- `name`: string; Name; the type's name when absent +- `type`: string (generic | plastic | plastic_clear | metal | metal_brushed | paint | paint_metallic | glass | glass_thin | liquid | gem | rubber | fabric | ceramic | diffuse | emissive | wood | stone); Start from this material type's preset (ignores material) ## material.set_params @@ -210,10 +224,71 @@ Change a material's surface parameters; give only the fields to change. ## material.set_type -Change a material's catalogue type id. +Change a material's type; keep false resets parameters and graph to the type's preset. -- `key`: integer; required; range 1 to inf; Material -- `type_id`: string; required; Catalogue type id +- `keep`: boolean; default true; Keep parameters and graph; false resets them to the type's preset +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `type_id`: string; required; Material type id (alias: type); see material.types + +## material.set_slot + +Drive a material input with an image texture (an existing texture or a new path); give only the slot fields to change. + +- `colour_space`: string; Colour-space hint for the new texture +- `input`: string (base_color | base_metalness | specular_weight | specular_roughness | coat_weight | coat_roughness | emission_color | geometry_opacity | normal | bump | displacement); required; Input the texture drives +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `path`: string; Image file to add as a new texture in the same step (instead of slot.texture) +- `slot`: object; Only the slot fields to change; a new slot starts from the defaults; fields channel, colour_space, fallback, filter, flip_y, invert, multiply, projection, range, strength, texture, transform, wrap + +## material.clear_slot + +Remove the texture slot of a material input; the constant applies again. + +- `input`: string (base_color | base_metalness | specular_weight | specular_roughness | coat_weight | coat_roughness | emission_color | geometry_opacity | normal | bump | displacement); required; Input +- `key`: integer; required; range 1 to inf; Material (alias: material) + +## material.set_graph + +Replace a material's node graph, or remove it with null. + +- `graph`: value; required; The whole graph; null removes it +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `merge`: boolean; default false; Merge into the previous merging set_graph of this material until history.barrier, so a value drag is one undo step + +## material.label_add + +Add a label (an image projected onto the parts wearing the material), optionally adding its image file in the same step; answers the new label id. + +- `colour_space`: string; Colour-space hint for the new texture +- `index`: integer; range 0 to inf; Position in the list; last when absent +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `label`: object; Label fields over the defaults (0.1 m square facing +Z, 10 mm deep); fields colour_space, depth, id, metalness, name, normal, opacity, origin, rotation, roughness, size, texture, two_sided, up, visible +- `path`: string; Image file to add as the label's texture in the same step + +## material.label_set + +Change a label; give only the fields to change (path replaces its image with a new texture). + +- `colour_space`: string; Colour-space hint for the new texture +- `id`: integer; required; range 1 to inf; Label id +- `key`: integer; required; range 1 to inf; Material (alias: material) +- `label`: object; Only the label fields to change; fields colour_space, depth, id, metalness, name, normal, opacity, origin, rotation, roughness, size, texture, two_sided, up, visible +- `path`: string; Image file to add as the label's new texture in the same step + +## material.label_remove + +Remove a label from a material. + +- `id`: integer; required; range 1 to inf; Label id +- `key`: integer; required; range 1 to inf; Material (alias: material) + +## material.label_move + +Move a label within its material's list; later labels print over earlier ones. + +- `id`: integer; required; range 1 to inf; Label id +- `index`: integer; required; range 0 to inf; New position; later labels print over earlier ones +- `key`: integer; required; range 1 to inf; Material (alias: material) ## material.assign @@ -402,9 +477,17 @@ Start a new document, empty or from a template (empty-studio, product-white, stu ## file.open -Open a .fshot project, or a model file as a new document. +Open a .fshot project, or a model file as a new document with the file.import options (camera framed). -- `path`: string; required; A .fshot project or a model file +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `merge`: boolean; default false; Put everything the file holds under one group +- `name`: string; Name for the imported group (the original file name) +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y ## file.save @@ -414,12 +497,18 @@ Save the document as .fshot to path, or to its own path. ## file.import -Import a model (glb, gltf, obj, stl, ply) with clean-up as one undoable step. +Import a model (glb, gltf, obj, stl, ply, 3mf, fbx, step, iges) with clean-up as one undoable step; units, up_axis, stand_on_floor, center, merge and cad_quality are optional, and every node made carries source.path and source.node metadata. -- `frame`: boolean; Frame the camera on the result (default: only when the document was empty) +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `frame`: boolean; Frame the camera on the result (default: only when the document had no parts) +- `merge`: boolean; default false; Put everything the file holds under one group - `name`: string; Name for the imported group (the original file name) -- `options`: object; fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group -- `path`: string; required; Model file: glb, gltf, obj, stl or ply +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y ## file.close @@ -598,6 +687,224 @@ Move the active camera, keeping its view direction, so the given nodes (or every - `nodes`: array of ['string', 'integer']; Node ids (decimal strings or numbers) - `width`: number; range 1 to inf; Viewport width in pixels (aspect only); the document's when absent +## import.probe + +Read a model file without changing the document: {format, units_declared, units_guess, unit_guessed, up_axis, bounds: {min, max, size} in file units and size_m (the size in metres at units_guess), triangles, meshes, nodes, materials, textures, images_in_file (images stored inside the model), texture_slots, warnings}. + +- `path`: string; required; Model file to read +- `worker`: boolean; default true; STEP and IGES: also open the file with the CAD worker (bodies, groups, colours, size; a few seconds); false answers from the file's header alone + +Note: read-only. + +## import.start + +Start importing a model in the background with the file.import options and return {job}; the read and clean-up run on a worker, and the document changes (one undo step) on the first engine call after the worker finishes. Follow it with import.status. + +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `frame`: boolean; Frame the camera on the result (default: only when the document had no parts) +- `merge`: boolean; default false; Put everything the file holds under one group +- `name`: string; Name for the imported group (the original file name) +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y + +## import.status + +An import job's progress: {job, state (running, done, failed, cancelled, or stale when the document was replaced while it ran and nothing was applied), stage (reading, validating, welding, normals, instancing, placing, converting, then waiting while a history group is open, done), fraction (0 to 1 over the whole import), path, seconds, result (the file.import reply) when done, error {message, code} when failed}; without job, {jobs: [...]} for every job of this session. + +- `job`: ['integer', 'string']; Job id from import.start + +Note: read-only. + +## import.cancel + +Cancel a running import job; the document stays exactly as it was. Answers the job's status with cancelled true when it was still running. + +- `job`: ['integer', 'string']; required; Job id from import.start + +## file.reimport + +Read the source files of the given imported nodes again (every imported node when none): parts match by source.node, then by unique name, then by identical shape; matched parts keep their materials and transforms and take the new shape, new parts are added, parts gone from the file are hidden (marked source.missing), all as one undo step. Answers {matched, added, hidden, updated, files: [{path, matched, added, hidden, updated, warnings, report (the clean-up report of the re-read), error?}]}. + +- `nodes`: array of ['string', 'integer']; Imported nodes (or groups holding them) whose files to read again; every imported node when absent + +## cad.status + +Whether the CAD worker that opens STEP and IGES files is installed, where, and which release; probe starts it once to check. + +- `probe`: boolean; Start the worker and ask its version (takes a few seconds) + +Note: read-only. + +## scene.retessellate + +Rebuild the meshes of CAD parts from their kept STEP or IGES source at a new quality; each part keeps its id, name, placement, material, visibility and selection (scene.set_part_mesh); one undo step. + +- `nodes`: array of ['string', 'integer']; Parts or groups whose CAD parts are rebuilt; every CAD part when absent +- `quality`: value; required; Tessellation of STEP and IGES surfaces: a preset, or chord (fraction of the model's diagonal) and angle (degrees) + +## cad.parts + +Parts imported from STEP or IGES files, with their kept source, original path, quality, unit and up axis; nodes limits the answer to the parts under those nodes. + +- `nodes`: array of ['string', 'integer']; Parts or groups to look under; every part when absent + +Note: read-only. + +## handoff.inspect + +Tell what a file or folder another Form app wrote is (a GoF folder from FormSculpt or FormFabric, a FormSurface export folder of maps, a FormCAD, FormSculpt or FormFabric model) and what it holds, without changing the document. + +- `item`: ['string', 'integer']; For a GoF folder: the entry's file name, id or name; the newest entry meant for FormShot (target any or formshot) when omitted. +- `path`: string; required; Absolute path of the file or folder: a GoF folder (holding gof.json), a FormSurface export folder or one of its files, or a model file. +- `read`: boolean; default true; Read the model too, to count meshes, triangles, materials and textures. + +Note: read-only. + +## handoff.open + +Open what another Form app handed over, as a new document or added to the current one as one undo step; every node that arrives records source.app, source.path and source.node in its metadata, and FormSurface's maps arrive as texture references by role and colour space. + +- `as`: string (new | add); default "add"; new replaces the document with a new one holding the hand-off; add puts it into the current document as one undo step. +- `frame`: boolean; Frame the camera on the scene afterwards; by default when the document had no parts before, or for a new document. +- `item`: ['string', 'integer']; For a GoF folder: the entry's file name, id or name; the newest entry meant for FormShot (target any or formshot) when omitted. +- `path`: string; required; Absolute path of the file or folder: a GoF folder (holding gof.json), a FormSurface export folder or one of its files, or a model file. + +## material.types + +The material types (id, name, category, default parameters, the parameters each page shows with ranges and units, preset graph) and the measured metal colours. + +- no parameters + +Note: read-only. + +## material.node_kinds + +Material graph node kinds with their input and output sockets, defaults and settings, and the material inputs slots and graph outputs may drive. + +- no parameters + +Note: read-only. + +## material.program + +A material's compiled program: whether it is constant, the instructions, constants, outputs, textures it samples and its encoded size. + +- `key`: integer; range 1 to inf; Material (alias: material) +- `material`: integer; range 1 to inf; Same as key + +Note: read-only. + +## material.preview_maps + +Small base colour, roughness, metalness and normal maps of a material baked in uv space by the CPU interpreter (base64 PNG), for the window's raster material view. + +- `key`: integer; range 1 to inf; Material (alias: material) +- `material`: integer; range 1 to inf; Same as key +- `size`: integer; default 128; range 16 to 512; Map width and height in pixels + +Note: read-only. + +## material.get + +One material's full JSON (name, type, params, texture keys, slots, graph, labels), the document's texture references by key, and a summary of its compiled program. + +- `key`: integer; range 1 to inf; Material (alias: material) +- `material`: integer; range 1 to inf; Same as key + +Note: read-only. + +## material.labels + +A material's labels in print order, each with its image path and pixel size (null when unknown), for the window's label list. + +- `key`: integer; range 1 to inf; Material (alias: material) +- `material`: integer; range 1 to inf; Same as key + +Note: read-only. + +## library.list + +List material library presets by shelf (all, favorites, recent, user), category and search words, ranked when searching, with category counts and library warnings. + +- `category`: string; Category name (Metal) or folder (metal), any case +- `limit`: integer; range 1 to inf; At most this many presets +- `offset`: integer; default 0; range 0 to inf; Skip this many presets first +- `query`: string; Words matched against name, tags, category and type, case- and accent-insensitive; results ranked +- `shelf`: string (all | favorites | recent | user); default "all"; all, favorites, recent (most recent first) or user (the user's own presets) + +Note: read-only. + +## library.get + +One library preset: its file, its source and the material applying it would make. + +- `id`: string; required; Preset id (metal/gold-polished, user/my-red) + +Note: read-only. + +## library.favorite + +Mark or unmark a library preset as a favourite (kept in the user's library state). + +- `id`: string; required; Preset id +- `on`: boolean; default true; true marks it a favourite, false unmarks it + +## library.recent + +The library presets applied most recently, newest first. + +- no parameters + +Note: read-only. + +## library.apply + +Apply a library preset to parts as one undo step: builds its material (or reuses an identical one) and assigns it to the parts the scope reaches (part, group or same_material). + +- `id`: string; required; Preset id +- `nodes`: array of ['integer', 'string']; required; Node ids the preset is dropped on (parts or groups) +- `scope`: string (part | group | same_material); default "part"; part: the parts in the given nodes; group: every part of their parent group; same_material: every part wearing the same material as a given part + +## library.save + +Save a document material as one of the user's own library presets (user/). + +- `category`: string (Metal | Plastic | Glass | Paint | Rubber | Fabric | Wood | Stone | Ceramic | Liquid | Gem | Emissive); required; Library category +- `material`: integer; required; range 1 to inf; Material key of the document material to save +- `name`: string; Preset name (the material's name when absent) + +## library.remove + +Delete one of the user's own library presets; built-in presets cannot be removed. + +- `id`: string; required; Id of one of the user's own presets (user/...) + +## library.thumbnail + +A preset's thumbnail (the material ball under the studio, CPU path traced, cached as PNG by preset hash and size); a missing one is queued on a background worker. + +- `id`: string; required; Preset id +- `inline`: boolean; default false; Add the PNG as base64 when it is ready +- `retry`: boolean; default false; Queue again a thumbnail whose render failed +- `size`: integer; default 128; range 64 to 512; Width and height in pixels +- `timeout`: integer; default 120; range 1 to 600; Seconds to wait at most +- `wait`: boolean; default false; Wait for a missing thumbnail to be rendered (otherwise it is queued and the reply says queued) + +Note: read-only. + +## library.thumbnails + +Queue the thumbnails of several presets on the background worker, in the order given, and report each one's state. + +- `ids`: array of string; required; Preset ids, most wanted first +- `size`: integer; default 128; range 64 to 512; Width and height in pixels + +Note: read-only. + ## node.set_visible Same as scene.set_visible ({id, visible} -> {ids: [id], visible}). @@ -638,16 +945,30 @@ Same as file.new ({path?, title?, template?} unchanged). Same as file.open ({path} unchanged). -- `path`: string; required; A .fshot project or a model file +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `merge`: boolean; default false; Put everything the file holds under one group +- `name`: string; Name for the imported group (the original file name) +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y ## document.import Same as file.import ({path, name?, options?} unchanged). -- `frame`: boolean; Frame the camera on the result (default: only when the document was empty) +- `cad_quality`: value; Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle} +- `center`: boolean; default false; Move the model's footprint centre to the origin +- `frame`: boolean; Frame the camera on the result (default: only when the document had no parts) +- `merge`: boolean; default false; Put everything the file holds under one group - `name`: string; Name for the imported group (the original file name) -- `options`: object; fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group -- `path`: string; required; Model file: glb, gltf, obj, stl or ply +- `options`: object; Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here); fields centre, detect_instances, generate_normals, smoothing_angle_deg, stand_on_floor, unit, up_axis, weld, wrap_in_group +- `path`: string; required; Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker +- `stand_on_floor`: boolean; default true; Lift the model so its lowest point rests at height 0 +- `units`: string (auto | mm | cm | m | in | ft); Unit the file is in; auto takes what the file declares, else a guess from its size +- `up_axis`: string (auto | y | z); Axis that points up in the file; auto takes what the file declares, else y ## document.save diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md index 786e5dee..2d869821 100644 --- a/.docs/wiki/Architecture.md +++ b/.docs/wiki/Architecture.md @@ -1,7 +1,7 @@ # Architecture -- `native/` is one Cargo workspace. `fsh-core` holds maths, colour and the sampler; `fsh-scene` the document and its commands; `fsh-accel` the BVH; `fsh-materials` the surface model; `fsh-io` and `fsh-format` the files; `fsh-render-cpu` the CPU path tracer, which is the specification; `fsh-render-gpu` the GPU path tracer on wgpu compute shaders, held to the CPU's picture; `fsh-commands` the command registry, `dispatch`, device choice and the crash journal; `fsh-cli` the `formshot-engine` program. `fsh-py` and `fsh-wasm` bind the same registry for Python and the browser, and `fsh-wasm` also runs the GPU tracer in the window on WebGPU. -- Every command is declared once (88 catalogue entries). The window, the command line, the MCP server and the agent skills read the same catalogue. +- `native/` is one Cargo workspace. `fsh-core` holds maths, colour and the sampler; `fsh-scene` the document and its commands; `fsh-accel` the BVH; `fsh-materials` the surface model; `fsh-io` and `fsh-format` the files (with 3MF and FBX readers and the Form family's hand-off formats); `fsh-cad` STEP and IGES through FormCAD's kernel worker, a separate program; `fsh-render-cpu` the CPU path tracer, which is the specification; `fsh-render-gpu` the GPU path tracer on wgpu compute shaders, held to the CPU's picture; `fsh-commands` the command registry, `dispatch`, device choice and the crash journal; `fsh-cli` the `formshot-engine` program. `fsh-py` and `fsh-wasm` bind the same registry for Python and the browser, and `fsh-wasm` also runs the GPU tracer in the window on WebGPU. +- Every command is declared once (121 catalogue entries); the command groups added with import, CAD, hand-offs, materials and the library live in their own modules under `fsh-commands/src/ext/`. Material slots and graphs compile to one small program that both tracers run, and the material library's presets live in `assets/library/`. The window, the command line, the MCP server and the agent skills read the same catalogue. - `frontend/` is a vanilla TypeScript app on Vite. The engine client builds no UI; the shell renders once and patches text and attributes in place. The viewport draws Solid, Wireframe and Material preview itself with WebGL2 and shows the path tracer as streamed frames from the engine, or through WebGPU in the window when that works. - `backend/` is the FastAPI service. It serves the built frontend, the projects library, the engine bridge (with the engine's crash journal in the data folder), the binary mesh and project snapshot routes for the viewport, and `/mcp`. - `src-tauri/` is the Tauri 2 shell: a splash window, the frozen service started as a sidecar, the main window opened on the service's page, the service stopped on exit. diff --git a/.docs/wiki/CAD-and-Hand-offs.md b/.docs/wiki/CAD-and-Hand-offs.md new file mode 100644 index 00000000..d309aa91 --- /dev/null +++ b/.docs/wiki/CAD-and-Hand-offs.md @@ -0,0 +1,20 @@ +# CAD and Hand-offs + +## STEP and IGES + +STEP and IGES files are opened by FormCAD's kernel worker, a separate program built on OpenCascade. FormShot does not include it: download it once from **Preferences > CAD Import** (or the Download line in the import sheet, or `./formshot cad fetch`). The download is checked file by file against a published record before it is installed in your cache folder. `./formshot cad status` tells whether it is there. + +- **Quality.** Draft, Medium (default), High, Ultra, or Custom (the largest gap between the mesh and the surface as a share of the model's size, and an angle). The default is set on the CAD Import page. +- **What comes in.** Assemblies as groups, one part per body, colours as materials (face colours of STEP files and solid colours of IGES files are read from the file itself), identical bodies sharing one mesh. The STEP or IGES file is kept inside the project. +- **Re-tessellate.** **Scene > Re-tessellate CAD Parts** rebuilds the selected CAD parts, or all of them, at another quality. Each part keeps its name, position, material, visibility and selection, and it is one undo step. +- **Limits.** The worker reports no progress inside one body, so a big file waits on one step. Starting the worker can take a while on a busy machine; FormShot waits up to 120 s for it (`FORMSHOT_CAD_HELLO_TIMEOUT` changes that). Only tested on Linux. + +## Hand-offs from the Form apps + +FormShot picks up what the other Form apps hand over: + +- **FormSculpt** and **FormFabric** send models through their GoF folder; FormShot takes the entries meant for any app. +- **FormSurface** exports painted maps (in its own names or any of its templates, with texture sets and UDIM tiles) and its OBJ; FormShot puts the maps on the matching materials as textures with the right roles. +- **FormCAD** models (GLB, 3MF) arrive with their title and design unit; its STEP files go through the CAD worker. + +While the FormShot window is open, the service watches those folders. Nothing comes in on its own: each arrival asks **Decline**, **Open once** or **Always allow** for that app, and whether to add it to this document or open it as a new one. **Preferences > Hand-offs** keeps the choice per app (ask, always, block) and shows the watched folders. **File > Open a Hand-off** lists everything waiting. A hand-off is one undo step, and every node records which app it came from. Agents use the same `handoff.inspect` and `handoff.open` tools, under the same consent as any other change. diff --git a/.docs/wiki/GPU-Engine.md b/.docs/wiki/GPU-Engine.md index 4d26c1c1..e50ebdbf 100644 --- a/.docs/wiki/GPU-Engine.md +++ b/.docs/wiki/GPU-Engine.md @@ -6,14 +6,14 @@ - **Same paths as the CPU.** The same sampler, draw order, BSDF (with the same energy tables), light, environment and emissive tables as `fsh-render-cpu`. The CPU engine is the specification: changes land there first. - **Two traversal paths.** FormShot's own BVH, flattened into storage buffers, runs wherever compute runs. Hardware ray queries are used where the adapter offers them, and their hits are refined to match the software path exactly. `FORMSHOT_GPU_TRAVERSAL=software|hardware|auto` forces a choice. -- **Materials are data.** Changing a material writes a record; it never compiles a shader. Switching adaptive sampling is a flag in the frame uniform and never compiles one either. +- **Materials are data.** Changing a material writes a record; it never compiles a shader. Texture slots, graphs and labels are a small program the kernel interprets, stored with the textures' pixels in the float table; a scene with no such material leaves the interpreter out. Thin film and dispersion are part of the record. Switching adaptive sampling is a flag in the frame uniform and never compiles one either. - **Render region.** `render.region` limits passes and sample statistics to a rectangle of the image; the rest keeps its samples. The CPU engine does not have this yet and says so. - **Eight storage buffers.** The scene fits the WebGPU default limit: nodes, triangles, vertex normals, instances, materials, lights, one float table (environment, BSDF energy and emissive blocks) and the film. New data goes into the float table or a uniform, never into a new binding. - **Bands and budgets.** The film is split into row bands that fit one storage binding, and each pass into dispatches of about 0.1 s, so the operating system's GPU watchdog is never tripped. ## Shader modules -`bindings`, `math`, `features` and `sampler` are the base; `traverse_common`, `traverse_sw` and `traverse_hw` (selected through the one-line `trace` and `trace_hw`) do traversal; `camera`, `env`, `surface`, `lights`, `catcher`, `bsdf_tables` and `bsdf` are ported from the CPU engine; `integrator` holds the path loop; `kernel` is the megakernel entry, `adaptive` the adaptive-sampling pass, and `plumbing` a minimal smoke kernel. +`bindings`, `math`, `features` and `sampler` are the base; `traverse_common`, `traverse_sw` and `traverse_hw` (selected through the one-line `trace` and `trace_hw`) do traversal; `camera`, `env`, `surface`, `lights`, `catcher`, `bsdf_tables` and `bsdf` are ported from the CPU engine; `texture`, `procedural` and `program` sample textures, compute the procedural patterns and run material programs; `integrator` holds the path loop; `kernel` is the megakernel entry, `adaptive` the adaptive-sampling pass, and `plumbing` a minimal smoke kernel. ## Measured diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 6406d0c6..9a37e3f9 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -1,7 +1,7 @@ # FormShot -The Form family's 3D product renderer. Start with [Getting Started](Getting-Started), then [Architecture](Architecture), [Rendering](Rendering), [GPU Engine](GPU-Engine) and [Viewport](Viewport). +The Form family's 3D product renderer. Start with [Getting Started](Getting-Started), then [Architecture](Architecture), [Rendering](Rendering), [GPU Engine](GPU-Engine) and [Viewport](Viewport). Getting models and materials in: [Import](Import), [CAD and Hand-offs](CAD-and-Hand-offs), [Materials](Materials) and [Library](Library). -At 0.2.0 the repository held the shell (launcher, service, window, desktop shell and agent dock), the document and its `.fshot` project file, the CPU path tracer and the command line render. The GPU tracer (0.3.0) and the live viewport (0.4.0) have since landed in the tree: a GPU path tracer that matches the CPU picture, device choice with a fallback to the processor, WebGL2 raster modes with selection and a gizmo, and an optional engine in the window through WebAssembly and WebGPU. FormShot is unreleased. +At 0.2.0 the repository held the shell (launcher, service, window, desktop shell and agent dock), the document and its `.fshot` project file, the CPU path tracer and the command line render. The GPU tracer (0.3.0) and the live viewport (0.4.0) have since landed in the tree: a GPU path tracer that matches the CPU picture, device choice with a fallback to the processor, WebGL2 raster modes with selection and a gizmo, and an optional engine in the window through WebAssembly and WebGPU. Since then import (3MF, FBX, background jobs, reimport, embedded textures), STEP and IGES through FormCAD's kernel worker, hand-offs from the other Form apps, material types, texture slots, a node graph with procedural patterns, and a library of 249 measured and published presets have landed, with image labels, thin film and dispersion, and textures and material graphs rendered by both path tracers. FormShot is unreleased. GPU rendering has run only on software drivers (Vulkan through lavapipe and SwiftShader, OpenGL through llvmpipe), and the path tracer in the window has not drawn a frame yet; the window shows streamed frames from the engine instead. [Rendering](Rendering) lists every known limit. diff --git a/.docs/wiki/Import.md b/.docs/wiki/Import.md new file mode 100644 index 00000000..c7849f35 --- /dev/null +++ b/.docs/wiki/Import.md @@ -0,0 +1,24 @@ +# Import + +FormShot reads glTF and GLB, OBJ with MTL, STL, PLY, 3MF and FBX itself, and STEP and IGES through FormCAD's kernel worker (see [CAD and Hand-offs](CAD-and-Hand-offs)). FBX is read by the desktop engine only. The full description is `docs/IMPORT.md` in the repository. + +## Bringing a model in + +- **File > Import Model** (Mod+I), a drop on the viewport, or a drop on Home (which starts a new project named after the file). In a browser the file and the files beside it (glTF buffers and images, OBJ's MTL and maps) are uploaded to the service; on the desktop FormShot reads the file where it is. +- The import sheet shows what the file holds before anything changes: format, size, triangles, parts and materials, and the unit the file declares or the one FormShot guesses from its size. A guessed unit is marked; check it. +- Options: units (automatic, mm, cm, m, in, ft), up axis (automatic, Y or Z), stand on the floor, centre, frame the camera, merge everything into one group, and the CAD quality for STEP and IGES. The sheet remembers your choices. With several files, Import All applies them to the rest. +- The import runs in the background with its progress in the sheet; Cancel leaves the document exactly as it was. A finished import is one undo step. + +## What comes in + +- Parts, groups and their names; repeated parts share one mesh, also when they are rotated or mirrored copies. +- Materials with their texture maps as texture slots (base colour, roughness, metalness, normal, emission, opacity, bump and more), including glTF's material extensions and texture transforms. PNG, JPEG, HDR and EXR images are stored inside the project, so it can be moved and still find them; other image formats are skipped with a note. +- Every imported part remembers its file and where it sat in it. + +## Reimport + +**File > Reimport** reads the files of the selected parts again (all imported parts when nothing is selected). Parts are matched by their place in the file, then by name, then by shape: they keep their position and material, take the new shape, and keep their identity; new parts arrive and parts gone from the file are hidden, not deleted. **File > Recent Imports** lists the last eight. A model uploaded from a browser is kept for 24 hours for this. + +## Limits + +glTF materials with masked alpha cut sharply at their cutoff; blended ones fade. FBX NURBS, skins, blend shapes, cameras and lights are not read. Files given to the desktop app when it starts open in the import sheet; folders given that way do not. diff --git a/.docs/wiki/Library.md b/.docs/wiki/Library.md new file mode 100644 index 00000000..b2815b11 --- /dev/null +++ b/.docs/wiki/Library.md @@ -0,0 +1,18 @@ +# Library + +The Library panel on the left holds 249 material presets in twelve categories: Metal, Plastic, Glass, Paint, Rubber, Fabric, Wood, Stone, Ceramic, Liquid, Gem and Emissive. The full description is `docs/LIBRARY.md` in the repository. + +## Where the numbers come from + +Every preset is FormShot's own, made from public physical data: metal colours and edge tints computed from measured optical constants (the refractiveindex.info database, CC0), refractive indices and dispersion of glasses, plastics, liquids and gems from measurements and published tables, and lamp colours from their spectra. Finish roughness and dye colours are chosen by hand, and each preset says which of its numbers were chosen and why (the details popover shows its sources). + +## Using it + +- **Find.** Search by name, tag, category or type (accents and case do not matter). Shelves: All, Favorites, Recent, In project (the document's own materials) and User (your saved presets). Category counts follow the shelf and the search. +- **Apply.** Double-click a tile or press Enter to put it on the selected parts. The tile menu also applies it to the whole group or to every part with the same material. Or drag the tile onto a part in the viewport: Alt takes the whole group, Shift every part with the same material. One undo step either way, and applying the same preset twice reuses the material. +- **Favourites and your own presets.** Star a preset from its tile menu. **Save Selected Material to Library** (the plus button) keeps a material of yours on the User shelf. +- **Thumbnails** are rendered by FormShot's own path tracer on its material ball the first time a tile is seen, and kept. + +## Limits + +Wood, stone and metallic paint presets get their procedural graph when applied, and thin-film presets (anodised titanium, pearl paints) their film, in both path tracers; Material preview shows only an approximation of the patterns. A saved preset keeps parameters only, not textures or a graph. diff --git a/.docs/wiki/Materials.md b/.docs/wiki/Materials.md new file mode 100644 index 00000000..27d3f683 --- /dev/null +++ b/.docs/wiki/Materials.md @@ -0,0 +1,31 @@ +# Materials + +Every FormShot material is the same layered surface model (base, specular, transmission, coat, fuzz, emission and the rest, after OpenPBR Surface) with a type that gives it sensible starting values and decides which settings its page shows. The full description is `docs/MATERIALS.md` in the repository. + +## Types + +Generic, Plastic, Clear plastic, Metal, Brushed metal, Paint, Metallic paint, Glass, Thin glass, Liquid, Gem, Rubber, Fabric, Ceramic, Diffuse, Emissive, Wood and Stone. Metal offers ten measured metal colours. Wood, Stone and Metallic paint start with a procedural graph (rings, veins, flakes). Changing the type keeps the current values or resets them to the new type, as you choose. + +## The Material page + +In the inspector: the list of the document's materials with a swatch each (new, assign to selection, duplicate, rename, delete), the parameters of the selected material's type (All parameters shows every field), Textures, Graph and Save to library. A drag on a value is one undo step. + +## Texture slots + +A texture can drive a material's base colour, roughness, metalness, specular weight, coat, coat roughness, emission, opacity, normal, bump or displacement. Each slot sets how the image is placed (uv set, box, planar, cylindrical or spherical projection; offset, scale, rotation), repeated (repeat, clamp, mirror), filtered, read (colour space, channel, range, invert, multiply) and how strong a normal or bump map is. Choose an image from disk; imported models bring their maps as slots already. + +## The node graph + +**Edit graph** opens the node editor: images, mapping, mix, maths, colour ramps, normal maps, bump, and ten procedural patterns (noise, fractal noise, Voronoi, checker, gradient, wave, brushed lines, flakes, wood and marble). Connect node outputs to the material's inputs on the output node; links that cannot work are refused with the reason. Tab adds a node at the pointer, L connects, ? lists the keys. Every change is undoable, and a drag on a value is one step. Procedural patterns fade fine detail to its average when it gets smaller than a pixel, so they do not shimmer. + +## Where you see it + +Both path tracers (processor and graphics card) render slots, graphs and labels, with PNG, JPEG, HDR and EXR images filtered to the pixel's size, and they agree with each other. An image that is missing or cannot be read shows the slot's fallback colour, and the render status says which. The viewport's **Material preview** mode shows slots and graphs from small maps the engine bakes, on parts with texture coordinates; projected and procedural materials are approximated there, image slots and labels show their images. Images you choose (for slots, labels or the environment) are stored inside the project, so it can be moved. + +## Labels + +The **Labels** section of the Material page prints images onto the parts that wear the material, like stickers or printed logos: add one from an image, then **Place on Surface** and click where it goes on the part. Set its width and height (in millimetres, linked to the image's proportions), rotation, depth (how far through the part it reaches), opacity, one- or two-sided, and optionally its own roughness and metalness. Drag rows to change which label prints on top. Every change is undoable. + +## Thin film and dispersion + +A thin film on a surface gives soap-bubble and anodised-metal colours that shift with the angle (thickness in micrometres, the film's refractive index, and a weight). Dispersion splits light by colour in glass and gems (the Abbe number and a scale): a prism shows separate red, green and blue images, a diamond coloured fire. Both work in both path tracers. diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index bd960cd7..e1f42014 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -4,3 +4,7 @@ - [Rendering](Rendering) - [GPU Engine](GPU-Engine) - [Viewport](Viewport) +- [Import](Import) +- [CAD and Hand-offs](CAD-and-Hand-offs) +- [Materials](Materials) +- [Library](Library) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f2384a0..bc926309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,82 @@ Versions follow `v*.*.*` with dots. Dates are UTC. FormShot has not been released; these versions exist in the repository only. +## 0.6.0 · 2026-12-02 + +Materials get types, texture maps, a node graph and labels, both path tracers render them, and a library of 249 presets made from measured and published data sits in the left panel. + +### Added + +- Eighteen material types (Generic, Plastic, Clear plastic, Metal, Brushed metal, Paint, Metallic paint, Glass, Thin glass, Liquid, Gem, Rubber, Fabric, Ceramic, Diffuse, Emissive, Wood and Stone), each a preset of the one layered surface model, with ten measured metal colours. `material.create {type}` starts from a type, and `material.set_type` keeps the values or resets them to the new type. +- Texture slots: an image can drive a material's base colour, roughness, metalness, specular weight, coat, coat roughness, emission, opacity, normal, bump or displacement, with a uv set or a box, planar, cylindrical or spherical projection, offset, scale and rotation, repeat, clamp or mirror, filtering, colour space, channel, range, invert and multiply (`material.set_slot`, `material.clear_slot`). +- A material node graph (`material.set_graph`) with image, mapping, mix, maths, colour ramp, normal map and bump nodes and ten procedural patterns: noise, fractal noise, Voronoi, checker, gradient, wave, brushed lines, flakes, wood and marble. Patterns fade detail finer than a pixel to its average. Wood, Stone and Metallic paint start with a graph, and a procedural normal output can be linked straight to a material's normal. +- Slots, graphs and labels compile to a small material program that agents can read with `material.program`; materials without them stay exactly as they were. +- Both path tracers render texture slots, graphs and labels: the processor runs the program at every hit and the graphics card runs the same program in its shader, with the textures packed into its existing buffers (opaque 8-bit images at half the memory). Fine detail is filtered by each pixel's footprint (ray cones), so distant textures and patterns do not shimmer. +- Textures load from PNG (8 and 16 bit), JPEG (baseline and progressive), Radiance HDR and OpenEXR (scanline; uncompressed, RLE, ZIP, PIZ and PXR24). A missing or unreadable image shows its slot's fallback colour and is named in `render.status`; a texture file changed on disk is picked up at the next render. +- Texture maps of imported glTF, OBJ, 3MF and FBX files arrive as material texture slots, with glTF's texture transforms and material extensions; masked glTF alpha cuts sharply at its cutoff. Every reader stores texture coordinates with v pointing up. +- Images found by an import, and images you choose for a slot, a label or the environment, are stored inside the project (named by their SHA-256; projects with the older names still open), so a moved project keeps its textures and its HDRI. Environments can be OpenEXR as well as Radiance HDR. +- Labels: images printed onto parts like stickers (`material.label_add`, `label_set`, `label_remove`, `label_move`, `material.labels`), with size, rotation, depth, opacity, one or two sides and their own roughness and metalness; the Labels section of the Material page lists them and places one with a click on the part. +- Thin-film iridescence (soap bubbles, anodised metals, pearl paints) and dispersion in glass and gems (a prism shows separate colour images, a diamond coloured fire), on both tracers. +- The Material page in the inspector: the material list with swatches, the type's parameters (and all of them on request), texture slots with every setting, the graph's state, labels and Save to library. A drag on a value is one undo step. Images are chosen from disk, through `POST /api/textures` in a browser. +- The graph editor window: add nodes with Tab, connect with drags or L, copy and paste between materials, a colour ramp editor, links that cannot work refused with the reason, and every change undoable; a value drag is one undo step through `material.set_graph {merge: true}`. +- Material preview in the viewport shows texture slots, graphs and labels from maps the engine bakes with the real images (`material.preview_maps`), sampled by the mesh's texture coordinates, with GGX highlights. +- The window's own WebGPU engine receives the document's textures: embedded ones from the project, others through `GET /api/engine/texture`, decoded in a background worker. +- The material library: 249 presets in twelve categories, each citing the measured data, published tables or authored choices behind its numbers (metal colours and edge tints computed from the refractiveindex.info database, CC0). `library.list` searches and ranks; `library.apply` puts a preset on parts, their group or every part with the same material as one undo step, reusing an identical material; favourites, recent presets and your own saved presets (`library.save`, `library.remove`) are kept in your user data folder. +- Library thumbnails rendered by FormShot's own CPU path tracer on its material ball, in the background, cached by preset and served by `GET /api/library/thumbnail/`. +- The Library panel: search, shelves (All, Favorites, Recent, In project, User), category counts, three tile sizes, a virtual grid that scrolls thousands of tiles with twenty nodes, apply by double-click, Enter or by dragging a tile onto a part (Alt for the whole group, Shift for every part with the same material), details with the preset's sources, and Save Selected Material to Library. +- The desktop app carries the library as a bundle resource and tells the service where it is; `FORMSHOT_LIBRARY` points the engine at another one. +- Editing a material, applying a library preset or assigning a new material refreshes only the parts that wear it, on the graphics card as on the processor, and the rest of the picture keeps its samples. +- Steep normal and bump maps no longer leave black rims on polished metal: both tracers keep the reflection just above the surface. When the graphics card fails and the processor takes over, textures come along. +- `material.get` returns one material with its textures and a summary of its program, and `cad.parts` lists the CAD parts; the window uses them instead of reading the whole project. +- Edits that agents make through the service or MCP show in the open window at once, and undo and redo stay current after edits that change nothing on screen. +- `FORMSHOT_CAD_HELLO_TIMEOUT` sets how long a starting CAD worker may take (120 s by default), and a save writes only the CAD sources some part still uses. +- The material, graph, library and labels pages and the viewport's texture notes are translated into the 23 interface languages. + +### Checked + +- Materials without slots or graphs render byte-identically to the previous engine, every one compiles to a constant program equal to its old inputs, and older projects and crash journals load and resave byte for byte. +- All 18 types create, compile and survive a save and reopen; bump of a sloped height gives the expected normal; slot transforms and projections match values worked out by hand. +- The ten procedural patterns agree between the processor and the graphics card's shader language to within 5.4e-7 over 8192 points each, on software Vulkan only. +- Untextured scenes render byte-identically to before on the processor, and the graphics card stays within 0.00001 of it on software Vulkan and OpenGL. 77 programs evaluated value by value agree within 1.4e-5 apart from bump through cylindrical and spherical projections. Bubbles, anodised metals, a prism and a diamond agree within 0.00007. +- Thirty scenes (Khronos glTF samples, every material type, procedurals, labels, thin film, dispersion, normal maps, blended and masked alpha, a preset per library category; under the sky and under a CC0 HDRI) agree between the processor and software Vulkan within 0.0009, with no NaN pixels; constant scenes take the same time as before on both tracers. +- Applying a preset to one band of a product cleared the same 5,600 of 76,800 pixels on both tracers, all of the changed pixels inside that region. +- Thin film matches an exact spectral calculation to 0.003 on average over glass and stays energy-conserving (white furnace 0.986 to 1.008). +- The JPEG reader agrees with libjpeg within 4 levels and the OpenEXR reader with the OpenEXR library bit for bit; thousands of damaged files gave errors, never a crash. +- glTF, OBJ, 3MF and FBX projects with textures, and a project with images chosen by hand, were moved to a fresh folder, their source images deleted, reopened and rendered with every texture; they also survived a crash and recovery. +- The Material page, the graph editor and the Library panel ran in headless Chrome against the engine, with drags as one undo step and no layout shift. The library lists 249 presets without warnings; a deliberately damaged copy gave 247 presets and seven warnings and no crash. Thumbnails of every category and all graph presets were looked at. +- Not yet: the window's own WebGPU engine has run with textures only against a stand-in viewport; no real graphics card, no desktop bundle; the brushed-metal streak direction is not yet tied to the part. + +## 0.5.0 · 2026-12-02 + +Models come in more ways: 3MF, FBX, STEP and IGES, in the background with a sheet that shows what a file holds, and from the other Form apps. + +### Added + +- 3MF and FBX import (FBX in the desktop engine), alongside glTF, GLB, OBJ, STL and PLY. Polygons are ear-clipped, groups in OBJ files become nodes, STL facet colours become vertex colours, and tangents are made for meshes with texture coordinates. +- Repeated parts are found also when they are rotated or mirrored copies, and share one mesh. +- `file.import` takes `units`, `up_axis`, `stand_on_floor`, `center`, `frame`, `merge` and `cad_quality`; older calls keep working. A guessed unit now comes with a confidence. +- `import.probe` tells what a file holds without changing the document. +- `import.start`, `import.status` and `import.cancel` run an import in the background with its stage and progress; a cancelled import leaves the document exactly as it was, a finished one is one undo step, and a job started before another document was opened reports stale and changes nothing. +- `file.reimport` reads changed files again: parts keep their material, position and identity, new parts arrive and missing ones are hidden. +- Imported parts remember their file and where they sat in it (`source.path`, `source.node`). +- STEP and IGES through FormCAD's kernel worker: assemblies, colours (also STEP face colours and IGES solid colours read from the file) and shared parts at draft, medium, high, ultra or a custom quality. The source file is kept inside the project and the crash journal. +- `./formshot cad fetch` and Preferences > CAD Import download the CAD worker and check every file against a pinned record; `cad.status` says whether it is installed and what it can report. +- `scene.retessellate` rebuilds CAD parts at another quality, and the new `scene.set_part_mesh` swaps a part's mesh, so parts keep their ids, materials and selection. Scene > Retessellate opens a dialog for it. +- Hand-offs from the Form apps: what FormSculpt and FormFabric send through their GoF folder, FormSurface's painted maps and FormCAD's models are picked up while the window is open and offered for the person's answer first (decline, open once, always allow that app). `handoff.inspect` and `handoff.open` serve the window and agents. +- The import sheet (Mod+I, drops on the viewport and on Home): the file's size, counts and unit, the options, progress and Cancel, Import All for several files, File > Reimport and Recent Imports. Browser uploads go to `POST /api/imports` and are removed after a day without changes. +- Files given to the desktop app open: a project opens, models (now also 3MF, FBX, STEP and IGES) go to the import sheet. +- The command line takes import options on `render`, `convert` and `info`, and gains `probe` and `reimport`. +- The import sheet, the hand-off prompts and settings, and the CAD settings and dialog are translated into the 23 interface languages. + +### Checked + +- 94 files (3MF Consortium samples, Khronos glTF samples, the ufbx test files and our own) imported, and over 40,000 damaged copies gave errors, never a crash. +- Ten models with two option sets each imported, saved, reopened and saved again with identical documents. +- A 1.8 million triangle OBJ was cancelled at 23 % with the document unchanged. +- STEP and IGES ran with the real worker on Linux x86_64: a gearbox at four qualities, retessellation from draft to ultra with every part id kept, re-import of a changed file, cancel and timeout with no worker left running, and recovery after a crash with the source file deleted. The worker itself reports no progress within a file, no per-face colours and no assembly transforms. +- Hand-offs ran with real exports from FormSculpt, FormFabric and FormCAD and with FormSurface folders written by hand, through the engine and the window's prompt in headless Chrome. +- Not run: macOS and Windows, the Tauri desktop build (the open panel, native drops and launch opens ran against a stub only), and a live FormSurface export. + ## 0.4.0 · 2026-12-02 The viewport is live: you can see the scene in four modes, pick and move parts in it, and keep a path-traced picture refining while you work. diff --git a/CLAUDE.md b/CLAUDE.md index 0afc7a64..10292251 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,8 +4,12 @@ ## Repo layout notes -- `assets/` is repo-level art (the README logo and the desktop icon source), not app runtime assets: runtime files live in `frontend/public/` and `frontend/src/`. +- `assets/` is repo-level art (the README logo and the desktop icon source), not app runtime assets: runtime files live in `frontend/public/` and `frontend/src/`. The one exception is `assets/library/` (below). - `native/crates/fsh-commands` is the only place an engine command is declared (its catalogue is built on `fsh-scene`'s command table). The window, the CLI (`formshot-engine`), the MCP server and the agent skills read its catalogue; never add a tool name anywhere else. The one exception is window-only service commands that must never reach MCP (`terminal.*`, `claudecode.*`, `agents.*`, `chat.*`, `prefs.*`), which live on the service's bus in `backend/app/agent/`. +- Command groups added since the first catalogue live one module each in `native/crates/fsh-commands/src/ext/` (`import.rs` with `import/`, `cad.rs`, `handoff.rs`, `materials.rs`, `library.rs` with `library/`): a module lists its commands in `COMMANDS` and answers them in `dispatch`, and `ext/mod.rs` chains the groups into the catalogue. Commands that change the document as data still go in `fsh-scene`'s table. When several people build at once, a new group or window module is first committed as an empty reserved file (the reserved-module pattern: `ext/*.rs`, `backend/app/routers/*.py`, `frontend/src/ui//index.ts`, `fsh_io::family`), so ownership is decided by path (`frontend/src/ui/labels/index.ts` began as such a stub and is now the Labels section). +- `native/crates/fsh-cad` reads STEP and IGES through FormCAD's kernel worker, a separate program run as a child process and never linked. The engine never downloads it: `backend/app/routers/cad.py` (and `./formshot cad fetch`, `setup/cad_worker`) installs it into the user cache after checking a pinned record. fsh-cad is a native-only dependency. +- `assets/library/` holds the material library's presets (`materials//.json`) and their generated `index.json`, with its own README of sources and licences; it is app data shipped as a Tauri bundle resource, unlike the rest of `assets/`. Preset ids never change once released. +- Material slots and graphs compile to a material program (`fsh-scene` compile.rs, `fsh-materials` program.rs and interp.rs); a constant material must stay a constant program whose `base` equals the old per-material inputs. `docs/MATERIALS.md`, `docs/IMPORT.md` and `docs/LIBRARY.md` describe the import, materials and library work. - The document changes only through commands. `fsh-scene`'s `Editor` owns the document, the undo history and the selection; the renderers read an immutable `RenderSnapshot` from `flatten()`, never the live document. - `fsh-render-cpu` is the specification engine: the GPU tracer (`fsh-render-gpu`, planned for 0.3.0 and now built) must match its pictures within 0.005 mean absolute difference at equal samples, so a change to sampling, lights or materials lands on the CPU path first (and in its public `spec` module), then is ported to WGSL. GPU work has run only on software drivers; say so in every report. `docs/GPU-ENGINE.md` holds the buffer layouts and the shader map. - `fsh-render-gpu` keeps 8 storage buffers per shader stage (the WebGPU default); never add a storage binding, and change `src/layout.rs` and `src/shaders/bindings.wgsl` together. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d1ad19a8..63394867 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ Thank you for helping. FormShot is the Form family's 3D product renderer: open a model, dress its parts in materials, light it and render it in one window, with no account, -running on your own computer, and open to agents over MCP. It is at 0.4.0 and not +running on your own computer, and open to agents over MCP. It is at 0.6.0 and not released yet, so the most useful help now is careful use and clear reports. ## Where to start diff --git a/NOTICE.md b/NOTICE.md index 5ec2cd9a..bab2b339 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -4,7 +4,7 @@ FormShot is licensed under the Apache License 2.0 (see `LICENSE`). Copyright 202 This file is the human list: what each component is and why it is there. `THIRD-PARTY-NOTICES.txt` lists every package that ships with its version and licence; `./formshot notices` replaces it with the full licence texts (copyright lines, conditions and disclaimers) from the installed Python packages, `frontend/package-lock.json`, `native/Cargo.lock`, `src-tauri/Cargo.lock` and the cargo registry, and `./formshot notices --check` checks it covers what ships. It ships in every installer beside this file, is frozen into the service, and is shown in Preferences under About. -FormShot 0.4.0 is unreleased. Licences marked "to confirm" below were not read from package metadata on the machine that wrote this file, and are confirmed when the lock files are complete and `./formshot notices` runs. +FormShot 0.6.0 is unreleased. Licences marked "to confirm" below were not read from package metadata on the machine that wrote this file, and are confirmed when the lock files are complete and `./formshot notices` runs. ## Included in this repository @@ -29,6 +29,10 @@ FormShot 0.4.0 is unreleased. Licences marked "to confirm" below were not read f | regex, serde, serde_json | MIT OR Apache-2.0 (serde and serde_json read from the registry; regex to confirm) | shell and engine | | windows-sys (Windows), objc2, objc2-app-kit, objc2-foundation (macOS) | to confirm | desktop shell platform calls | | rayon 1.12.0 and rayon-core 1.13.0 | MIT OR Apache-2.0 | parallel BVH builds and render tiles | +| roxmltree 0.21.2 | MIT OR Apache-2.0 | reads the XML inside 3MF files (fsh-io) | +| bevy_mikktspace 1.0.0 | Zlib AND (MIT OR Apache-2.0) | MikkTSpace tangents for imported meshes (fsh-io); the package carries the MIT and Apache texts, its README names the Zlib licence of the original MikkTSpace code | +| zune-jpeg 0.5.15 and zune-core 0.5.4 | MIT OR Apache-2.0 OR Zlib | decodes JPEG textures, baseline and progressive (fsh-io), in the engine and in the window's WebAssembly engine | +| ufbx 0.11.5 (with the ufbx C library it compiles) | MIT OR Unlicense (used under MIT) | reads FBX files in native builds (fsh-io); the crate package carries no licence file: its Cargo.toml declares the licence and the upstream ufbx repository's LICENSE gives MIT or public domain | | crossbeam-deque, crossbeam-epoch, crossbeam-utils, either | MIT OR Apache-2.0 | pulled in by rayon | | itoa, zmij, memchr | MIT OR Apache-2.0; MIT; Unlicense OR MIT (used under MIT) | pulled in by serde_json | | serde_core, serde_derive, proc-macro2, quote, syn, unicode-ident | MIT OR Apache-2.0; unicode-ident (MIT OR Apache-2.0) AND Unicode-3.0 | serde's derive, compiled at build time | @@ -45,7 +49,25 @@ FormShot 0.4.0 is unreleased. Licences marked "to confirm" below were not read f | Vite 8.3.5 with rolldown, postcss and lightningcss | MIT; lightningcss MPL-2.0 | builds the window; lightningcss is used unmodified at build time and none of it is in the app | | TypeScript 7.0.2 | Apache-2.0 | type check | | @tauri-apps/cli 2.12.5 | Apache-2.0 OR MIT | desktop builds | +| cc 1.12.0, find-msvc-tools 0.1.16, shlex 2.0.1 | MIT OR Apache-2.0 | compile ufbx's C source when the engine is built; none of it is in the app | + +## Downloaded on request, not shipped + +| Program | License | Notes | +| --- | --- | --- | +| FormCAD kernel worker `formcad-kernel` (release occt-8.0.1, built on OpenCascade by nodemode-ai) | as listed in its release record `occt-licence.json`, which is pinned by SHA-256 and checked before install | opens STEP and IGES files; downloaded into the user cache folder only when the person asks (`./formshot cad fetch` or Preferences > CAD Import), run as a separate process and never linked into FormShot | + +## Data in the material library + +The presets in `assets/library/` are our own work under Apache-2.0. Their numbers come from these sources, cited in each preset's `source` field and in `assets/library/README.md`: + +| Source | License | Used for | +| --- | --- | --- | +| refractiveindex.info database, M. N. Polyanskiy, Sci. Data 11, 94 (2024), commit e6d15e364f70de1cad8a96a20f75689f2fba8b21 | CC0 1.0 | optical constants of metals, alloys, glasses, polymers, liquids and crystals; each preset also cites the original measurement paper (for example K. M. McPeak et al., ACS Photonics 2, 326 (2015) for gold, silver, copper and aluminium) | +| CIE 1931 colour matching functions and illuminant D65, as tabulated in colour-science | CIE standard data; colour-science is BSD-3-Clause | spectra to colours at build time; nothing stored | +| USDA AMS Sucrose Conversion Table (Appendix XV) | US government work | refractive index of sugar solutions | +| MFA Boston CAMEO gemstone table, GIA Gem Encyclopedia, LibreTexts Gemology, orders of magnitude of luminance | facts cited, no text or tables copied | gem indices and dispersion, lamp and display luminance | ## Trademarks -glTF is a trademark of the Khronos Group Inc. Other names are the property of their owners. They are used only to describe compatibility and file formats; FormShot is not affiliated with or endorsed by them. FormShot's features carry its own names, and no other product's artwork, presets, materials or code are included. +glTF is a trademark of the Khronos Group Inc. FBX is a trademark of Autodesk, Inc. Other names are the property of their owners. They are used only to describe compatibility and file formats; FormShot is not affiliated with or endorsed by them. FormShot's features carry its own names, and no other product's artwork, presets, materials or code are included. diff --git a/README.md b/README.md index 49a082fd..534cd186 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version 0.4.0 + version 0.6.0 Rust TypeScript macOS, Windows, Linux @@ -65,7 +65,7 @@ ## Features -FormShot is at 0.4.0 and has not been released. This is what exists in the repository today: +FormShot is at 0.6.0 and has not been released. This is what exists in the repository today: - **The window.** Home with recent projects, four starting templates and a Trash you can restore from; the workspace with the live viewport, a material library panel, an inspector (Scene, Camera, Environment, Image and more) and a status bar; menus, a command palette, Preferences with a shortcut editor, 29 themes and the interface in English and 23 more languages. - **The live viewport.** Rendered, Material preview, Solid and Wireframe modes (the last three drawn in the window with WebGL2); click and box selection with a selection outline; a move, rotate and scale gizmo in world or local space with snapping; navigation presets for mouse, trackpad and touch; Frame Selection, Frame All, the six views and composition guides; light and camera outlines. While you move the camera the path tracer drops to fast low-resolution passes and climbs back to full resolution when you stop. A chip says what is drawing, on which device, and why the window is not drawing itself when it is not; the island menu picks the device, the viewport quality and adaptive sampling. @@ -74,8 +74,13 @@ FormShot is at 0.4.0 and has not been released. This is what exists in the repos - **The CPU path tracer.** The reference renderer: a deterministic sampler, a two-level BVH, next-event estimation with multiple importance sampling, environment importance sampling, the layered surface model, a procedural sky, a studio sweep, a shadow-catcher floor, a thin lens, the develop step (exposure and the Neutral, AgX, ACES, sRGB and raw transforms) and its own a-trous denoiser. - **The GPU path tracer.** The same picture as the CPU path tracer, written for Vulkan, Metal, Direct3D 12 and OpenGL, with its own BVH traversal and hardware ray queries where the device offers them. Adaptive sampling and reduced-resolution passes work on both engines. When the graphics card cannot render a scene, or fails while rendering, the processor takes over and a note says why. See [`docs/GPU-ENGINE.md`](docs/GPU-ENGINE.md). - **The engine in the window.** `./formshot engine wasm` builds the engine as WebAssembly so the window can path-trace through WebGPU itself, with a start-up guard that falls back to streamed frames from the service. See [`docs/VIEWPORT.md`](docs/VIEWPORT.md) and the limits below. -- **Files in and out.** Readers for glTF and GLB, OBJ with MTL, STL and PLY models with a clean-up pass (weld, normals, repeated parts, units, up axis, standing on the floor); PNG and Radiance HDR pictures read and written, OpenEXR (uncompressed float) written. -- **The command line.** `./formshot render model.glb out.png --samples 256` renders a picture without the window. `./formshot cli` runs the engine's own program, `formshot-engine`, with `render`, `info`, `convert`, `devices`, `bench`, `catalogue`, `dispatch`, `version` and `help`. Run so far: the sample scene renders byte-identical on 1 and 2 threads, a GLB and `.fshot` round trip renders the same picture from both files, and `bench` renders it on the processor, software Vulkan and software OpenGL within 0.00001 mean difference of each other. +- **Import.** Readers for glTF and GLB, OBJ with MTL, STL, PLY, 3MF and FBX (FBX in the desktop engine) with a clean-up pass (weld, normals, tangents, repeated parts also when rotated or mirrored, units with a guess you can check, up axis, standing on the floor). An import sheet shows what a file holds before anything changes, imports run in the background with progress and a Cancel that leaves the document untouched, and each import is one undo step. Texture maps arrive as material texture slots and PNG, JPEG, HDR and EXR images are kept inside the project. File > Reimport reads changed files again and keeps each part's material and identity. Drop files on the viewport or on Home. See [`docs/IMPORT.md`](docs/IMPORT.md). +- **STEP and IGES.** Opened by FormCAD's kernel worker, a separate program FormShot downloads on request and checks file by file (`./formshot cad fetch`, or Preferences > CAD Import). Assemblies, colours and shared parts come in at a quality you choose, the file is kept in the project, and Scene > Re-tessellate CAD Parts rebuilds parts at another quality without losing their materials. +- **Hand-offs from the Form apps.** What FormSculpt and FormFabric send through their GoF folder, FormSurface's painted maps and FormCAD's models are picked up while the window is open and offered for your yes first (decline, open once, always allow that app). +- **Materials.** One layered surface model with 18 types (plastics, metals with ten measured colours, paints, glass, liquids, gems, rubber, fabric, ceramic, emissive, wood, stone and more), texture slots with projections and transforms, and a node graph editor with image, maths, ramp, normal map and bump nodes and ten anti-aliased procedural patterns, image labels projected onto parts and placed with a click, thin-film iridescence (soap bubbles, anodised metals) and dispersion in glass and gems. Both path tracers render all of it, with PNG, JPEG, HDR and EXR textures filtered by the pixel's footprint; an image you choose is stored inside the project, and editing a material refreshes only the parts that wear it on either tracer. The Material page in the inspector edits them. See [`docs/MATERIALS.md`](docs/MATERIALS.md). +- **The material library.** 249 presets in twelve categories made from measured optical data and published tables, each citing its sources; search, favourites, recent and your own saved presets; thumbnails rendered by FormShot's own path tracer; apply by double-click or by dragging onto a part, to a part, its group or every part with the same material, as one undo step. See [`docs/LIBRARY.md`](docs/LIBRARY.md). +- **Pictures.** PNG and Radiance HDR read and written, OpenEXR read (scanline, uncompressed or RLE, ZIP, PIZ and PXR24) and written (uncompressed float), JPEG read. +- **The command line.** `./formshot render model.glb out.png --samples 256` renders a picture without the window. `./formshot cli` runs the engine's own program, `formshot-engine`, with `render`, `info`, `convert` (with import options), `probe`, `reimport`, `devices`, `bench`, `catalogue`, `dispatch`, `version` and `help`. Run so far: the sample scene renders byte-identical on 1 and 2 threads, a GLB and `.fshot` round trip renders the same picture from both files, and `bench` renders it on the processor, software Vulkan and software OpenGL within 0.00001 mean difference of each other. - **The agent dock.** A shell, Chat and tabs for Claude Code, Codex, Cursor and Antigravity, each connected to FormShot's MCP server. Everything else in this README marked planned is on the plan with the version it is due in, and is not built yet. @@ -99,8 +104,11 @@ The output names the device that drew the picture, and adds a `note:` line when - Hardware ray queries have run only on a software implementation (lavapipe), never on ray-tracing hardware. - The path tracer in the window (WebGPU) has not drawn a frame anywhere yet: the software WebGPU compiler runs out of memory on the kernel, and no browser with a real graphics card was available. The window uses streamed frames unless a real GPU proves otherwise. - Region render works on the GPU engine only: on the processor `render.region` answers that regions are not supported on that device yet and the whole picture renders. -- The GPU engine restarts the whole picture after a material change; only the CPU engine keeps the samples outside the edited parts. -- Edits made outside the window (by an agent or the command line) show in the window only after its next own change. +- Edits made with the command line run in their own engine process and do not show in an open window; edits by agents through the service and MCP do. +- Material preview shows texture slots, graphs and labels from small maps baked on a 1 m square, so projected and procedural materials are approximated there; the Rendered mode is exact. +- Textured materials in the window's own WebGPU path tracer have run only against a stand-in viewport; dispersion stays within the three colour channels, and shadows through glass are opaque. +- STEP and IGES through the CAD worker have run on Linux x86_64 only; the worker reports no progress inside one body. +- FBX is read by the desktop engine, not by the engine in the browser. - The Tauri desktop build has not been run on any platform. ## Everything in the box @@ -108,23 +116,23 @@ The output names the device that drew the picture, and adds a `note:` line when
-

Today (0.4.0)

- Home and projects · Scene tree · Camera, environment and image settings · CPU path tracer · GPU path tracer · Live viewport with raster modes, selection and gizmo · Region render on the GPU · Device choice and bench · Develop and tone maps · .fshot projects · Crash recovery commands · Command line render · MCP · Agent dock +

Today (0.6.0)

+ Home and projects · Scene tree · Camera, environment and image settings · CPU path tracer · GPU path tracer · Live viewport with raster modes, selection and gizmo · Region render on the GPU · Device choice and bench · Develop and tone maps · .fshot projects · Crash recovery commands · Import with background jobs and reimport · STEP and IGES through FormCAD's kernel · Hand-offs from the Form apps · Material types, texture slots, the node graph and labels, rendered on both tracers · Thin film and dispersion · Material library with 249 presets · Command line render · MCP · Agent dock

Planned

- The WebGPU path tracer in the window proven on a real graphics card, and region render on the CPU engine (after 0.4.0) · Import, CAD through FormCAD's kernel, materials and the library (0.5.0 to 0.6.0) · Lighting, cameras, output and denoising (0.7.0 to 0.8.0) · Shots, animation and advanced light transport (0.9.0 to 0.10.0) · Editors and exchange (0.11.0 to 0.12.0) · Agents, render farm and release (0.13.0 to 0.14.0) + The WebGPU path tracer in the window proven on a real graphics card, and region render on the CPU engine (after 0.4.0) · Lighting, cameras, output and denoising (0.7.0 to 0.8.0) · Shots, animation and advanced light transport (0.9.0 to 0.10.0) · Editors and exchange (0.11.0 to 0.12.0) · Agents, render farm and release (0.13.0 to 0.14.0)

Formats

- Native: .fshot · Models in: glTF/GLB, OBJ, STL, PLY · Pictures: PNG and HDR in and out, EXR out · Planned: 3MF, FBX, STEP and IGES in; TIFF, JPEG, PSD, video, GLB, USD out + Native: .fshot · Models in: glTF/GLB, OBJ, STL, PLY, 3MF, FBX, STEP, IGES · Pictures: PNG, HDR and EXR in and out, JPEG in; PNG, JPEG, HDR and EXR textures kept in projects · Planned: TIFF, JPEG, PSD, video, GLB, USD out
## Built for agents -The engine's 88 commands (39 document commands, 38 engine commands and 11 aliases) are listed in one catalogue built by `native/crates/fsh-commands`; the window, the command line and the MCP server all call them. +The engine's 121 commands (47 document commands, 38 engine commands, 25 import, CAD, hand-off, material and library commands, and 11 aliases) are listed in one catalogue built by `native/crates/fsh-commands`; the window, the command line and the MCP server all call them. ```sh ./formshot mcp # MCP server on stdio for Claude Code, Codex, Cursor and Antigravity @@ -172,7 +180,7 @@ cd formshot Render from the command line with `./formshot render model.glb out.png --samples 256` (also `--width`, `--height`, `--threads`, `--seed`, `--denoise` and `--device`). `./formshot engine wasm` builds the optional in-window engine; the window works without it. `./formshot desktop dev` opens the desktop window instead, after `./formshot install-desktop`. On Windows use `formshot_oc_install.bat` and `formshot.bat`. `FORMSHOT_DATA` moves the data folder and `FORMSHOT_PROJECTS` the projects folder (`~/Documents/FormShot` by default). > [!IMPORTANT] -> **Status:** pre-release. FormShot 0.4.0 has the shell, the document and project file, the CPU and GPU path tracers, the live viewport with region render on the GPU, and the command line render. It has not been built or tested as a desktop app on any platform yet, and GPU rendering has run only on software drivers (see [Known limits](#known-limits)). See [`CHANGELOG.md`](CHANGELOG.md). +> **Status:** pre-release. FormShot 0.6.0 has the shell, the document and project file, the CPU and GPU path tracers, the live viewport with region render on the GPU, and the command line render. It has not been built or tested as a desktop app on any platform yet, and GPU rendering has run only on software drivers (see [Known limits](#known-limits)). See [`CHANGELOG.md`](CHANGELOG.md). **Contributing:** branch from `main`, keep changes to source here, and leave packaging and releases to FormCompiler. See [`CONTRIBUTING.md`](CONTRIBUTING.md), [`.docs/BRANCHING.md`](.docs/BRANCHING.md) and [`AGENTS.md`](AGENTS.md). @@ -185,7 +193,7 @@ Render from the command line with `./formshot render model.glb out.png --samples | `backend/` · `src-tauri/` | FastAPI service · Tauri 2 desktop shell | | `setup/` · `mcp/` | the scripts behind `./formshot` · the MCP stdio bridge | -Docs: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md), [`docs/GPU-ENGINE.md`](docs/GPU-ENGINE.md), [`docs/VIEWPORT.md`](docs/VIEWPORT.md), [`.docs/wiki`](.docs/wiki), [`CHANGELOG.md`](CHANGELOG.md) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) +Docs: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md), [`docs/GPU-ENGINE.md`](docs/GPU-ENGINE.md), [`docs/VIEWPORT.md`](docs/VIEWPORT.md), [`docs/IMPORT.md`](docs/IMPORT.md), [`docs/MATERIALS.md`](docs/MATERIALS.md), [`docs/LIBRARY.md`](docs/LIBRARY.md), [`docs/FILE-FORMAT.md`](docs/FILE-FORMAT.md), [`.docs/wiki`](.docs/wiki), [`CHANGELOG.md`](CHANGELOG.md) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md)
diff --git a/SECURITY.md b/SECURITY.md index 5512da63..ca621989 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,7 +7,7 @@ FormShot has not been released yet. Until the first release, security fixes go i | Version | Supported | | --- | --- | -| `main` (0.4.0, unreleased) | Yes | +| `main` (0.6.0, unreleased) | Yes | | Anything older | No | ## Reporting a vulnerability diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 7eda5f54..c35588af 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -37,6 +37,22 @@ packages carry no licence file (among them objc2-metal, profiling and spirv), which need texts in setup/licence_texts before the generated file can replace this one. +The import work added three direct dependencies to fsh-io, listed in the crate +sections below: roxmltree (MIT OR Apache-2.0), bevy_mikktspace (Zlib AND (MIT +OR Apache-2.0)) and, in native builds only, ufbx (MIT OR Unlicense), which +compiles the ufbx C library into the engine. ufbx's crate package carries no +licence file, and bevy_mikktspace's carries no Zlib text; both need texts in +setup/licence_texts. Building ufbx pulls in cc, find-msvc-tools and shlex (all +MIT OR Apache-2.0), which run at build time only and are named in NOTICE.md. +The texture work added zune-jpeg (with zune-core; both MIT OR Apache-2.0 OR +Zlib, each with all three licence files) to fsh-io for JPEG textures; it is +compiled into the native engine and the WebAssembly engine. +The FormCAD kernel worker that opens STEP and IGES files is not shipped: it is +downloaded into the user cache on request and run as a separate program. +NOTICE.md also lists the data sources of the material library +(assets/library): the refractiveindex.info database (CC0 1.0) and the papers +each preset cites. + Build tools that do not ship (vite, rolldown, lightningcss, postcss, typescript, @tauri-apps/cli, maturin, pyinstaller apart from its bootloader) are named in NOTICE.md. @@ -191,6 +207,12 @@ Licence: MIT Source: https://www.npmjs.com/package/@xterm/xterm Note: Licence as declared by the package: read from its package.json in frontend/node_modules on 2026-12-02. The full licence text is added by ./formshot notices. +============================================================================== +crate: bevy_mikktspace 1.0.0 +Licence: Zlib AND (MIT OR Apache-2.0) +Source: https://crates.io/crates/bevy_mikktspace/1.0.0 +Note: Direct dependency of fsh-io (MikkTSpace tangents for imported meshes). Licence as declared by the package: read from its Cargo.toml in the local cargo registry on 2026-12-02. The package carries LICENSE-MIT and LICENSE-APACHE but no Zlib text; its README names the Zlib licence of the original MikkTSpace code, whose text ./formshot notices must take from setup/licence_texts. The full licence texts are added by ./formshot notices. + ============================================================================== crate: bytemuck 1.25.2 Licence: Zlib OR Apache-2.0 OR MIT @@ -281,6 +303,12 @@ Licence: MIT OR Apache-2.0 Source: https://crates.io/crates/rayon-core/1.13.0 Note: Licence as declared by the package: read from its Cargo.toml in the local cargo registry on 2026-12-02. The full licence text is added by ./formshot notices. +============================================================================== +crate: roxmltree 0.21.2 +Licence: MIT OR Apache-2.0 +Source: https://crates.io/crates/roxmltree/0.21.2 +Note: Direct dependency of fsh-io (the XML inside 3MF files). Licence as declared by the package: read from its Cargo.toml in the local cargo registry on 2026-12-02. The full licence text is added by ./formshot notices. + ============================================================================== crate: serde 1.0.229 Licence: MIT OR Apache-2.0 @@ -311,6 +339,12 @@ Licence: MIT OR Apache-2.0 Source: https://crates.io/crates/syn/3.0.10 Note: Licence as declared by the package: read from its Cargo.toml in the local cargo registry on 2026-12-02. The full licence text is added by ./formshot notices. +============================================================================== +crate: ufbx 0.11.5 +Licence: MIT OR Unlicense +Source: https://crates.io/crates/ufbx/0.11.5 +Note: Direct dependency of fsh-io in native builds only (FBX files); it compiles the ufbx C library into the engine. Licence as declared by the package's Cargo.toml in the local cargo registry on 2026-12-02. The package carries no licence file; the upstream repository's LICENSE (https://github.com/ufbx/ufbx) gives MIT or public domain, and FormShot uses it under MIT, whose text ./formshot notices must take from setup/licence_texts. + ============================================================================== crate: unicode-ident 1.0.27 Licence: (MIT OR Apache-2.0) AND Unicode-3.0 @@ -383,6 +417,18 @@ Licence: MIT Source: https://crates.io/crates/zmij/1.0.23 Note: Licence as declared by the package: read from its Cargo.toml in the local cargo registry on 2026-12-02. The full licence text is added by ./formshot notices. +============================================================================== +crate: zune-core 0.5.4 +Licence: MIT OR Apache-2.0 OR Zlib +Source: https://crates.io/crates/zune-core/0.5.4 +Note: Pulled in by zune-jpeg. Licence as declared by the package: read from its Cargo.toml in the local cargo registry on 2026-12-02; the package carries LICENSE-MIT, LICENSE-APACHE and LICENSE-ZLIB. The full licence text is added by ./formshot notices. + +============================================================================== +crate: zune-jpeg 0.5.15 +Licence: MIT OR Apache-2.0 OR Zlib +Source: https://crates.io/crates/zune-jpeg/0.5.15 +Note: Direct dependency of fsh-io (JPEG textures), also in the WebAssembly engine. Licence as declared by the package: read from its Cargo.toml in the local cargo registry on 2026-12-02; the package carries LICENSE-MIT, LICENSE-APACHE and LICENSE-ZLIB. The full licence text is added by ./formshot notices. + ============================================================================== Shared licence texts diff --git a/VERSION b/VERSION index 1d0ba9ea..a918a2aa 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.0 +0.6.0 diff --git a/agents/manifest.json b/agents/manifest.json index 393c207f..a7fdf6ef 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -18,6 +18,7 @@ "scene.set_part_colour", "scene.set_metadata", "scene.set_pivot", + "scene.set_part_mesh", "scene.set_light", "scene.set_cutaway", "scene.reparent", @@ -28,6 +29,13 @@ "material.create", "material.set_params", "material.set_type", + "material.set_slot", + "material.clear_slot", + "material.set_graph", + "material.label_add", + "material.label_set", + "material.label_remove", + "material.label_move", "material.assign", "material.rename", "material.remove", @@ -81,6 +89,31 @@ "scene.meshes", "scene.mesh_data", "view.frame", + "import.probe", + "import.start", + "import.status", + "import.cancel", + "file.reimport", + "cad.status", + "scene.retessellate", + "cad.parts", + "handoff.inspect", + "handoff.open", + "material.types", + "material.node_kinds", + "material.program", + "material.preview_maps", + "material.get", + "material.labels", + "library.list", + "library.get", + "library.favorite", + "library.recent", + "library.apply", + "library.save", + "library.remove", + "library.thumbnail", + "library.thumbnails", "node.set_visible", "node.set_locked", "node.rename", @@ -105,7 +138,23 @@ "view.bounds", "view.pick", "scene.meshes", - "scene.mesh_data" + "scene.mesh_data", + "import.probe", + "import.status", + "cad.status", + "cad.parts", + "handoff.inspect", + "material.types", + "material.node_kinds", + "material.program", + "material.preview_maps", + "material.get", + "material.labels", + "library.list", + "library.get", + "library.recent", + "library.thumbnail", + "library.thumbnails" ], "approval_gated": [ "scene.add_group", @@ -122,6 +171,7 @@ "scene.set_part_colour", "scene.set_metadata", "scene.set_pivot", + "scene.set_part_mesh", "scene.set_light", "scene.set_cutaway", "scene.reparent", @@ -132,6 +182,13 @@ "material.create", "material.set_params", "material.set_type", + "material.set_slot", + "material.clear_slot", + "material.set_graph", + "material.label_add", + "material.label_set", + "material.label_remove", + "material.label_move", "material.assign", "material.rename", "material.remove", @@ -173,6 +230,15 @@ "render.region", "render.viewport", "view.frame", + "import.start", + "import.cancel", + "file.reimport", + "scene.retessellate", + "handoff.open", + "library.favorite", + "library.apply", + "library.save", + "library.remove", "node.set_visible", "node.set_locked", "node.rename", @@ -195,6 +261,7 @@ "name": "formshot-harness", "sub_skills": [ "agent-substrate", + "cad-and-handoffs", "command-registry", "cpu-tracer", "desktop-shell", @@ -202,6 +269,7 @@ "engine-service", "gpu-tracer", "io-formats", + "material-library", "materials", "scene-document", "ui-shell", diff --git a/assets/library/README.md b/assets/library/README.md new file mode 100644 index 00000000..96dab60f --- /dev/null +++ b/assets/library/README.md @@ -0,0 +1,46 @@ +# FormShot material library + +Material presets for the Library window. Every preset here is our own work, written from public physical data, and is licensed with the rest of FormShot under Apache-2.0 (each file says so in its `licence` field). No preset, name or description comes from another renderer's library. + +## Layout + +- `materials//.json`: one preset per file. Categories, in the window's order: Metal, Plastic, Glass, Paint, Rubber, Fabric, Wood, Stone, Ceramic, Liquid, Gem, Emissive. The folder is the category in lower case. +- `materials/index.json`: every preset with its id, name, category, type, tags, file and the SHA-256 of the file. + +## Preset format (version 1) + +``` +{format: "formshot-material-preset", version: 1, id, name, category, type, params, tags, source, licence} +``` + +- `id` is `/`, stable for good: favourites, thumbnails and documents refer to it. +- `type` is a material type id (`metal`, `metal_brushed`, `plastic`, `plastic_clear`, `paint`, `paint_metallic`, `glass`, `glass_thin`, `liquid`, `gem`, `rubber`, `fabric`, `ceramic`, `diffuse`, `emissive`, `wood`, `stone`, `generic`). +- `params` uses the field names of the engine's surface model (`SurfaceParams` in fsh-scene, which follows the OpenPBR Surface parameter names). Applying a preset starts from the type's defaults and sets every key in `params`. Version 1 presets store the full value of every field that defines their look. +- Colours are scene-linear ACEScg, the engine's working space. Lengths are metres, except `thin_film_thickness` in micrometres. `emission_luminance` is in nits (cd/m2) and `emission_color` is normalised to luminance 1, so the number is the surface's luminance. +- `source` says where each number came from: `kind` is `measured`, `published` or `authored`; `reference` and `urls` cite the data; `notes` explains derivations and the reasoning behind authored values; `authored` lists the parameters we chose ourselves (roughness of a finish, the colour of a dyed plastic) when the rest of the preset is measured or published. + +## Sources and licences + +| Source | Used for | Licence | +| --- | --- | --- | +| refractiveindex.info database, M. N. Polyanskiy, Sci. Data 11, 94 (2024), https://github.com/polyanskiy/refractiveindex.info-database (commit e6d15e364f70de1cad8a96a20f75689f2fba8b21) | Complex refractive index n and k of metals and alloys; refractive index and dispersion of glasses, polymers, liquids and crystals; absorption of water and window glasses | CC0 1.0 | +| CIE 1931 2 degree colour matching functions and CIE illuminant D65, as tabulated in the colour-science Python package (BSD-3-Clause), https://github.com/colour-science/colour | Turning spectra into colours (used only by the conversion, not stored) | CIE standard data; package BSD-3-Clause | +| USDA AMS, Sucrose Conversion Table, Technical Procedures Manual Appendix XV, https://www.ams.usda.gov/sites/default/files/media/SucroseConversionTableXV.pdf | Refractive index of sugar solutions (juices, syrups, soft drinks) | US federal government work | +| Museum of Fine Arts Boston, CAMEO, Gemstone properties table, https://cameo.mfa.org/wiki/Gemstone | Refractive index and dispersion of gems without n data in the database | Facts cited, nothing copied | +| GIA Gem Encyclopedia, emerald facts, https://www.gia.edu/emerald/gem-overview | Emerald refractive index | Facts cited, nothing copied | +| LibreTexts Geosciences, Gemology, Emerald, https://geo.libretexts.org/Bookshelves/Geology/Gemology/16%3A_Gemstones/16.04%3A_Beryl/16.4.03%3A_Emerald | Beryl dispersion (emerald, aquamarine) | Facts cited, nothing copied | +| Orders of magnitude (luminance), https://en.wikipedia.org/wiki/Orders_of_magnitude_(illuminance)#Luminance | Luminance of displays and lamps | Facts cited, nothing copied | + +Only numbers are taken from these sources; the presets, names and notes are ours. + +## How the numbers were made + +- Metals: the base colour is the normal-incidence Fresnel reflectance of the measured n and k, and the edge tint (`specular_color`) is the F82 tint of the OpenPBR metal model: the ratio of the true reflectance at 82 degrees (cosine 1/7) to the Schlick curve through the base colour. Each reflectance spectrum (380 to 780 nm, 5 nm steps) is integrated against the CIE 1931 colour matching functions under D65, normalised so a perfect reflector is white, converted to linear sRGB and then to ACEScg with the engine's matrix. The fitted F0 and tint reproduce the true reflectance at every angle to within 0.043 (27 of the 32 measured metals within 0.03); each preset's notes give its own figure. +- Dielectrics: `specular_ior` is n at 587.6 nm; the Abbe number is (nd - 1) / (nF - nC) at 587.6, 486.1 and 656.3 nm. For gems quoted with a B-G dispersion (nG - nB), the Abbe number uses nF - nC = 0.5845 (nG - nB), which follows from Cauchy's two-term formula. +- Absorbing transparent materials (water, window glasses): `transmission_color` is the Beer-Lambert transmittance exp(-4 pi k d / lambda) at `transmission_depth` d, integrated to a colour like the metals. +- Emitters: `emission_color` is the colour of a blackbody at the lamp's colour temperature, or of the emission line, normalised to luminance 1. +- Authored values (finish roughness, dye and pigment colours, coat settings) are recorded in each preset's `source.authored` and explained in `source.notes`; authored colours give the 8-bit sRGB value they were picked as. + +## Adding a preset + +Write the file by hand in the format above, add its entry to `materials/index.json` (keep the order: category, then name) with the file's SHA-256, and keep the whole library under 2 MB. Cite every measured or published number; list every chosen one in `authored`. diff --git a/assets/library/materials/ceramic/alumina-technical.json b/assets/library/materials/ceramic/alumina-technical.json new file mode 100644 index 00000000..4ae84cac --- /dev/null +++ b/assets/library/materials/ceramic/alumina-technical.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/alumina-technical", + "name": "Alumina ceramic, technical", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.8871, 0.88, 0.8305], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.3, + "specular_ior": 1.7682, + "coat_weight": 0.0 + }, + "tags": ["ceramic", "satin", "white", "opaque", "industrial"], + "source": { + "kind": "published", + "reference": "I. H. Malitson. Refraction and dispersion of synthetic sapphire. J. Opt. Soc. Am. 52, 1377-1379 (1962); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al2O3/nk/Malitson.yml"], + "notes": "Sintered aluminium oxide, as in insulators and wear parts. specular_ior 1.7682 is the measured ordinary index of sapphire (Al2O3) at 587.6 nm. Colour sRGB #f3f1ea and roughness 0.3 (ground finish) authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/bisque-white-unglazed.json b/assets/library/materials/ceramic/bisque-white-unglazed.json new file mode 100644 index 00000000..2a1bc2e8 --- /dev/null +++ b/assets/library/materials/ceramic/bisque-white-unglazed.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/bisque-white-unglazed", + "name": "Bisque, unglazed white", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.8161, 0.7934, 0.7138], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.8, + "specular_roughness": 0.8, + "specular_ior": 1.5, + "coat_weight": 0.0 + }, + "tags": ["ceramic", "matte", "white", "opaque", "tableware"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Unglazed porous body, white body after the first firing: coat off, very rough. Colour sRGB #ece6da, roughness 0.8, diffuse roughness 0.8 and ior 1.5 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/glazed-black.json b/assets/library/materials/ceramic/glazed-black.json new file mode 100644 index 00000000..14f6c62a --- /dev/null +++ b/assets/library/materials/ceramic/glazed-black.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/glazed-black", + "name": "Glazed ceramic, black", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.007, 0.007, 0.007], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5234, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["ceramic", "gloss", "coat", "black", "opaque", "tableware"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "Fired body under a glaze. The glaze is a silicate glass, so coat_ior 1.5234 is the measured n of soda-lime glass at 587.6 nm. Body colour sRGB #141414, body roughness 0.4 and ior 1.5, and glaze roughness 0.03 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior", "coat_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/glazed-celadon.json b/assets/library/materials/ceramic/glazed-celadon.json new file mode 100644 index 00000000..7da84943 --- /dev/null +++ b/assets/library/materials/ceramic/glazed-celadon.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/glazed-celadon", + "name": "Glazed ceramic, celadon", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.4434, 0.5327, 0.3996], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.05, + "coat_ior": 1.5234, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["ceramic", "gloss", "coat", "green", "opaque", "tableware"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "Fired body under a glaze. The glaze is a silicate glass, so coat_ior 1.5234 is the measured n of soda-lime glass at 587.6 nm. Body colour sRGB #a8c3a6, body roughness 0.4 and ior 1.5, and glaze roughness 0.05 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior", "coat_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/glazed-cobalt-blue.json b/assets/library/materials/ceramic/glazed-cobalt-blue.json new file mode 100644 index 00000000..4079f8d6 --- /dev/null +++ b/assets/library/materials/ceramic/glazed-cobalt-blue.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/glazed-cobalt-blue", + "name": "Glazed ceramic, cobalt blue", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.0364, 0.0473, 0.2443], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5234, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["ceramic", "gloss", "coat", "blue", "opaque", "tableware"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "Fired body under a glaze. The glaze is a silicate glass, so coat_ior 1.5234 is the measured n of soda-lime glass at 587.6 nm. Body colour sRGB #1d3d8f, body roughness 0.4 and ior 1.5, and glaze roughness 0.03 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior", "coat_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/glazed-tile-white.json b/assets/library/materials/ceramic/glazed-tile-white.json new file mode 100644 index 00000000..eadda18f --- /dev/null +++ b/assets/library/materials/ceramic/glazed-tile-white.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/glazed-tile-white", + "name": "Glazed tile, white", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.8663, 0.8632, 0.8282], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5234, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["ceramic", "gloss", "coat", "white", "opaque", "architectural"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "Fired body under a glaze. The glaze is a silicate glass, so coat_ior 1.5234 is the measured n of soda-lime glass at 587.6 nm. Body colour sRGB #f0efea, body roughness 0.4 and ior 1.5, and glaze roughness 0.02 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior", "coat_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/glazed-white.json b/assets/library/materials/ceramic/glazed-white.json new file mode 100644 index 00000000..da038a26 --- /dev/null +++ b/assets/library/materials/ceramic/glazed-white.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/glazed-white", + "name": "Glazed ceramic, white", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.8828, 0.8797, 0.8443], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5234, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["ceramic", "gloss", "coat", "white", "opaque", "tableware"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "Fired body under a glaze. The glaze is a silicate glass, so coat_ior 1.5234 is the measured n of soda-lime glass at 587.6 nm. Body colour sRGB #f2f1ec, body roughness 0.4 and ior 1.5, and glaze roughness 0.03 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior", "coat_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/porcelain-glazed.json b/assets/library/materials/ceramic/porcelain-glazed.json new file mode 100644 index 00000000..6c72a40b --- /dev/null +++ b/assets/library/materials/ceramic/porcelain-glazed.json @@ -0,0 +1,32 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/porcelain-glazed", + "name": "Porcelain, glazed", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.8998, 0.8964, 0.8676], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.2, + "specular_roughness": 0.3, + "specular_ior": 1.5, + "subsurface_weight": 0.4, + "subsurface_color": [0.8923, 0.8806, 0.8307], + "subsurface_radius": 0.003, + "subsurface_radius_scale": [1.0, 0.85, 0.7], + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5234, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["ceramic", "gloss", "coat", "subsurface", "white", "tableware"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "Vitrified porcelain is slightly translucent: subsurface weight 0.4, 3 mm mean free path, warmer in red (authored). Glaze coat_ior 1.5234 is the measured n of soda-lime glass; colours sRGB #f4f3ef and #f4f1ea, roughness values authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior", "subsurface_weight", "subsurface_color", "subsurface_radius", "subsurface_radius_scale", "coat_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/stoneware-matte-glaze.json b/assets/library/materials/ceramic/stoneware-matte-glaze.json new file mode 100644 index 00000000..b67e4318 --- /dev/null +++ b/assets/library/materials/ceramic/stoneware-matte-glaze.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/stoneware-matte-glaze", + "name": "Stoneware, matte glaze", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.6022, 0.5798, 0.5084], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.35, + "coat_ior": 1.5234, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["ceramic", "matte", "coat", "grey", "opaque", "tableware"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "Fired body under a glaze. The glaze is a silicate glass, so coat_ior 1.5234 is the measured n of soda-lime glass at 587.6 nm. Body colour sRGB #cfc8bb, body roughness 0.4 and ior 1.5, and glaze roughness 0.35 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior", "coat_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/ceramic/terracotta-unglazed.json b/assets/library/materials/ceramic/terracotta-unglazed.json new file mode 100644 index 00000000..191ad063 --- /dev/null +++ b/assets/library/materials/ceramic/terracotta-unglazed.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "ceramic/terracotta-unglazed", + "name": "Terracotta, unglazed", + "category": "Ceramic", + "type": "ceramic", + "params": { + "base_color": [0.327, 0.145, 0.0635], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.8, + "specular_roughness": 0.8, + "specular_ior": 1.5, + "coat_weight": 0.0 + }, + "tags": ["ceramic", "matte", "orange", "opaque", "architectural"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Unglazed porous body, iron-rich earthenware fired red: coat off, very rough. Colour sRGB #b5623d, roughness 0.8, diffuse roughness 0.8 and ior 1.5 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/display-white-srgb.json b/assets/library/materials/emissive/display-white-srgb.json new file mode 100644 index 00000000..e64d3889 --- /dev/null +++ b/assets/library/materials/emissive/display-white-srgb.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/display-white-srgb", + "name": "Display white, sRGB reference", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 80.0, + "emission_color": [0.9036, 1.0316, 1.092] + }, + "tags": ["light-source", "emissive", "display", "white", "electronics"], + "source": { + "kind": "published", + "reference": "IEC 61966-2-1 (sRGB) reference display luminance 80 cd/m2; Orders of magnitude (luminance), Wikipedia, luminance table and its cited sources", + "urls": ["https://en.wikipedia.org/wiki/Orders_of_magnitude_(illuminance)#Luminance"], + "notes": "Luminance 80 nits, the sRGB reference display white. emission_color is CIE D65 (the sRGB white point) normalised to luminance 1. Base black, roughness 0.3 for the screen's front glass, authored.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/electroluminescent-green.json b/assets/library/materials/emissive/electroluminescent-green.json new file mode 100644 index 00000000..40eb6f56 --- /dev/null +++ b/assets/library/materials/emissive/electroluminescent-green.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/electroluminescent-green", + "name": "Electroluminescent panel, green", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 30.0, + "emission_color": [0.0, 1.4378, 0.5737] + }, + "tags": ["light-source", "emissive", "green", "display"], + "source": { + "kind": "published", + "reference": "Orders of magnitude (luminance), Wikipedia, luminance table and its cited sources", + "urls": ["https://en.wikipedia.org/wiki/Orders_of_magnitude_(illuminance)#Luminance"], + "notes": "Luminance 30 nits, a green electroluminescent source. emission_color is a band centred at 510 nm, 25 nm wide (authored from the typical zinc sulphide copper phosphor), normalised to luminance 1. Roughness authored.", + "authored": ["emission_color", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/fluorescent-tube-4000k.json b/assets/library/materials/emissive/fluorescent-tube-4000k.json new file mode 100644 index 00000000..ca1b63b3 --- /dev/null +++ b/assets/library/materials/emissive/fluorescent-tube-4000k.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/fluorescent-tube-4000k", + "name": "Fluorescent tube, 4000 K", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 12000.0, + "emission_color": [1.0966, 0.9883, 0.6569] + }, + "tags": ["light-source", "emissive", "white", "lighting"], + "source": { + "kind": "published", + "reference": "Orders of magnitude (luminance), Wikipedia, luminance table and its cited sources", + "urls": ["https://en.wikipedia.org/wiki/Orders_of_magnitude_(illuminance)#Luminance"], + "notes": "Luminance 12000 nits, a fluorescent lamp. emission_color is a 4000 K blackbody normalised to luminance 1; the colour temperature is authored (neutral white tube). Roughness authored.", + "authored": ["emission_color", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/hdr-display-peak.json b/assets/library/materials/emissive/hdr-display-peak.json new file mode 100644 index 00000000..4fda5f2f --- /dev/null +++ b/assets/library/materials/emissive/hdr-display-peak.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/hdr-display-peak", + "name": "HDR display, peak white", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 1000.0, + "emission_color": [0.9036, 1.0316, 1.092] + }, + "tags": ["light-source", "emissive", "display", "white", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Luminance 1000 nits authored: the peak level HDR televisions and monitors are commonly graded to. D65 white normalised to luminance 1. Roughness authored.", + "authored": ["base_color", "specular_roughness", "emission_luminance", "emission_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/incandescent-frosted-2700k.json b/assets/library/materials/emissive/incandescent-frosted-2700k.json new file mode 100644 index 00000000..aefc2253 --- /dev/null +++ b/assets/library/materials/emissive/incandescent-frosted-2700k.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/incandescent-frosted-2700k", + "name": "Incandescent bulb, frosted", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 130000.0, + "emission_color": [1.3466, 0.9131, 0.3332] + }, + "tags": ["light-source", "emissive", "orange", "lighting"], + "source": { + "kind": "published", + "reference": "Orders of magnitude (luminance), Wikipedia, luminance table and its cited sources", + "urls": ["https://en.wikipedia.org/wiki/Orders_of_magnitude_(illuminance)#Luminance"], + "notes": "Luminance 130000 nits, a frosted incandescent bulb. emission_color is a 2700 K blackbody normalised to luminance 1, the usual colour temperature of a household tungsten lamp (authored). Roughness authored.", + "authored": ["emission_color", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/indicator-led-red.json b/assets/library/materials/emissive/indicator-led-red.json new file mode 100644 index 00000000..62024430 --- /dev/null +++ b/assets/library/materials/emissive/indicator-led-red.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/indicator-led-red", + "name": "Indicator LED, red", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 5000.0, + "emission_color": [3.5049, 0.0667, 0.0175] + }, + "tags": ["light-source", "emissive", "red", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "A small red status LED seen through its diffusing lens: 5000 nits authored; emission_color a 630 nm band 10 nm wide (typical AlGaInP red), normalised to luminance 1. Roughness authored.", + "authored": ["base_color", "specular_roughness", "emission_luminance", "emission_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/light-box-6500k.json b/assets/library/materials/emissive/light-box-6500k.json new file mode 100644 index 00000000..35ec9ba7 --- /dev/null +++ b/assets/library/materials/emissive/light-box-6500k.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/light-box-6500k", + "name": "Light box, daylight", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 2000.0, + "emission_color": [0.9036, 1.0316, 1.092] + }, + "tags": ["light-source", "emissive", "white", "lighting"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "A diffuser panel for product lighting: 2000 nits authored, bright enough to key a product without clipping a typical exposure. D65 white normalised to luminance 1. Roughness authored.", + "authored": ["base_color", "specular_roughness", "emission_luminance", "emission_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/monitor-white-lcd.json b/assets/library/materials/emissive/monitor-white-lcd.json new file mode 100644 index 00000000..9634dc6a --- /dev/null +++ b/assets/library/materials/emissive/monitor-white-lcd.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/monitor-white-lcd", + "name": "LCD monitor, white", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 250.0, + "emission_color": [0.9036, 1.0316, 1.092] + }, + "tags": ["light-source", "emissive", "display", "white", "electronics"], + "source": { + "kind": "published", + "reference": "Orders of magnitude (luminance), Wikipedia, luminance table and its cited sources", + "urls": ["https://en.wikipedia.org/wiki/Orders_of_magnitude_(illuminance)#Luminance"], + "notes": "Luminance 250 nits, the peak of a typical LCD monitor. emission_color is D65 normalised to luminance 1. Roughness authored.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/emissive/sodium-lamp-low-pressure.json b/assets/library/materials/emissive/sodium-lamp-low-pressure.json new file mode 100644 index 00000000..e0d771ab --- /dev/null +++ b/assets/library/materials/emissive/sodium-lamp-low-pressure.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "emissive/sodium-lamp-low-pressure", + "name": "Sodium lamp, low pressure", + "category": "Emissive", + "type": "emissive", + "params": { + "base_color": [0.0, 0.0, 0.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "emission_luminance": 75000.0, + "emission_color": [1.9191, 0.7077, 0.0099] + }, + "tags": ["light-source", "emissive", "orange", "lighting"], + "source": { + "kind": "published", + "reference": "Orders of magnitude (luminance), Wikipedia, luminance table and its cited sources", + "urls": ["https://en.wikipedia.org/wiki/Orders_of_magnitude_(illuminance)#Luminance"], + "notes": "Luminance 75000 nits, a low-pressure sodium lamp. emission_color is the 589.3 nm sodium D line, integrated with CIE 1931 and normalised to luminance 1 (it lies inside the ACEScg gamut). Roughness authored.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/cotton-navy.json b/assets/library/materials/fabric/cotton-navy.json new file mode 100644 index 00000000..c699bc20 --- /dev/null +++ b/assets/library/materials/fabric/cotton-navy.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/cotton-navy", + "name": "Cotton, navy", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.019, 0.023, 0.0531], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.124, 0.1428, 0.246], + "fuzz_roughness": 0.5, + "specular_ior": 1.4701 + }, + "tags": ["natural-fibre", "fuzz", "matte", "blue", "apparel"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #1f2a44 and fuzz colour sRGB #5a6a8c authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.5 authored. specular_ior 1.4701 is the measured n of cotton (cellulose) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/cotton-red.json b/assets/library/materials/fabric/cotton-red.json new file mode 100644 index 00000000..15f3c9ca --- /dev/null +++ b/assets/library/materials/fabric/cotton-red.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/cotton-red", + "name": "Cotton, red", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.2317, 0.0422, 0.0314], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.4754, 0.1772, 0.165], + "fuzz_roughness": 0.5, + "specular_ior": 1.4701 + }, + "tags": ["natural-fibre", "fuzz", "matte", "red", "apparel"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #a3242c and fuzz colour sRGB #d8686e authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.5 authored. specular_ior 1.4701 is the measured n of cotton (cellulose) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/cotton-white.json b/assets/library/materials/fabric/cotton-white.json new file mode 100644 index 00000000..dd3cf73e --- /dev/null +++ b/assets/library/materials/fabric/cotton-white.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/cotton-white", + "name": "Cotton, white", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.8335, 0.8307, 0.7899], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [1.0, 1.0, 1.0], + "fuzz_roughness": 0.5, + "specular_ior": 1.4701 + }, + "tags": ["natural-fibre", "fuzz", "matte", "white", "apparel"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #ecebe5 and fuzz colour sRGB #ffffff authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.5 authored. specular_ior 1.4701 is the measured n of cotton (cellulose) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/denim-blue.json b/assets/library/materials/fabric/denim-blue.json new file mode 100644 index 00000000..ad697fca --- /dev/null +++ b/assets/library/materials/fabric/denim-blue.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/denim-blue", + "name": "Denim, indigo", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.0414, 0.0565, 0.1224], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.3174, 0.3619, 0.499], + "fuzz_roughness": 0.55, + "specular_ior": 1.4701 + }, + "tags": ["natural-fibre", "fuzz", "matte", "blue", "apparel"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #2c4466 and fuzz colour sRGB #8fa3bf authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.55 authored. specular_ior 1.4701 is the measured n of cotton (cellulose) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/felt-charcoal.json b/assets/library/materials/fabric/felt-charcoal.json new file mode 100644 index 00000000..0f974a27 --- /dev/null +++ b/assets/library/materials/fabric/felt-charcoal.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/felt-charcoal", + "name": "Felt, charcoal", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.0439, 0.0438, 0.0463], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.2022, 0.2017, 0.214], + "fuzz_roughness": 0.8, + "specular_ior": 1.55 + }, + "tags": ["natural-fibre", "fuzz", "matte", "grey", "apparel"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #3b3b3d and fuzz colour sRGB #7c7c80 authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.8 authored. specular_ior 1.55 authored: the commonly quoted index of keratin fibre (wool).", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/linen-natural.json b/assets/library/materials/fabric/linen-natural.json new file mode 100644 index 00000000..d659190d --- /dev/null +++ b/assets/library/materials/fabric/linen-natural.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/linen-natural", + "name": "Linen, natural", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.546, 0.5067, 0.3814], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.7549, 0.719, 0.5859], + "fuzz_roughness": 0.6, + "specular_ior": 1.4701 + }, + "tags": ["natural-fibre", "fuzz", "matte", "brown", "apparel"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #c9bca2 and fuzz colour sRGB #e6dcc6 authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.6 authored. specular_ior 1.4701 is the measured n of linen (cellulose) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/polyester-black.json b/assets/library/materials/fabric/polyester-black.json new file mode 100644 index 00000000..5810196f --- /dev/null +++ b/assets/library/materials/fabric/polyester-black.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/polyester-black", + "name": "Polyester, black", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.007, 0.007, 0.007], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.1022, 0.1022, 0.1022], + "fuzz_roughness": 0.45, + "specular_ior": 1.5693 + }, + "tags": ["synthetic-fibre", "fuzz", "matte", "black", "apparel"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C10H8O4)n%20-%20polyethylene%20terephthalate/nk/Zhang.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #141414 and fuzz colour sRGB #5a5a5a authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.45 authored. specular_ior 1.5693 is the measured n of polyester (PET) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/polyester-grey.json b/assets/library/materials/fabric/polyester-grey.json new file mode 100644 index 00000000..d62f4be8 --- /dev/null +++ b/assets/library/materials/fabric/polyester-grey.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/polyester-grey", + "name": "Polyester, grey", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.198, 0.2013, 0.2139], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.4619, 0.4673, 0.4878], + "fuzz_roughness": 0.45, + "specular_ior": 1.5693 + }, + "tags": ["synthetic-fibre", "fuzz", "matte", "grey", "apparel"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C10H8O4)n%20-%20polyethylene%20terephthalate/nk/Zhang.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #7a7c80 and fuzz colour sRGB #b4b6ba authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.45 authored. specular_ior 1.5693 is the measured n of polyester (PET) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/silk-ivory.json b/assets/library/materials/fabric/silk-ivory.json new file mode 100644 index 00000000..d64d370c --- /dev/null +++ b/assets/library/materials/fabric/silk-ivory.json @@ -0,0 +1,29 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/silk-ivory", + "name": "Silk, ivory", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.8046, 0.7712, 0.6442], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_weight": 0.6, + "specular_roughness": 0.35, + "specular_ior": 1.5503, + "specular_roughness_anisotropy": 0.5, + "fuzz_weight": 0.3, + "fuzz_color": [1.0, 1.0, 1.0], + "fuzz_roughness": 0.4 + }, + "tags": ["natural-fibre", "fuzz", "satin", "anisotropic", "white", "apparel"], + "source": { + "kind": "published", + "reference": "G. Perotto, Y. Zhang, D. Naskar, N. Patel, D. L. Kaplan, S. C. Kundu, F. G. Omenetto. The optical properties of regenerated silk fibroin films obtained from different sources. Appl. Phys. Lett. 111, 103702 (2017); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/silk/Bombyx%20mori/nk/Perotto-crystallized.yml"], + "notes": "Smooth filament silk: a stronger, anisotropic specular along the threads and little fuzz. specular_ior 1.5503 is the measured n of crystallised Bombyx mori fibroin at 587.6 nm. Colour sRGB #ece3cf, specular weight 0.6, roughness 0.35, anisotropy 0.5 and fuzz 0.3 authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "specular_roughness_anisotropy", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/velvet-black.json b/assets/library/materials/fabric/velvet-black.json new file mode 100644 index 00000000..10a98cb6 --- /dev/null +++ b/assets/library/materials/fabric/velvet-black.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/velvet-black", + "name": "Velvet, black", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.0037, 0.0037, 0.0037], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.147, 0.147, 0.147], + "fuzz_roughness": 0.3, + "specular_ior": 1.5693 + }, + "tags": ["synthetic-fibre", "fuzz", "matte", "black", "furniture"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C10H8O4)n%20-%20polyethylene%20terephthalate/nk/Zhang.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #0c0c0c and fuzz colour sRGB #6b6b6b authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.3 authored, low for the upright pile of velvet. specular_ior 1.5693 is the measured n of polyester (PET) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/velvet-burgundy.json b/assets/library/materials/fabric/velvet-burgundy.json new file mode 100644 index 00000000..1c7d355a --- /dev/null +++ b/assets/library/materials/fabric/velvet-burgundy.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/velvet-burgundy", + "name": "Velvet, burgundy", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.044, 0.009, 0.0109], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.2924, 0.0896, 0.1048], + "fuzz_roughness": 0.3, + "specular_ior": 1.5693 + }, + "tags": ["synthetic-fibre", "fuzz", "matte", "red", "furniture"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C10H8O4)n%20-%20polyethylene%20terephthalate/nk/Zhang.yml"], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #4a0e1a and fuzz colour sRGB #b0475a authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.3 authored, low for the upright pile of velvet. specular_ior 1.5693 is the measured n of polyester (PET) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/wool-camel.json b/assets/library/materials/fabric/wool-camel.json new file mode 100644 index 00000000..febaa5d9 --- /dev/null +++ b/assets/library/materials/fabric/wool-camel.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/wool-camel", + "name": "Wool, camel", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.3103, 0.2161, 0.1002], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.5797, 0.469, 0.292], + "fuzz_roughness": 0.7, + "specular_ior": 1.55 + }, + "tags": ["natural-fibre", "fuzz", "matte", "brown", "apparel"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #a77d50 and fuzz colour sRGB #d6b48c authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.7 authored. specular_ior 1.55 authored: the commonly quoted index of keratin fibre (wool).", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/fabric/wool-grey.json b/assets/library/materials/fabric/wool-grey.json new file mode 100644 index 00000000..3ee7ddd4 --- /dev/null +++ b/assets/library/materials/fabric/wool-grey.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "fabric/wool-grey", + "name": "Wool, grey", + "category": "Fabric", + "type": "fabric", + "params": { + "base_color": [0.2086, 0.2053, 0.1902], + "base_metalness": 0.0, + "base_diffuse_roughness": 1.0, + "specular_weight": 0.25, + "specular_roughness": 0.8, + "fuzz_weight": 1.0, + "fuzz_color": [0.5304, 0.5217, 0.4851], + "fuzz_roughness": 0.7, + "specular_ior": 1.55 + }, + "tags": ["natural-fibre", "fuzz", "matte", "grey", "apparel"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Woven or felted fibre: a rough diffuse base with a weak specular and a fuzz layer for the fibres standing off the surface. base_color sRGB #7f7d78 and fuzz colour sRGB #c2bfb8 authored (fuzz lighter, as stray fibres scatter un-dyed light); fuzz roughness 0.7 authored. specular_ior 1.55 authored: the commonly quoted index of keratin fibre (wool).", + "authored": ["base_color", "base_diffuse_roughness", "specular_weight", "specular_roughness", "fuzz_color", "fuzz_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/amethyst.json b/assets/library/materials/gem/amethyst.json new file mode 100644 index 00000000..03ac8443 --- /dev/null +++ b/assets/library/materials/gem/amethyst.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/amethyst", + "name": "Amethyst", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5443, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 69.7, + "transmission_color": [0.2051, 0.0959, 0.4307], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "purple", "tinted", "jewellery"], + "source": { + "kind": "measured", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.5443 is the measured n at 587.6 nm and the Abbe number 69.7 is (nd - 1)/(nF - nC) from the same data (ordinary ray; the small birefringence is not modelled). transmission_color authored as sRGB #8a4fb8, the violet of iron colour centres in quartz, reached through 0.005 m, a typical stone's depth.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/aquamarine.json b/assets/library/materials/gem/aquamarine.json new file mode 100644 index 00000000..44784c4e --- /dev/null +++ b/assets/library/materials/gem/aquamarine.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/aquamarine", + "name": "Aquamarine", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.58, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 70.9, + "transmission_color": [0.3989, 0.5757, 0.7192], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "blue", "tinted", "jewellery"], + "source": { + "kind": "published", + "reference": "Museum of Fine Arts Boston, CAMEO: Conservation and Art Materials Encyclopedia Online, Properties of Gemstones table; LibreTexts Geosciences, Gemology, Emerald: dispersion 0.014", + "urls": ["https://cameo.mfa.org/wiki/Gemstone", "https://geo.libretexts.org/Bookshelves/Geology/Gemology/16%3A_Gemstones/16.04%3A_Beryl/16.4.03%3A_Emerald"], + "notes": "Faceted stone, dispersion on. specular_ior 1.58: the mid value of beryl's ordinary index 1.574 to 1.586 (CAMEO); beryl dispersion 0.014 (LibreTexts Gemology). The Abbe number 70.9 is converted from the published B-G dispersion 0.014 (nG - nB) with nF - nC = 0.5845 (nG - nB), Cauchy's two-term relation. transmission_color authored as sRGB #8ccbe0, the sea blue of iron in beryl, through 0.005 m.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/chrysoberyl.json b/assets/library/materials/gem/chrysoberyl.json new file mode 100644 index 00000000..02cee621 --- /dev/null +++ b/assets/library/materials/gem/chrysoberyl.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/chrysoberyl", + "name": "Chrysoberyl", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.7428, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 73.9, + "transmission_color": [0.5463, 0.4991, 0.1266], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "yellow", "tinted", "jewellery"], + "source": { + "kind": "measured", + "reference": "J. Walling, O. Peterson, H. Jenssen, R. Morris, E. O'Dell. Tunable alexandrite lasers. IEEE J. Quantum Electron., 16, 1302-1315 (1980); P. Loiko, A. Major. Dispersive properties of alexandrite and beryllium hexaaluminate crystals. Opt. Mater. Express, 6, 2177-2183 (2016) * Ref. 2 provides a dispersion formula based on the experimental data from Ref. 1; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/BeAl2O4/nk/Walling-alpha.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.7428 is the measured n at 587.6 nm and the Abbe number 73.9 is (nd - 1)/(nF - nC) from the same data. transmission_color authored as sRGB #cdbb4a, the greenish yellow of iron in chrysoberyl, reached through 0.005 m, a typical stone's depth.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/citrine.json b/assets/library/materials/gem/citrine.json new file mode 100644 index 00000000..6b94bb0e --- /dev/null +++ b/assets/library/materials/gem/citrine.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/citrine", + "name": "Citrine", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5443, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 69.7, + "transmission_color": [0.6174, 0.41, 0.0788], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "yellow", "tinted", "jewellery"], + "source": { + "kind": "measured", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.5443 is the measured n at 587.6 nm and the Abbe number 69.7 is (nd - 1)/(nF - nC) from the same data (ordinary ray; the small birefringence is not modelled). transmission_color authored as sRGB #e6a72a, the golden yellow of heated or iron-bearing quartz, reached through 0.005 m, a typical stone's depth.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/cubic-zirconia.json b/assets/library/materials/gem/cubic-zirconia.json new file mode 100644 index 00000000..725355e2 --- /dev/null +++ b/assets/library/materials/gem/cubic-zirconia.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/cubic-zirconia", + "name": "Cubic zirconia", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 2.1476, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 33.5, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery", "synthetic"], + "source": { + "kind": "measured", + "reference": "R.A. Synowicki and T. E. Tiwald. Optical properties of bulk c-ZrO2, c-MgO and a-As2S3 determined by variable angle spectroscopic ellipsometry. Thin Solid Films 455-456, 248-255 (2004) Calculation scripts (Python): Synowicki 2004 - ZrO2.py, Synowicki 2004 - Aux funcs.py; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/ZrO2/nk/Synowicki.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 2.1476 is the measured n at 587.6 nm and the Abbe number 33.5 is (nd - 1)/(nF - nC) from the same data.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/diamond.json b/assets/library/materials/gem/diamond.json new file mode 100644 index 00000000..5f696c31 --- /dev/null +++ b/assets/library/materials/gem/diamond.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/diamond", + "name": "Diamond", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 2.4175, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 55.3, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery"], + "source": { + "kind": "measured", + "reference": "F. Peter. Über Brechungsindizes und Absorptionskonstanten des Diamanten zwischen 644 und 226 mμ. Zeitschrift für Physik 15, 358-368 (1923); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/C/nk/Peter.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 2.4175 is the measured n at 587.6 nm and the Abbe number 55.3 is (nd - 1)/(nF - nC) from the same data.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/emerald.json b/assets/library/materials/gem/emerald.json new file mode 100644 index 00000000..fe9988f6 --- /dev/null +++ b/assets/library/materials/gem/emerald.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/emerald", + "name": "Emerald", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.58, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 70.9, + "transmission_color": [0.123, 0.2985, 0.1246], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "green", "tinted", "jewellery"], + "source": { + "kind": "published", + "reference": "GIA Gem Encyclopedia, Emerald: refractive index 1.577 to 1.583; LibreTexts Geosciences, Gemology, Emerald: dispersion 0.014", + "urls": ["https://www.gia.edu/emerald/gem-overview", "https://geo.libretexts.org/Bookshelves/Geology/Gemology/16%3A_Gemstones/16.04%3A_Beryl/16.4.03%3A_Emerald"], + "notes": "Faceted stone, dispersion on. specular_ior 1.58: the mid value of 1.577 to 1.583 (GIA); dispersion 0.014 from LibreTexts Gemology. The Abbe number 70.9 is converted from the published B-G dispersion 0.014 (nG - nB) with nF - nC = 0.5845 (nG - nB), Cauchy's two-term relation. transmission_color authored as sRGB #1f9a5a, the green of chromium and vanadium in beryl, through 0.005 m.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/fluorite-purple.json b/assets/library/materials/gem/fluorite-purple.json new file mode 100644 index 00000000..3eb43ab8 --- /dev/null +++ b/assets/library/materials/gem/fluorite-purple.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/fluorite-purple", + "name": "Fluorite, purple", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.4338, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 95.0, + "transmission_color": [0.2893, 0.2026, 0.5296], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "purple", "tinted", "mineral"], + "source": { + "kind": "measured", + "reference": "I. H. Malitson. A redetermination of some optical properties of calcium fluoride. Appl. Opt. 2, 1103-1107 (1963); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/CaF2/nk/Malitson.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.4338 is the measured n at 587.6 nm and the Abbe number 95.0 is (nd - 1)/(nF - nC) from the same data. transmission_color authored as sRGB #9a78c8, the lavender of colour centres in fluorite, reached through 0.005 m, a typical stone's depth.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/garnet-almandine.json b/assets/library/materials/gem/garnet-almandine.json new file mode 100644 index 00000000..71f35ded --- /dev/null +++ b/assets/library/materials/gem/garnet-almandine.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/garnet-almandine", + "name": "Garnet, almandine", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.81, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 57.7, + "transmission_color": [0.1225, 0.0203, 0.0201], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "red", "tinted", "jewellery"], + "source": { + "kind": "published", + "reference": "Museum of Fine Arts Boston, CAMEO: Conservation and Art Materials Encyclopedia Online, Properties of Gemstones table", + "urls": ["https://cameo.mfa.org/wiki/Gemstone"], + "notes": "Faceted stone, dispersion on. specular_ior 1.81: the mid value of 1.79 to 1.83 (CAMEO). The Abbe number 57.7 is converted from the published B-G dispersion 0.024 (nG - nB) with nF - nC = 0.5845 (nG - nB), Cauchy's two-term relation. transmission_color authored as sRGB #7a1424, deep purplish red almandine, through 0.005 m.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/moissanite.json b/assets/library/materials/gem/moissanite.json new file mode 100644 index 00000000..3b867497 --- /dev/null +++ b/assets/library/materials/gem/moissanite.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/moissanite", + "name": "Moissanite", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 2.648, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 26.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery", "synthetic"], + "source": { + "kind": "measured", + "reference": "S. Wang, M. Zhan, G. Wang, H. Xuan, W. Zhang, C. Liu, C. Xu, Y. Liu, Z. Wei, X. Chen. 4H-SiC: A new nonlinear material for midinfrared lasers. Laser Photonics Rev. 7, 831-838 (2013); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiC/nk/Wang-6H-o.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 2.648 is the measured n at 587.6 nm and the Abbe number 26.0 is (nd - 1)/(nF - nC) from the same data (ordinary ray; the small birefringence is not modelled).", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/peridot.json b/assets/library/materials/gem/peridot.json new file mode 100644 index 00000000..f9e894e2 --- /dev/null +++ b/assets/library/materials/gem/peridot.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/peridot", + "name": "Peridot", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.67, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 57.3, + "transmission_color": [0.3782, 0.506, 0.0846], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "green", "tinted", "jewellery"], + "source": { + "kind": "published", + "reference": "Museum of Fine Arts Boston, CAMEO: Conservation and Art Materials Encyclopedia Online, Properties of Gemstones table", + "urls": ["https://cameo.mfa.org/wiki/Gemstone"], + "notes": "Faceted stone, dispersion on. specular_ior 1.67: the mid value of the beta index 1.652 to 1.698 (CAMEO). The Abbe number 57.3 is converted from the published B-G dispersion 0.02 (nG - nB) with nF - nC = 0.5845 (nG - nB), Cauchy's two-term relation. transmission_color authored as sRGB #9ac02a, olive green of iron in olivine, through 0.005 m.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/rock-crystal.json b/assets/library/materials/gem/rock-crystal.json new file mode 100644 index 00000000..bdea1b04 --- /dev/null +++ b/assets/library/materials/gem/rock-crystal.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/rock-crystal", + "name": "Quartz, rock crystal", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5443, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 69.7, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["crystal", "transparent", "dispersion", "clear", "mineral"], + "source": { + "kind": "measured", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.5443 is the measured n at 587.6 nm and the Abbe number 69.7 is (nd - 1)/(nF - nC) from the same data (ordinary ray; the small birefringence is not modelled).", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/ruby.json b/assets/library/materials/gem/ruby.json new file mode 100644 index 00000000..4f7a4ac4 --- /dev/null +++ b/assets/library/materials/gem/ruby.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/ruby", + "name": "Ruby", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.7682, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 72.3, + "transmission_color": [0.3261, 0.0421, 0.0333], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "red", "tinted", "jewellery"], + "source": { + "kind": "measured", + "reference": "I. H. Malitson and M. J. Dodge. Refractive index and birefringence of synthetic sapphire. J. Opt. Soc. Am. 62, 1405 (1972); M. J. Dodge. \"Refractive index\" in Handbook of Laser Science and Technology, Volume IV, Optical Materials: Part 2, CRC Press, Boca Raton, 1986, p. 30 * Ref. 1 is a talk abstract in a conference program; Ref. 2 provides a dispersion formula; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al2O3/nk/Malitson-o.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.7682 is the measured n at 587.6 nm and the Abbe number 72.3 is (nd - 1)/(nF - nC) from the same data (ordinary ray; the small birefringence is not modelled). transmission_color authored as sRGB #c0102c, the red of chromium in corundum, reached through 0.005 m, a typical stone's depth.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/sapphire-blue.json b/assets/library/materials/gem/sapphire-blue.json new file mode 100644 index 00000000..8d2841d0 --- /dev/null +++ b/assets/library/materials/gem/sapphire-blue.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/sapphire-blue", + "name": "Sapphire, blue", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.7682, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 72.3, + "transmission_color": [0.0425, 0.0516, 0.3463], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "blue", "tinted", "jewellery"], + "source": { + "kind": "measured", + "reference": "I. H. Malitson and M. J. Dodge. Refractive index and birefringence of synthetic sapphire. J. Opt. Soc. Am. 62, 1405 (1972); M. J. Dodge. \"Refractive index\" in Handbook of Laser Science and Technology, Volume IV, Optical Materials: Part 2, CRC Press, Boca Raton, 1986, p. 30 * Ref. 1 is a talk abstract in a conference program; Ref. 2 provides a dispersion formula; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al2O3/nk/Malitson-o.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.7682 is the measured n at 587.6 nm and the Abbe number 72.3 is (nd - 1)/(nF - nC) from the same data (ordinary ray; the small birefringence is not modelled). transmission_color authored as sRGB #1c3fa8, the cornflower blue of iron and titanium in corundum, reached through 0.005 m, a typical stone's depth.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/smoky-quartz.json b/assets/library/materials/gem/smoky-quartz.json new file mode 100644 index 00000000..afa4d3da --- /dev/null +++ b/assets/library/materials/gem/smoky-quartz.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/smoky-quartz", + "name": "Quartz, smoky", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5443, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 69.7, + "transmission_color": [0.1664, 0.1315, 0.0878], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "brown", "tinted", "mineral"], + "source": { + "kind": "measured", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.5443 is the measured n at 587.6 nm and the Abbe number 69.7 is (nd - 1)/(nF - nC) from the same data (ordinary ray; the small birefringence is not modelled). transmission_color authored as sRGB #7a6450, the grey-brown of irradiated aluminium centres in quartz, reached through 0.005 m, a typical stone's depth.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/spinel-red.json b/assets/library/materials/gem/spinel-red.json new file mode 100644 index 00000000..88822915 --- /dev/null +++ b/assets/library/materials/gem/spinel-red.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/spinel-red", + "name": "Spinel, red", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.7162, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 60.7, + "transmission_color": [0.3305, 0.0509, 0.057], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "red", "tinted", "jewellery"], + "source": { + "kind": "measured", + "reference": "W. J. Tropf and M. E. Thomas, Magnesium aluminum spinel (MgAlO4), in E. D. Palik (ed.), Handbook of Optical Constants of Solids II, Academic Press, Orlando, 1991, pp. 881-8952) Handbook of Optics, 3rd edition, Vol. 4. McGraw-Hill 2009* Ref. 2 provides improved Sellmeier equation based on data from Ref. 1; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/MgAl2O4/nk/Tropf.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.7162 is the measured n at 587.6 nm and the Abbe number 60.7 is (nd - 1)/(nF - nC) from the same data. transmission_color authored as sRGB #c02040, chromium red spinel, reached through 0.005 m, a typical stone's depth.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/topaz-blue.json b/assets/library/materials/gem/topaz-blue.json new file mode 100644 index 00000000..fbbbfcf0 --- /dev/null +++ b/assets/library/materials/gem/topaz-blue.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/topaz-blue", + "name": "Topaz, blue", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.62, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 75.8, + "transmission_color": [0.2282, 0.3752, 0.6423], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "blue", "tinted", "jewellery"], + "source": { + "kind": "published", + "reference": "Museum of Fine Arts Boston, CAMEO: Conservation and Art Materials Encyclopedia Online, Properties of Gemstones table", + "urls": ["https://cameo.mfa.org/wiki/Gemstone"], + "notes": "Faceted stone, dispersion on. specular_ior 1.62: the beta index of 1.609 to 1.631 (CAMEO), mid value. The Abbe number 75.8 is converted from the published B-G dispersion 0.014 (nG - nB) with nF - nC = 0.5845 (nG - nB), Cauchy's two-term relation. transmission_color authored as sRGB #5aa8d8, the sky blue of treated topaz, through 0.005 m.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/tourmaline-green.json b/assets/library/materials/gem/tourmaline-green.json new file mode 100644 index 00000000..50e5db0d --- /dev/null +++ b/assets/library/materials/gem/tourmaline-green.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/tourmaline-green", + "name": "Tourmaline, green", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.645, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 69.0, + "transmission_color": [0.1155, 0.2368, 0.0883], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "green", "tinted", "jewellery"], + "source": { + "kind": "published", + "reference": "Museum of Fine Arts Boston, CAMEO: Conservation and Art Materials Encyclopedia Online, Properties of Gemstones table", + "urls": ["https://cameo.mfa.org/wiki/Gemstone"], + "notes": "Faceted stone, dispersion on. specular_ior 1.645: between the extraordinary 1.610 to 1.650 and ordinary 1.635 to 1.675 indices (CAMEO). The Abbe number 69.0 is converted from the published B-G dispersion 0.016 (nG - nB) with nF - nC = 0.5845 (nG - nB), Cauchy's two-term relation. transmission_color authored as sRGB #3a8a4a, the green of iron in verdelite, through 0.005 m.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/tourmaline-pink.json b/assets/library/materials/gem/tourmaline-pink.json new file mode 100644 index 00000000..52168d61 --- /dev/null +++ b/assets/library/materials/gem/tourmaline-pink.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/tourmaline-pink", + "name": "Tourmaline, pink", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.645, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 69.0, + "transmission_color": [0.5213, 0.1887, 0.3122], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "pink", "tinted", "jewellery"], + "source": { + "kind": "published", + "reference": "Museum of Fine Arts Boston, CAMEO: Conservation and Art Materials Encyclopedia Online, Properties of Gemstones table", + "urls": ["https://cameo.mfa.org/wiki/Gemstone"], + "notes": "Faceted stone, dispersion on. specular_ior 1.645: between the extraordinary 1.610 to 1.650 and ordinary 1.635 to 1.675 indices (CAMEO). The Abbe number 69.0 is converted from the published B-G dispersion 0.016 (nG - nB) with nF - nC = 0.5845 (nG - nB), Cauchy's two-term relation. transmission_color authored as sRGB #e06a9a, the pink of manganese in rubellite, through 0.005 m.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/white-sapphire.json b/assets/library/materials/gem/white-sapphire.json new file mode 100644 index 00000000..35955ff0 --- /dev/null +++ b/assets/library/materials/gem/white-sapphire.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/white-sapphire", + "name": "Sapphire, colourless", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.7682, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 72.3, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery"], + "source": { + "kind": "measured", + "reference": "I. H. Malitson and M. J. Dodge. Refractive index and birefringence of synthetic sapphire. J. Opt. Soc. Am. 62, 1405 (1972); M. J. Dodge. \"Refractive index\" in Handbook of Laser Science and Technology, Volume IV, Optical Materials: Part 2, CRC Press, Boca Raton, 1986, p. 30 * Ref. 1 is a talk abstract in a conference program; Ref. 2 provides a dispersion formula; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al2O3/nk/Malitson-o.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.7682 is the measured n at 587.6 nm and the Abbe number 72.3 is (nd - 1)/(nF - nC) from the same data (ordinary ray; the small birefringence is not modelled).", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/yag.json b/assets/library/materials/gem/yag.json new file mode 100644 index 00000000..d8c9a254 --- /dev/null +++ b/assets/library/materials/gem/yag.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/yag", + "name": "YAG, colourless", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.8328, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 52.6, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["crystal", "transparent", "dispersion", "clear", "optics", "synthetic"], + "source": { + "kind": "measured", + "reference": "D. E. Zelmon, D. L. Small and R. Page. Refractive-index measurements of undoped yttrium aluminum garnet from 0.4 to 5.0 μm. Appl. Opt. 37, 4933-4935 (1998); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Y3Al5O12/nk/Zelmon.yml"], + "notes": "Faceted stone, dispersion on. specular_ior 1.8328 is the measured n at 587.6 nm and the Abbe number 52.6 is (nd - 1)/(nF - nC) from the same data.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/gem/zircon.json b/assets/library/materials/gem/zircon.json new file mode 100644 index 00000000..598f4787 --- /dev/null +++ b/assets/library/materials/gem/zircon.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "gem/zircon", + "name": "Zircon, colourless", + "category": "Gem", + "type": "gem", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.94, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 33.5, + "transmission_color": [0.9597, 0.9561, 0.9262], + "transmission_depth": 0.005 + }, + "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery"], + "source": { + "kind": "published", + "reference": "Museum of Fine Arts Boston, CAMEO: Conservation and Art Materials Encyclopedia Online, Properties of Gemstones table", + "urls": ["https://cameo.mfa.org/wiki/Gemstone"], + "notes": "Faceted stone, dispersion on. specular_ior 1.94: the mid value of the ordinary 1.923 to 1.960 (CAMEO). The Abbe number 33.5 is converted from the published B-G dispersion 0.048 (nG - nB) with nF - nC = 0.5845 (nG - nB), Cauchy's two-term relation. transmission_color authored as sRGB #fbfaf6, near colourless, through 0.005 m.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/bottle-glass-amber.json b/assets/library/materials/glass/bottle-glass-amber.json new file mode 100644 index 00000000..202d0558 --- /dev/null +++ b/assets/library/materials/glass/bottle-glass-amber.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/bottle-glass-amber", + "name": "Bottle glass, amber", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.2734, 0.117, 0.0229], + "transmission_depth": 0.003, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "brown", "tinted", "packaging"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire. transmission_color authored as sRGB #a8580f, the amber of iron-sulphur coloured container glass through a 3 mm wall; the measured clear soda-lime index is kept.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/bottle-glass-green.json b/assets/library/materials/glass/bottle-glass-green.json new file mode 100644 index 00000000..f4f989b8 --- /dev/null +++ b/assets/library/materials/glass/bottle-glass-green.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/bottle-glass-green", + "name": "Bottle glass, green", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.1599, 0.3022, 0.0789], + "transmission_depth": 0.003, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "green", "tinted", "packaging"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire. transmission_color authored as sRGB #4f9a3e, the green of iron and chromium coloured container glass seen through a 3 mm wall; the measured clear soda-lime index is kept.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/cobalt-blue-glass.json b/assets/library/materials/glass/cobalt-blue-glass.json new file mode 100644 index 00000000..b81ff58f --- /dev/null +++ b/assets/library/materials/glass/cobalt-blue-glass.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/cobalt-blue-glass", + "name": "Cobalt blue glass", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.0453, 0.0522, 0.3739], + "transmission_depth": 0.003, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "blue", "tinted", "tableware"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire. transmission_color authored as sRGB #1f3fae, the deep blue of cobalt oxide glass through a 3 mm wall; the measured clear soda-lime index is kept.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/dense-flint-n-sf11.json b/assets/library/materials/glass/dense-flint-n-sf11.json new file mode 100644 index 00000000..b4d6b4ed --- /dev/null +++ b/assets/library/materials/glass/dense-flint-n-sf11.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/dense-flint-n-sf11", + "name": "Dense flint glass (N-SF11)", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.7847, + "transmission_weight": 1.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 25.7 + }, + "tags": ["glass", "transparent", "clear", "optics", "dispersion"], + "source": { + "kind": "published", + "reference": "SCHOTT Zemax catalog 2017-01-20b (obtained from http://www.schott.com)See also SCHOTT glass data sheets; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/specs/schott/optical/N-SF11.yml"], + "notes": "specular_ior 1.7847 is the measured n at 587.6 nm and Abbe number 25.7 is (nd - 1)/(nF - nC) from the same data. Dispersion on (scale 1): visible fire is part of this glass's look.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/fused-silica.json b/assets/library/materials/glass/fused-silica.json new file mode 100644 index 00000000..20507223 --- /dev/null +++ b/assets/library/materials/glass/fused-silica.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/fused-silica", + "name": "Fused silica", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.4585, + "transmission_weight": 1.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 67.8 + }, + "tags": ["glass", "transparent", "clear", "optics"], + "source": { + "kind": "published", + "reference": "I. H. Malitson. Interspecimen comparison of the refractive index of fused silica. J. Opt. Soc. Am. 55, 1205-1208 (1965); C. Z. Tan. Determination of refractive index of silica glass for infrared wavelengths by IR spectroscopy. J. Non-Cryst. Solids 223, 158-163 (1998) * Sellmeier formula is reported in Ref. 1 for the 0.21-3.71 μm wavelength range. Ref. 2 verifies the validity of the formula up to 6.7 μm.; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Malitson.yml"], + "notes": "specular_ior 1.4585 is the measured n at 587.6 nm and Abbe number 67.8 is (nd - 1)/(nF - nC) from the same data. Dispersion on (scale 1): visible fire is part of this glass's look.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/opal-glass.json b/assets/library/materials/glass/opal-glass.json new file mode 100644 index 00000000..6fccd000 --- /dev/null +++ b/assets/library/materials/glass/opal-glass.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/opal-glass", + "name": "Opal glass", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [0.8864, 0.8875, 0.8593], + "base_metalness": 0.0, + "specular_roughness": 0.05, + "specular_ior": 1.5234, + "transmission_weight": 0.0, + "subsurface_weight": 1.0, + "subsurface_color": [0.8864, 0.8875, 0.8593], + "subsurface_radius": 0.002, + "subsurface_radius_scale": [1.0, 0.9, 0.8] + }, + "tags": ["glass", "translucent", "subsurface", "white", "lighting"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "Opal (milk) glass: a clear soda-lime base (measured n 1.5234) with light-scattering inclusions, modelled as subsurface with transmission off. Colour sRGB #f2f2ee, mean free path 2 mm and the warm radius scale are authored so a 3 mm lamp shade diffuses fully.", + "authored": ["base_color", "specular_roughness", "subsurface_color", "subsurface_radius", "subsurface_radius_scale"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/optical-crown-n-bk7.json b/assets/library/materials/glass/optical-crown-n-bk7.json new file mode 100644 index 00000000..5de0f3bb --- /dev/null +++ b/assets/library/materials/glass/optical-crown-n-bk7.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/optical-crown-n-bk7", + "name": "Optical crown glass (N-BK7)", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5168, + "transmission_weight": 1.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 64.2 + }, + "tags": ["glass", "transparent", "clear", "optics"], + "source": { + "kind": "published", + "reference": "SCHOTT Zemax catalog 2017-01-20b (obtained from http://www.schott.com) See also SCHOTT glass data sheets; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/specs/schott/optical/N-BK7.yml"], + "notes": "specular_ior 1.5168 is the measured n at 587.6 nm and Abbe number 64.2 is (nd - 1)/(nF - nC) from the same data. Dispersion on (scale 1): visible fire is part of this glass's look.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/optical-flint-n-f2.json b/assets/library/materials/glass/optical-flint-n-f2.json new file mode 100644 index 00000000..80f7e278 --- /dev/null +++ b/assets/library/materials/glass/optical-flint-n-f2.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/optical-flint-n-f2", + "name": "Optical flint glass (N-F2)", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.6201, + "transmission_weight": 1.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 1.0, + "transmission_dispersion_abbe_number": 36.4 + }, + "tags": ["glass", "transparent", "clear", "optics", "dispersion"], + "source": { + "kind": "published", + "reference": "SCHOTT Zemax catalog 2017-01-20b (obtained from http://www.schott.com)See also SCHOTT glass data sheets; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/specs/schott/optical/N-F2.yml"], + "notes": "specular_ior 1.6201 is the measured n at 587.6 nm and Abbe number 36.4 is (nd - 1)/(nF - nC) from the same data. Dispersion on (scale 1): visible fire is part of this glass's look.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-glass-bronze.json b/assets/library/materials/glass/window-glass-bronze.json new file mode 100644 index 00000000..ac7cf925 --- /dev/null +++ b/assets/library/materials/glass/window-glass-bronze.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-glass-bronze", + "name": "Window glass, bronze tint", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.6105, 0.5673, 0.4963], + "transmission_depth": 0.006, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "brown", "tinted", "architectural"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-bronze.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through transmission_depth 0.006 m; the depth was chosen so the colour is strong enough to keep its hue in RGB. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire.", + "authored": ["transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-glass-clear.json b/assets/library/materials/glass/window-glass-clear.json new file mode 100644 index 00000000..52dd73cc --- /dev/null +++ b/assets/library/materials/glass/window-glass-clear.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-glass-clear", + "name": "Window glass, clear", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.6033, 0.773, 0.7639], + "transmission_depth": 0.05, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "clear", "architectural"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through transmission_depth 0.05 m; the depth was chosen so the colour is strong enough to keep its hue in RGB. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire.", + "authored": ["transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-glass-frosted.json b/assets/library/materials/glass/window-glass-frosted.json new file mode 100644 index 00000000..8d2aaa02 --- /dev/null +++ b/assets/library/materials/glass/window-glass-frosted.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-glass-frosted", + "name": "Window glass, frosted", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.35, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.6033, 0.773, 0.7639], + "transmission_depth": 0.05, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "clear", "frosted", "translucent", "architectural"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through transmission_depth 0.05 m; the depth was chosen so the colour is strong enough to keep its hue in RGB. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire. Roughness 0.35 authored for an acid-etched surface.", + "authored": ["specular_roughness", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-glass-green.json b/assets/library/materials/glass/window-glass-green.json new file mode 100644 index 00000000..7b104e6c --- /dev/null +++ b/assets/library/materials/glass/window-glass-green.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-glass-green", + "name": "Window glass, green tint", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.3827, 0.573, 0.5777], + "transmission_depth": 0.02, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "green", "tinted", "architectural"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-green.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through transmission_depth 0.02 m; the depth was chosen so the colour is strong enough to keep its hue in RGB. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire.", + "authored": ["transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-glass-grey.json b/assets/library/materials/glass/window-glass-grey.json new file mode 100644 index 00000000..6928130e --- /dev/null +++ b/assets/library/materials/glass/window-glass-grey.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-glass-grey", + "name": "Window glass, grey tint", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.4563, 0.4663, 0.4886], + "transmission_depth": 0.006, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "grey", "tinted", "architectural"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-grey.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through transmission_depth 0.006 m; the depth was chosen so the colour is strong enough to keep its hue in RGB. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire.", + "authored": ["transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-glass-low-iron.json b/assets/library/materials/glass/window-glass-low-iron.json new file mode 100644 index 00000000..d2b870b7 --- /dev/null +++ b/assets/library/materials/glass/window-glass-low-iron.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-glass-low-iron", + "name": "Window glass, low iron", + "category": "Glass", + "type": "glass", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.6326, 0.7898, 0.7875], + "transmission_depth": 0.2, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0 + }, + "tags": ["glass", "transparent", "clear", "architectural"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-lowiron.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through transmission_depth 0.2 m; the depth was chosen so the colour is strong enough to keep its hue in RGB. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire.", + "authored": ["transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-pane-thin-bronze.json b/assets/library/materials/glass/window-pane-thin-bronze.json new file mode 100644 index 00000000..2e4df5c3 --- /dev/null +++ b/assets/library/materials/glass/window-pane-thin-bronze.json @@ -0,0 +1,29 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-pane-thin-bronze", + "name": "Window pane, thin bronze", + "category": "Glass", + "type": "glass_thin", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.6105, 0.5673, 0.4963], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0, + "geometry_thin_walled": true + }, + "tags": ["glass", "transparent", "brown", "tinted", "architectural", "thin-walled"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-bronze.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through one 6 mm pane, applied at the surface of the thin shell. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-pane-thin-frosted.json b/assets/library/materials/glass/window-pane-thin-frosted.json new file mode 100644 index 00000000..4f0d3f34 --- /dev/null +++ b/assets/library/materials/glass/window-pane-thin-frosted.json @@ -0,0 +1,29 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-pane-thin-frosted", + "name": "Window pane, thin frosted", + "category": "Glass", + "type": "glass_thin", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.35, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.94, 0.9693, 0.968], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0, + "geometry_thin_walled": true + }, + "tags": ["glass", "transparent", "clear", "frosted", "architectural", "thin-walled"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through one 6 mm pane, applied at the surface of the thin shell. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire. Roughness 0.35 authored for an acid-etched pane.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/glass/window-pane-thin.json b/assets/library/materials/glass/window-pane-thin.json new file mode 100644 index 00000000..ffc4f283 --- /dev/null +++ b/assets/library/materials/glass/window-pane-thin.json @@ -0,0 +1,29 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "glass/window-pane-thin", + "name": "Window pane, thin shell", + "category": "Glass", + "type": "glass_thin", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.5234, + "transmission_weight": 1.0, + "transmission_color": [0.94, 0.9693, 0.968], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.0, + "geometry_thin_walled": true + }, + "tags": ["glass", "transparent", "clear", "architectural", "thin-walled"], + "source": { + "kind": "published", + "reference": "M. Rubin. Optical properties of soda lime silica glasses. Sol. Energy Mater. 12, 275-288 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/glass/misc/soda-lime/nk/Rubin-clear.yml"], + "notes": "specular_ior 1.5234 is the measured n at 587.6 nm and Abbe number 64.0 is (nd - 1)/(nF - nC) from the same data. transmission_color is the measured absorption (Beer-Lambert from k, CIE 1931 under D65) through one 6 mm pane, applied at the surface of the thin shell. Dispersion stored but off (scale 0); set the scale to 1 for spectral fire.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/index.json b/assets/library/materials/index.json new file mode 100644 index 00000000..bac20f87 --- /dev/null +++ b/assets/library/materials/index.json @@ -0,0 +1,270 @@ +{ + "format": "formshot-material-index", + "version": 1, + "count": 249, + "categories": [ + {"name": "Metal", "folder": "metal", "count": 73}, + {"name": "Plastic", "folder": "plastic", "count": 37}, + {"name": "Glass", "folder": "glass", "count": 17}, + {"name": "Paint", "folder": "paint", "count": 22}, + {"name": "Rubber", "folder": "rubber", "count": 9}, + {"name": "Fabric", "folder": "fabric", "count": 13}, + {"name": "Wood", "folder": "wood", "count": 10}, + {"name": "Stone", "folder": "stone", "count": 10}, + {"name": "Ceramic", "folder": "ceramic", "count": 10}, + {"name": "Liquid", "folder": "liquid", "count": 17}, + {"name": "Gem", "folder": "gem", "count": 22}, + {"name": "Emissive", "folder": "emissive", "count": 9} + ], + "presets": [ + {"id": "metal/aluminium-anodised-black", "name": "Aluminium, anodised black", "category": "Metal", "type": "metal", "tags": ["anodised", "black", "satin", "coat", "electronics"], "file": "metal/aluminium-anodised-black.json", "sha256": "e3319368e21485873c0a3b5584fef499c8e822086a025bb5d5d15f4b49707e26"}, + {"id": "metal/aluminium-anodised-blue", "name": "Aluminium, anodised blue", "category": "Metal", "type": "metal", "tags": ["anodised", "blue", "satin", "coat", "electronics"], "file": "metal/aluminium-anodised-blue.json", "sha256": "dbb15e75bf823ae3f3dfa4b222d9e9971393ae76f1ff4341b4dd3385667bccd6"}, + {"id": "metal/aluminium-anodised-bronze", "name": "Aluminium, anodised bronze", "category": "Metal", "type": "metal", "tags": ["anodised", "brown", "satin", "coat", "electronics"], "file": "metal/aluminium-anodised-bronze.json", "sha256": "ce2b034542fd9f9726878f5f26222fae9d72c4f2e032ee78000ed02be78e4672"}, + {"id": "metal/aluminium-anodised-gold", "name": "Aluminium, anodised gold", "category": "Metal", "type": "metal", "tags": ["anodised", "gold", "satin", "coat", "electronics"], "file": "metal/aluminium-anodised-gold.json", "sha256": "dfd778541d7bd49fbd4dc6998a402cff4a6134de3e7980c645d853908b557800"}, + {"id": "metal/aluminium-anodised-green", "name": "Aluminium, anodised green", "category": "Metal", "type": "metal", "tags": ["anodised", "green", "satin", "coat", "electronics"], "file": "metal/aluminium-anodised-green.json", "sha256": "76a5ea0d49c602c4116bdf38527cb73cc700acf657c0f22ff15687bf1d4a7532"}, + {"id": "metal/aluminium-anodised-purple", "name": "Aluminium, anodised purple", "category": "Metal", "type": "metal", "tags": ["anodised", "purple", "satin", "coat", "electronics"], "file": "metal/aluminium-anodised-purple.json", "sha256": "3c5d57e19fd2e50230f323656b691b98ea73f63efb05c32ccbc3af4a7347d9aa"}, + {"id": "metal/aluminium-anodised-red", "name": "Aluminium, anodised red", "category": "Metal", "type": "metal", "tags": ["anodised", "red", "satin", "coat", "electronics"], "file": "metal/aluminium-anodised-red.json", "sha256": "e47a965ff2a6700c901661c475d369665dc3bd1ac19731d49d2f53f5a38139c9"}, + {"id": "metal/aluminium-anodised-rose", "name": "Aluminium, anodised rose", "category": "Metal", "type": "metal", "tags": ["anodised", "pink", "satin", "coat", "electronics"], "file": "metal/aluminium-anodised-rose.json", "sha256": "79009dc5590e467a4dc0c117c477664d4856ac66f39257e8b70714849abe5112"}, + {"id": "metal/aluminium-as-cast", "name": "Aluminium, as cast", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "electronics", "rough", "opaque"], "file": "metal/aluminium-as-cast.json", "sha256": "2625f0c3f013c75b0f20fb5db358dccbf5e5050724aa2b0893d95e1abeced0c7"}, + {"id": "metal/aluminium-bead-blasted", "name": "Aluminium, bead blasted", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "electronics", "rough", "opaque"], "file": "metal/aluminium-bead-blasted.json", "sha256": "5efa38a7b957f4490c38a0babaa680a276cde3e0d110111df8a35ee7bed3b5c3"}, + {"id": "metal/aluminium-brushed", "name": "Aluminium, brushed", "category": "Metal", "type": "metal_brushed", "tags": ["pure-metal", "silver", "electronics", "brushed", "opaque", "anisotropic"], "file": "metal/aluminium-brushed.json", "sha256": "1b5804d9ab98f1289b91bc65ec50928a5767bf84726e68d402293fed4993bf82"}, + {"id": "metal/aluminium-polished", "name": "Aluminium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "industrial", "polished", "opaque"], "file": "metal/aluminium-polished.json", "sha256": "d28b1b611eb8f56181f542816289c9f08835e00bd55bbd34d1da2d5cd4b77d9a"}, + {"id": "metal/aluminium-satin", "name": "Aluminium, satin", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "electronics", "satin", "opaque"], "file": "metal/aluminium-satin.json", "sha256": "55e62f68e122063083f0229840a341b6ca0cebda706cc0fcf1b7def4cdc3b1a2"}, + {"id": "metal/beryllium-polished", "name": "Beryllium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], "file": "metal/beryllium-polished.json", "sha256": "1aa06f880b5e6bded0fe4d962a4ec6fc10da8ad2d7fee193ffac65921f8a72b5"}, + {"id": "metal/bismuth-polished", "name": "Bismuth, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "polished", "opaque"], "file": "metal/bismuth-polished.json", "sha256": "5f674958eb28cf639362128eca9d2b17a2465b9d31e089e9ef10bdfe392d6ce7"}, + {"id": "metal/brass-polished", "name": "Brass (Cu70 Zn30), polished", "category": "Metal", "type": "metal", "tags": ["alloy", "gold", "architectural", "polished", "opaque"], "file": "metal/brass-polished.json", "sha256": "a47d30ea57e458d5610bcd7f65fa1e749480f0e954726078c866ddc1d6b38c0c"}, + {"id": "metal/brass-brushed", "name": "Brass, brushed", "category": "Metal", "type": "metal_brushed", "tags": ["alloy", "gold", "architectural", "brushed", "opaque", "anisotropic"], "file": "metal/brass-brushed.json", "sha256": "3be116c60408e12b486b50177ebb744e69868f9267b46065934a20dc3f586a9f"}, + {"id": "metal/brass-satin", "name": "Brass, satin", "category": "Metal", "type": "metal", "tags": ["alloy", "gold", "architectural", "satin", "opaque"], "file": "metal/brass-satin.json", "sha256": "960a9c4d858584965ecebb2aa69899b55a85dd68b887b3285d260ca9a3a469b5"}, + {"id": "metal/chromium-polished", "name": "Chromium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "automotive", "polished", "opaque"], "file": "metal/chromium-polished.json", "sha256": "3829789728a79166c9c2a54695aca55ce5ede8f24a3b79121c448c7973d8ee0f"}, + {"id": "metal/chromium-satin", "name": "Chromium, satin", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "automotive", "satin", "opaque"], "file": "metal/chromium-satin.json", "sha256": "50299c5d3b85ef58b5a0395392946f4d0cbba6a45859c413e7ef5e7bff87cb98"}, + {"id": "metal/cobalt-polished", "name": "Cobalt, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "industrial", "polished", "opaque"], "file": "metal/cobalt-polished.json", "sha256": "6409c98616a099464513afaf825cbe09813c60de510471542db3c2e7c4db4c86"}, + {"id": "metal/copper-bead-blasted", "name": "Copper, bead blasted", "category": "Metal", "type": "metal", "tags": ["pure-metal", "orange", "kitchen", "rough", "opaque"], "file": "metal/copper-bead-blasted.json", "sha256": "59d1bb03f8c92676601b2ce4a3e652df7fb750f5e6c6f74e296640d02e0da1e7"}, + {"id": "metal/copper-brushed", "name": "Copper, brushed", "category": "Metal", "type": "metal_brushed", "tags": ["pure-metal", "orange", "kitchen", "brushed", "opaque", "anisotropic"], "file": "metal/copper-brushed.json", "sha256": "fdddce96524ccd25067abe8bc005cbe82dada9937803266b93affc185e3b292f"}, + {"id": "metal/copper-polished", "name": "Copper, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "orange", "kitchen", "polished", "opaque"], "file": "metal/copper-polished.json", "sha256": "60199167394ccb582bf2fdd6ba246bff6584a2449744b979ca7fc3f38f0d6d31"}, + {"id": "metal/copper-satin", "name": "Copper, satin", "category": "Metal", "type": "metal", "tags": ["pure-metal", "orange", "kitchen", "satin", "opaque"], "file": "metal/copper-satin.json", "sha256": "bef260eecbd70c0d7fdbbeeb3edeaaf7a479927cd6211879d7265c598a3de8df"}, + {"id": "metal/electrum-polished", "name": "Electrum (Au50 Ag50), polished", "category": "Metal", "type": "metal", "tags": ["alloy", "gold", "jewellery", "polished", "opaque"], "file": "metal/electrum-polished.json", "sha256": "48add1c8c0e2b1454e6542ad644b5e99285f839ce8f2f1ec0f6f37d487f3c543"}, + {"id": "metal/gilding-metal-polished", "name": "Gilding metal (Cu90 Zn10), polished", "category": "Metal", "type": "metal", "tags": ["alloy", "orange", "polished", "opaque"], "file": "metal/gilding-metal-polished.json", "sha256": "40fc1d0dd4da229d4ca27274c9a21da097d028c322d1dbc55313638a10edf6eb"}, + {"id": "metal/gold-brushed", "name": "Gold, brushed", "category": "Metal", "type": "metal_brushed", "tags": ["pure-metal", "gold", "jewellery", "brushed", "opaque", "anisotropic"], "file": "metal/gold-brushed.json", "sha256": "1d4b377df9f05fad198e151412d92e2066e975101d11ede5681e3edabb76b35a"}, + {"id": "metal/gold-polished", "name": "Gold, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "gold", "jewellery", "polished", "opaque"], "file": "metal/gold-polished.json", "sha256": "5ddd0a5c230892ad269d5f5778b85993bfa05c573bb93e40d56e76148a60014c"}, + {"id": "metal/gold-satin", "name": "Gold, satin", "category": "Metal", "type": "metal", "tags": ["pure-metal", "gold", "jewellery", "satin", "opaque"], "file": "metal/gold-satin.json", "sha256": "811a90b6b10977ec52aed29f3e7f5c1228e171585cff14dfc3359bc5d9a3d3ee"}, + {"id": "metal/gold-silver-au60-polished", "name": "Gold-silver alloy (Au60 Ag40), polished", "category": "Metal", "type": "metal", "tags": ["alloy", "gold", "jewellery", "polished", "opaque"], "file": "metal/gold-silver-au60-polished.json", "sha256": "9b89c9f515dc775d61480f562cfdb5731c417c606747233ebbfe5a346b237a70"}, + {"id": "metal/gold-silver-au80-polished", "name": "Gold-silver alloy (Au80 Ag20), polished", "category": "Metal", "type": "metal", "tags": ["alloy", "gold", "jewellery", "polished", "opaque"], "file": "metal/gold-silver-au80-polished.json", "sha256": "d2a52ac26f9fa234f3f9d11e33b28aedb412c2ee12338b3eb356988b487b9eb8"}, + {"id": "metal/iridium-polished", "name": "Iridium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "polished", "opaque"], "file": "metal/iridium-polished.json", "sha256": "69b5a06626ab69bdf481f09c57924abf9fc7ac57090df0ce285f287795f9c206"}, + {"id": "metal/iron-as-cast", "name": "Iron, as cast", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "rough", "opaque"], "file": "metal/iron-as-cast.json", "sha256": "1a68f3c9d428b0a1a0c18dc4d54d556420a10e936f523f1b14b60ee7938a5635"}, + {"id": "metal/iron-bead-blasted", "name": "Iron, bead blasted", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "rough", "opaque"], "file": "metal/iron-bead-blasted.json", "sha256": "55d69418aaddce0f35f03a1d36664a7041cb4bb08018df4a63f2d0a6506a9c40"}, + {"id": "metal/iron-polished", "name": "Iron, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], "file": "metal/iron-polished.json", "sha256": "d04cd74175cf597341a12f4641693656397425e0a6837436b9796d948746dfd6"}, + {"id": "metal/iron-satin", "name": "Iron, satin", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "satin", "opaque"], "file": "metal/iron-satin.json", "sha256": "0c429270766c95a3be8c83da5efe1bd3f48a89afa73a075c35b5254d69215c72"}, + {"id": "metal/lead-polished", "name": "Lead, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], "file": "metal/lead-polished.json", "sha256": "288a4862a79ea22f11c5584a1a68f2456311b19060246e4850f0ba8ad20a37a6"}, + {"id": "metal/magnesium-polished", "name": "Magnesium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "industrial", "polished", "opaque"], "file": "metal/magnesium-polished.json", "sha256": "45100b01131f6abf5188dda1452dc46721a21e69c478949df0b284864ece612a"}, + {"id": "metal/mercury-polished", "name": "Mercury (liquid), polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "polished", "opaque"], "file": "metal/mercury-polished.json", "sha256": "74d905938f30e63a4ac1a98f57facdaf7c1c8b64c50ac29d432fdefd04d21b57"}, + {"id": "metal/molybdenum-polished", "name": "Molybdenum, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], "file": "metal/molybdenum-polished.json", "sha256": "cd8912a20fc3e8cb7a62566758ea559466a62c70f86f12ae754dc5d85e7f7de8"}, + {"id": "metal/nickel-brushed", "name": "Nickel, brushed", "category": "Metal", "type": "metal_brushed", "tags": ["pure-metal", "silver", "industrial", "brushed", "opaque", "anisotropic"], "file": "metal/nickel-brushed.json", "sha256": "eec3c0e42779786e4edad7a2d6bd0c07588c85b00b78640bb3c242b758660642"}, + {"id": "metal/nickel-polished", "name": "Nickel, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "industrial", "polished", "opaque"], "file": "metal/nickel-polished.json", "sha256": "eda3d5f480c35c6e77077356dbaedeaf986f187b28e6d59881e7c1731cf0a11c"}, + {"id": "metal/nickel-satin", "name": "Nickel, satin", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "industrial", "satin", "opaque"], "file": "metal/nickel-satin.json", "sha256": "eb4c6c3a87ccb0820802294ed924a16b1c39f59f06388c722d1b0293f26909c7"}, + {"id": "metal/niobium-polished", "name": "Niobium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "jewellery", "polished", "opaque"], "file": "metal/niobium-polished.json", "sha256": "20cdba04836498e49ef1a91e841e46828b2df27bdf6940de4048166124bb4f12"}, + {"id": "metal/palladium-polished", "name": "Palladium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "jewellery", "polished", "opaque"], "file": "metal/palladium-polished.json", "sha256": "cfd6806e859e737effb1d5b45da7e83b82991759af7d78ecb019957c894d1b2b"}, + {"id": "metal/platinum-polished", "name": "Platinum, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "jewellery", "polished", "opaque"], "file": "metal/platinum-polished.json", "sha256": "fc7f698415f8da212439f7de3a6f9ff8824cc15f9a82ac13986f7dae8d098b72"}, + {"id": "metal/red-brass-polished", "name": "Red brass (Cu85 Zn15), polished", "category": "Metal", "type": "metal", "tags": ["alloy", "orange", "polished", "opaque"], "file": "metal/red-brass-polished.json", "sha256": "b2deca162ded2c8b846edc3a453a82b6c91e372607a99b30137b2de2af5455b6"}, + {"id": "metal/rhodium-polished", "name": "Rhodium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "jewellery", "polished", "opaque"], "file": "metal/rhodium-polished.json", "sha256": "6d0eac0b891e436582f2e91f76cc6ac9265dd6146f82fefc9ce7f4faa65e506e"}, + {"id": "metal/rose-gold-polished", "name": "Rose gold, polished", "category": "Metal", "type": "metal", "tags": ["alloy", "pink", "polished", "jewellery", "opaque"], "file": "metal/rose-gold-polished.json", "sha256": "4ab001ab291dfcf43a7081aaa8b4e63ba9268e8e35881a9c5c48167876567673"}, + {"id": "metal/silver-brushed", "name": "Silver, brushed", "category": "Metal", "type": "metal_brushed", "tags": ["pure-metal", "silver", "jewellery", "brushed", "opaque", "anisotropic"], "file": "metal/silver-brushed.json", "sha256": "bb85ffeba267af3781bff1db1b136679443522a7c421c116ef457dd81be4f41d"}, + {"id": "metal/silver-polished", "name": "Silver, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "jewellery", "polished", "opaque"], "file": "metal/silver-polished.json", "sha256": "b0cf03d436ce886ea7488499ef78ae32cfad0abffeb10c21704706b6fdcc7d49"}, + {"id": "metal/silver-satin", "name": "Silver, satin", "category": "Metal", "type": "metal", "tags": ["pure-metal", "silver", "jewellery", "satin", "opaque"], "file": "metal/silver-satin.json", "sha256": "0bf4f22f89efa922d5eb9a286a2a256c60aff57e6157cf24740a54e070f2c85e"}, + {"id": "metal/stainless-steel-austenitic-polished", "name": "Stainless steel, austenitic, polished", "category": "Metal", "type": "metal", "tags": ["alloy", "silver", "kitchen", "polished", "opaque"], "file": "metal/stainless-steel-austenitic-polished.json", "sha256": "bdc9b907ad3ed70a3a6117279593608d4c9742892490d89611845f1f4cd72e32"}, + {"id": "metal/stainless-steel-bead-blasted", "name": "Stainless steel, bead blasted", "category": "Metal", "type": "metal", "tags": ["alloy", "silver", "kitchen", "rough", "opaque"], "file": "metal/stainless-steel-bead-blasted.json", "sha256": "6e5714d71d366131f5d022085c4b8a1855d4ff9e2e63055e5d1ee1f2e0ae660c"}, + {"id": "metal/stainless-steel-brushed", "name": "Stainless steel, brushed", "category": "Metal", "type": "metal_brushed", "tags": ["alloy", "silver", "kitchen", "brushed", "opaque", "anisotropic"], "file": "metal/stainless-steel-brushed.json", "sha256": "a663ee78b9359d5b6f7b8695cc0c550d4ce7b1e40e6a2a2f129037edc50a5154"}, + {"id": "metal/stainless-steel-ferritic-polished", "name": "Stainless steel, ferritic, polished", "category": "Metal", "type": "metal", "tags": ["alloy", "silver", "kitchen", "polished", "opaque"], "file": "metal/stainless-steel-ferritic-polished.json", "sha256": "e0cd93d608204aaa8ff3654c9bd4ad18b40363a75e6bfadd4f2dcd86a3ef817e"}, + {"id": "metal/stainless-steel-mirror", "name": "Stainless steel, mirror", "category": "Metal", "type": "metal", "tags": ["alloy", "silver", "kitchen", "polished", "opaque"], "file": "metal/stainless-steel-mirror.json", "sha256": "fbf9ed4ed6c9ee4e446d443b82751f83d62baa597ba707d4ed3d8bc3526e5544"}, + {"id": "metal/stainless-steel-satin", "name": "Stainless steel, satin", "category": "Metal", "type": "metal", "tags": ["alloy", "silver", "kitchen", "satin", "opaque"], "file": "metal/stainless-steel-satin.json", "sha256": "0360e514e0d0c529fba6cebca8f5c0f8dd162d60ad0a8c2035eb1c6ccd74eb9f"}, + {"id": "metal/titanium-nitride-polished", "name": "Titanium nitride coating, polished", "category": "Metal", "type": "metal", "tags": ["coating", "gold", "industrial", "polished", "opaque"], "file": "metal/titanium-nitride-polished.json", "sha256": "3257456396bdfbc305cbc88230c5d889511b214f50740fa76ee5e0aca3f9d8c3"}, + {"id": "metal/titanium-anodised-blue", "name": "Titanium, anodised blue", "category": "Metal", "type": "metal", "tags": ["anodised", "blue", "thin-film", "polished", "jewellery"], "file": "metal/titanium-anodised-blue.json", "sha256": "c4920cbcb9a0f58fc994916da506d115ab0e5c82c6606ec99f64f64b660fea08"}, + {"id": "metal/titanium-anodised-bronze", "name": "Titanium, anodised bronze", "category": "Metal", "type": "metal", "tags": ["anodised", "brown", "thin-film", "polished", "jewellery"], "file": "metal/titanium-anodised-bronze.json", "sha256": "fb70a8d0acdb9e716faf3f0c579df2c31e666ab54d23849e05eac7d2537ebe1e"}, + {"id": "metal/titanium-anodised-gold", "name": "Titanium, anodised gold", "category": "Metal", "type": "metal", "tags": ["anodised", "gold", "thin-film", "polished", "jewellery"], "file": "metal/titanium-anodised-gold.json", "sha256": "68056219754cea202c66df590d761e9f390d70b37d10cc47cceeeda1219e12d0"}, + {"id": "metal/titanium-anodised-light-blue", "name": "Titanium, anodised light blue", "category": "Metal", "type": "metal", "tags": ["anodised", "blue", "thin-film", "polished", "jewellery"], "file": "metal/titanium-anodised-light-blue.json", "sha256": "67f69831efd0f08d7df5695a1a6b66799be976a94d6ea9ef0a08c51620e6c5fd"}, + {"id": "metal/titanium-anodised-magenta", "name": "Titanium, anodised magenta", "category": "Metal", "type": "metal", "tags": ["anodised", "pink", "thin-film", "polished", "jewellery"], "file": "metal/titanium-anodised-magenta.json", "sha256": "164ee778a21abb313fccc7c5e2b986adbbbb001867d0c94bb49554db1fe48234"}, + {"id": "metal/titanium-anodised-purple", "name": "Titanium, anodised purple", "category": "Metal", "type": "metal", "tags": ["anodised", "purple", "thin-film", "polished", "jewellery"], "file": "metal/titanium-anodised-purple.json", "sha256": "f776d2619076910aaf4b393c1c0eeaaed4c6459706d98aca229b0476b2dedc36"}, + {"id": "metal/titanium-bead-blasted", "name": "Titanium, bead blasted", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "rough", "opaque"], "file": "metal/titanium-bead-blasted.json", "sha256": "aba9d62d2847e32810de2edd042208452ffbbe2188ff3ff916ad84dacb3b1a82"}, + {"id": "metal/titanium-brushed", "name": "Titanium, brushed", "category": "Metal", "type": "metal_brushed", "tags": ["pure-metal", "grey", "industrial", "brushed", "opaque", "anisotropic"], "file": "metal/titanium-brushed.json", "sha256": "08ffe60e37b211a344ef82882177bc92acd55e54b98216423b2f8a57f6e21eb7"}, + {"id": "metal/titanium-polished", "name": "Titanium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], "file": "metal/titanium-polished.json", "sha256": "6c424eb99a6bbf055451e8ebecd92e3a34a5e85c5b7ecb2116b6973c0c1b81ac"}, + {"id": "metal/titanium-satin", "name": "Titanium, satin", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "satin", "opaque"], "file": "metal/titanium-satin.json", "sha256": "bc6ee61e2dc8b4c1057364169b00eee9087ec218e8f833e0a01182132488b6ef"}, + {"id": "metal/tungsten-polished", "name": "Tungsten, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], "file": "metal/tungsten-polished.json", "sha256": "e44f12134699ff3ac81a019c1848d80d7f87ae7ac9f74441b9d29d4cc8ae80cb"}, + {"id": "metal/vanadium-polished", "name": "Vanadium, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], "file": "metal/vanadium-polished.json", "sha256": "b614288b606bcda8e94710b542e422538ffb561b30fa0b4db26d1bc7ee2961a1"}, + {"id": "metal/zinc-polished", "name": "Zinc, polished", "category": "Metal", "type": "metal", "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], "file": "metal/zinc-polished.json", "sha256": "732763d7c33b676e9c874beeb324f6069120fe13a8324981930ab3983fd0ec5f"}, + {"id": "plastic/abs-black-gloss", "name": "ABS, black gloss", "category": "Plastic", "type": "plastic", "tags": ["polymer", "gloss", "black", "opaque", "electronics"], "file": "plastic/abs-black-gloss.json", "sha256": "4d16b80d20f34472a8f9c37df9f6edf4fc83444a0818456a16b818f7167446df"}, + {"id": "plastic/abs-black-matte", "name": "ABS, black matte", "category": "Plastic", "type": "plastic", "tags": ["polymer", "matte", "black", "opaque", "electronics"], "file": "plastic/abs-black-matte.json", "sha256": "3a42d07ff55cc8de366a1a48385e2d2512e55ee762c1d0345451671c1ab2ef57"}, + {"id": "plastic/abs-black-satin", "name": "ABS, black satin", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "black", "opaque", "electronics"], "file": "plastic/abs-black-satin.json", "sha256": "02e5784012240c61e66a2dd7ba7464e249f2592282ae531d5c13391fc3ffe665"}, + {"id": "plastic/abs-blue-gloss", "name": "ABS, blue gloss", "category": "Plastic", "type": "plastic", "tags": ["polymer", "gloss", "blue", "opaque", "electronics"], "file": "plastic/abs-blue-gloss.json", "sha256": "52f74212813da0dd7d47ad06e378a920921a53087f742716cee2841d67e27c9b"}, + {"id": "plastic/abs-grey-gloss", "name": "ABS, grey gloss", "category": "Plastic", "type": "plastic", "tags": ["polymer", "gloss", "grey", "opaque", "electronics"], "file": "plastic/abs-grey-gloss.json", "sha256": "3fa4cb6639685dd81e5f745a6dfbdfd253d934280502694346d4c60fdb73d7cf"}, + {"id": "plastic/abs-grey-matte", "name": "ABS, grey matte", "category": "Plastic", "type": "plastic", "tags": ["polymer", "matte", "grey", "opaque", "electronics"], "file": "plastic/abs-grey-matte.json", "sha256": "ee1f4fe47ada2c7390c93c551f5f3f1099c0a3e170a34a38311d84d0819907cf"}, + {"id": "plastic/abs-red-gloss", "name": "ABS, red gloss", "category": "Plastic", "type": "plastic", "tags": ["polymer", "gloss", "red", "opaque", "electronics"], "file": "plastic/abs-red-gloss.json", "sha256": "8c600ffea716f96b94d25473d504244106fa653ad13a35065250ca60bad77218"}, + {"id": "plastic/abs-white-gloss", "name": "ABS, white gloss", "category": "Plastic", "type": "plastic", "tags": ["polymer", "gloss", "white", "opaque", "electronics"], "file": "plastic/abs-white-gloss.json", "sha256": "57a178493b5e38397e400a6631bbb2a7fbac703c8381b5a910a12285a27f1510"}, + {"id": "plastic/abs-yellow-gloss", "name": "ABS, yellow gloss", "category": "Plastic", "type": "plastic", "tags": ["polymer", "gloss", "yellow", "opaque", "electronics"], "file": "plastic/abs-yellow-gloss.json", "sha256": "499ed022faa4650fa3b7d10a40f42395ec02f0b7a4da263541199129ad8f6444"}, + {"id": "plastic/acetal-black-satin", "name": "Acetal, black satin", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "black", "opaque", "industrial"], "file": "plastic/acetal-black-satin.json", "sha256": "f502bd6be2bf8fa3214de2dff203f40a1596a6a8573a1ea922aea69d22e7298d"}, + {"id": "plastic/acetal-white-satin", "name": "Acetal, white satin", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "white", "opaque", "industrial"], "file": "plastic/acetal-white-satin.json", "sha256": "9a9d2bb08090ab48544a4d6a1ce631f26acc219f6d571cf2f4d3aef3b479cb53"}, + {"id": "plastic/acrylic-amber", "name": "Acrylic, amber tint", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "orange", "tinted", "gloss"], "file": "plastic/acrylic-amber.json", "sha256": "9685d7957b03adfc20e428191f40737e660ba1e52f65a7d577af870aee5f71ff"}, + {"id": "plastic/acrylic-blue", "name": "Acrylic, blue tint", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "blue", "tinted", "gloss"], "file": "plastic/acrylic-blue.json", "sha256": "630ba0f369926d2a60b20e0921bfd05e375ef04b482f20cee5853dcc59789607"}, + {"id": "plastic/acrylic-clear", "name": "Acrylic, clear", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "gloss", "architectural"], "file": "plastic/acrylic-clear.json", "sha256": "68cdd2e4161e24ab1ab15730d4d33c3cb97182b64c29fb045ad33aa5538c893c"}, + {"id": "plastic/acrylic-frosted", "name": "Acrylic, frosted", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "frosted", "translucent"], "file": "plastic/acrylic-frosted.json", "sha256": "392f606204345a830d2d5bac4c2bd76fba414294bc6ced731589bbb1b0135146"}, + {"id": "plastic/acrylic-red", "name": "Acrylic, red tint", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "red", "tinted", "gloss"], "file": "plastic/acrylic-red.json", "sha256": "559c03caf34c7aafd923b8e2f46067c1f7b3da05a5ff90b387d0528f35100ebb"}, + {"id": "plastic/acrylic-smoke", "name": "Acrylic, smoke grey", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "grey", "tinted", "gloss"], "file": "plastic/acrylic-smoke.json", "sha256": "eab9bf428c62445057f1bca187fdc5f699612d69e16dda6cb5c0df8d91e878ff"}, + {"id": "plastic/cr39-clear", "name": "CR-39 lens resin, clear", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "gloss", "optics"], "file": "plastic/cr39-clear.json", "sha256": "881640bfa8655f703903e4a45c5e1105949365e94bd1145112ca2c9780cd354b"}, + {"id": "plastic/cellulose-acetate-clear", "name": "Cellulose acetate, clear", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "gloss", "apparel"], "file": "plastic/cellulose-acetate-clear.json", "sha256": "3708e0f4aeee6b68360295183184de0f5602e8c903124ca90cc4f3993f36ef7b"}, + {"id": "plastic/hdpe-natural", "name": "HDPE, natural translucent", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "white", "translucent", "subsurface", "packaging"], "file": "plastic/hdpe-natural.json", "sha256": "7590a3717c0c335f03f174c7a232466ff9cb6c420ae114b8860ab263f3987f5b"}, + {"id": "plastic/hdpe-white-matte", "name": "HDPE, white matte", "category": "Plastic", "type": "plastic", "tags": ["polymer", "matte", "white", "opaque", "packaging"], "file": "plastic/hdpe-white-matte.json", "sha256": "626b032a49ba0d646c0d8cc58fd3a9a2b9076bb88d8b7fbbd0c737f08bee552c"}, + {"id": "plastic/nylon-black-matte", "name": "Nylon, black matte", "category": "Plastic", "type": "plastic", "tags": ["polymer", "matte", "black", "opaque", "industrial"], "file": "plastic/nylon-black-matte.json", "sha256": "6103525b2de9155a04a0e55fb47632c850c3e560ae50bb16ff19274f152f1884"}, + {"id": "plastic/nylon-natural-matte", "name": "Nylon, natural matte", "category": "Plastic", "type": "plastic", "tags": ["polymer", "matte", "white", "opaque", "industrial"], "file": "plastic/nylon-natural-matte.json", "sha256": "f0bdae950a2b2f12d4d0a2ed1e51b07e8dfdb385ff856a2f0f847af26ef2c812"}, + {"id": "plastic/pet-amber", "name": "PET, amber bottle tint", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "brown", "tinted", "packaging"], "file": "plastic/pet-amber.json", "sha256": "cce163d890c153821da5a4b814762d3ae189127aae7fcec56676f4627a9f5cb6"}, + {"id": "plastic/pet-clear", "name": "PET, clear", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "gloss", "packaging"], "file": "plastic/pet-clear.json", "sha256": "60df5d5810d7f35bed6d21fe7d4b259cb969e58c9a90fca8563d52f9d6920ca2"}, + {"id": "plastic/pet-green", "name": "PET, green bottle tint", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "green", "tinted", "packaging"], "file": "plastic/pet-green.json", "sha256": "c956aa84f68c0b1db2e627079fbdb3d346d1777ac3d8f7263d7d4bac69fa4c3a"}, + {"id": "plastic/pla-orange-satin", "name": "PLA, orange satin", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "orange", "opaque", "industrial"], "file": "plastic/pla-orange-satin.json", "sha256": "983a1036799a9ef05b5630c6b89641f3a1642c622566cc89f8fe49783826c88b"}, + {"id": "plastic/pla-white-satin", "name": "PLA, white satin", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "white", "opaque", "industrial"], "file": "plastic/pla-white-satin.json", "sha256": "a241bf1a7af598fa55d820bd7cc3271a23d1dfc06e74214dfc5bca42974db8cd"}, + {"id": "plastic/pvc-grey-satin", "name": "PVC, grey satin", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "grey", "opaque", "architectural"], "file": "plastic/pvc-grey-satin.json", "sha256": "589f125f8cb822efa3938759746b5efdc4eba5698109d60e1211b14d3d752c2c"}, + {"id": "plastic/pvc-white-gloss", "name": "PVC, white gloss", "category": "Plastic", "type": "plastic", "tags": ["polymer", "gloss", "white", "opaque", "architectural"], "file": "plastic/pvc-white-gloss.json", "sha256": "475adf37975f6436b7d999b92bd5046189c72741d1dc9af8d6d0ad9a3da0b613"}, + {"id": "plastic/polycarbonate-clear", "name": "Polycarbonate, clear", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "gloss", "electronics"], "file": "plastic/polycarbonate-clear.json", "sha256": "223a44668abcee09575644a69e52528c5c0a2f3a2fb5302498917b5467a1c118"}, + {"id": "plastic/polycarbonate-frosted", "name": "Polycarbonate, frosted", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "frosted", "translucent", "lighting"], "file": "plastic/polycarbonate-frosted.json", "sha256": "733573726839288b51d6aab360ee432bda4826af870bd4fa34608f15a5a62d45"}, + {"id": "plastic/polypropylene-black-satin", "name": "Polypropylene, black satin", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "black", "opaque", "automotive"], "file": "plastic/polypropylene-black-satin.json", "sha256": "12d67291733275622dcc43160656451749904e5003649da11eb6308e646f705e"}, + {"id": "plastic/polypropylene-natural", "name": "Polypropylene, natural translucent", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "white", "translucent", "subsurface", "packaging"], "file": "plastic/polypropylene-natural.json", "sha256": "b927794f6c02662c8d556dfcc8ecb4d0551d66b6eaea94c3e70fe41fef9f19f8"}, + {"id": "plastic/polypropylene-white-satin", "name": "Polypropylene, white satin", "category": "Plastic", "type": "plastic", "tags": ["polymer", "satin", "white", "opaque", "packaging"], "file": "plastic/polypropylene-white-satin.json", "sha256": "95adc92079d0dd4fe3df67bcb001ebb69d49996cc19eee21f4c0930fafa763e1"}, + {"id": "plastic/polystyrene-clear", "name": "Polystyrene, clear", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "gloss", "packaging"], "file": "plastic/polystyrene-clear.json", "sha256": "7fbd4bcabeb8e3860295165c80a56a5de25f00da43d38b233e8c0923d5aeb3e9"}, + {"id": "plastic/pdms-clear", "name": "Silicone (PDMS), clear", "category": "Plastic", "type": "plastic_clear", "tags": ["polymer", "transparent", "clear", "gloss", "elastomer"], "file": "plastic/pdms-clear.json", "sha256": "03fe343af8e7eb1216145cdbdbb7b9e7a58449bf4fe5f85ccd758fbe464c8966"}, + {"id": "glass/bottle-glass-amber", "name": "Bottle glass, amber", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "brown", "tinted", "packaging"], "file": "glass/bottle-glass-amber.json", "sha256": "4029884ec062191e388fab036749e361e16055e93f21b101f571f56d33632899"}, + {"id": "glass/bottle-glass-green", "name": "Bottle glass, green", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "green", "tinted", "packaging"], "file": "glass/bottle-glass-green.json", "sha256": "49629b2ea6ed3e81aad2c51fbcf1f849fd353d6b57249215eb7609bac9520fb8"}, + {"id": "glass/cobalt-blue-glass", "name": "Cobalt blue glass", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "blue", "tinted", "tableware"], "file": "glass/cobalt-blue-glass.json", "sha256": "f610826ddb3ba7bb21a6bb31495d1baed1b3abae0b5b2e866bba0fe7bd6627df"}, + {"id": "glass/dense-flint-n-sf11", "name": "Dense flint glass (N-SF11)", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "clear", "optics", "dispersion"], "file": "glass/dense-flint-n-sf11.json", "sha256": "5048ae10d577990cd054a8cd45b68c2bdb22ccc36a26d87eec8ef1446ed3d05c"}, + {"id": "glass/fused-silica", "name": "Fused silica", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "clear", "optics"], "file": "glass/fused-silica.json", "sha256": "3ef4166f1ac16c1b64e924f09f9fae9e8895773d51479b5f69e96bc0d109a179"}, + {"id": "glass/opal-glass", "name": "Opal glass", "category": "Glass", "type": "glass", "tags": ["glass", "translucent", "subsurface", "white", "lighting"], "file": "glass/opal-glass.json", "sha256": "d3338f2e6887558f708fa92b8c4aa929033fd65b0ce92a00975a75dab8fe6e11"}, + {"id": "glass/optical-crown-n-bk7", "name": "Optical crown glass (N-BK7)", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "clear", "optics"], "file": "glass/optical-crown-n-bk7.json", "sha256": "bfe8308c84aa1f7dd6237deccd3a9588626f7ca79166a94644c58ea705a8c221"}, + {"id": "glass/optical-flint-n-f2", "name": "Optical flint glass (N-F2)", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "clear", "optics", "dispersion"], "file": "glass/optical-flint-n-f2.json", "sha256": "8ec949ee1545de949149c983d2cc1051f776aef2f0eb2ba8bf434dcd03e4a330"}, + {"id": "glass/window-glass-bronze", "name": "Window glass, bronze tint", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "brown", "tinted", "architectural"], "file": "glass/window-glass-bronze.json", "sha256": "3fb400bf3f9d5b572be08a88e832c5624ef5df908f491933d2dd09b9157b6306"}, + {"id": "glass/window-glass-clear", "name": "Window glass, clear", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "clear", "architectural"], "file": "glass/window-glass-clear.json", "sha256": "4953d7a83227a69611f29f7240a35114967374bf3df4bfeb158ddb169a764ff8"}, + {"id": "glass/window-glass-frosted", "name": "Window glass, frosted", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "clear", "frosted", "translucent", "architectural"], "file": "glass/window-glass-frosted.json", "sha256": "97e7c4024b2c8caa52f9018a2f86f37f37609737e93fa92c8b7835f5b797eb04"}, + {"id": "glass/window-glass-green", "name": "Window glass, green tint", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "green", "tinted", "architectural"], "file": "glass/window-glass-green.json", "sha256": "4c2d3e976daf72be7a2aecfceee7ec0e3620274c7390376995fb9b1bf7c46c45"}, + {"id": "glass/window-glass-grey", "name": "Window glass, grey tint", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "grey", "tinted", "architectural"], "file": "glass/window-glass-grey.json", "sha256": "b1d199a6445b54afb55ce6056bfeb1fcb0091ec5f53b958faeb0134baa2c572a"}, + {"id": "glass/window-glass-low-iron", "name": "Window glass, low iron", "category": "Glass", "type": "glass", "tags": ["glass", "transparent", "clear", "architectural"], "file": "glass/window-glass-low-iron.json", "sha256": "8d6ec233790b015bcfe859b1ba9b1b543f801a5dd684d3270eeac32177c130e6"}, + {"id": "glass/window-pane-thin-bronze", "name": "Window pane, thin bronze", "category": "Glass", "type": "glass_thin", "tags": ["glass", "transparent", "brown", "tinted", "architectural", "thin-walled"], "file": "glass/window-pane-thin-bronze.json", "sha256": "2f1f1db44a5cc691623233d4bd0821d89a52ed04ba0f92d4a0ca703376900a79"}, + {"id": "glass/window-pane-thin-frosted", "name": "Window pane, thin frosted", "category": "Glass", "type": "glass_thin", "tags": ["glass", "transparent", "clear", "frosted", "architectural", "thin-walled"], "file": "glass/window-pane-thin-frosted.json", "sha256": "43ad7758c481df4cffa6bcf6a8a72928584872f5b4b8d2e67a72138c767e7b27"}, + {"id": "glass/window-pane-thin", "name": "Window pane, thin shell", "category": "Glass", "type": "glass_thin", "tags": ["glass", "transparent", "clear", "architectural", "thin-walled"], "file": "glass/window-pane-thin.json", "sha256": "d03d5f3c89efab99e2ebad6e630797087233daeab72a7b6c5750f69b4a295e9e"}, + {"id": "paint/gloss-black", "name": "Gloss enamel, black", "category": "Paint", "type": "paint", "tags": ["paint", "gloss", "coat", "black", "opaque", "automotive"], "file": "paint/gloss-black.json", "sha256": "76ae12bde364f02188699ef2d48b0d388e855f090afeeeaba33a10032fb62139"}, + {"id": "paint/gloss-blue", "name": "Gloss enamel, blue", "category": "Paint", "type": "paint", "tags": ["paint", "gloss", "coat", "blue", "opaque", "automotive"], "file": "paint/gloss-blue.json", "sha256": "7f11ee1c5644a171ed5fda407537f58b3c219569652e7f5fd63ae51d4e4e65dc"}, + {"id": "paint/gloss-green", "name": "Gloss enamel, green", "category": "Paint", "type": "paint", "tags": ["paint", "gloss", "coat", "green", "opaque", "automotive"], "file": "paint/gloss-green.json", "sha256": "9afe034ecdd27497d5e8d3768c25a07f02a43ff9ff121c0fe4b6164e3ac68281"}, + {"id": "paint/gloss-orange", "name": "Gloss enamel, orange", "category": "Paint", "type": "paint", "tags": ["paint", "gloss", "coat", "orange", "opaque", "industrial"], "file": "paint/gloss-orange.json", "sha256": "9339cdd63f8f08b142931428e79744cdcd95f66d811b95d3ea97255e0051aa1e"}, + {"id": "paint/gloss-red", "name": "Gloss enamel, red", "category": "Paint", "type": "paint", "tags": ["paint", "gloss", "coat", "red", "opaque", "automotive"], "file": "paint/gloss-red.json", "sha256": "9e14205e538acd2f1569d2dce8383535de349e2d4809f4b764be4e8a0f67daea"}, + {"id": "paint/gloss-white", "name": "Gloss enamel, white", "category": "Paint", "type": "paint", "tags": ["paint", "gloss", "coat", "white", "opaque", "furniture"], "file": "paint/gloss-white.json", "sha256": "ea8755af517ae5e62f8a13c2246f112092fbe1b92203139da0e70f76a8b7b25c"}, + {"id": "paint/gloss-yellow", "name": "Gloss enamel, yellow", "category": "Paint", "type": "paint", "tags": ["paint", "gloss", "coat", "yellow", "opaque", "industrial"], "file": "paint/gloss-yellow.json", "sha256": "04c3c8236ec18a73fd729366251131c68b6f200981a0aa3f93ba893ba31ad273"}, + {"id": "paint/matte-black", "name": "Matte paint, black", "category": "Paint", "type": "paint", "tags": ["paint", "matte", "black", "opaque", "industrial"], "file": "paint/matte-black.json", "sha256": "658e4c9925f15cca983890cba809b277b71a2663cdc9079616d07bd35eed4eab"}, + {"id": "paint/matte-sage", "name": "Matte paint, sage green", "category": "Paint", "type": "paint", "tags": ["paint", "matte", "green", "opaque", "architectural"], "file": "paint/matte-sage.json", "sha256": "444d02eebda9b90de51d2f71e4ac8c3b8f42e0bc82b5ab1d8c0d513cd57facc4"}, + {"id": "paint/matte-terracotta", "name": "Matte paint, terracotta", "category": "Paint", "type": "paint", "tags": ["paint", "matte", "orange", "opaque", "architectural"], "file": "paint/matte-terracotta.json", "sha256": "318f23ba653db2d950d20d0bdd4accf132fd273a8475e528fdeaf0dbd1753c0a"}, + {"id": "paint/matte-white", "name": "Matte paint, white", "category": "Paint", "type": "paint", "tags": ["paint", "matte", "white", "opaque", "architectural"], "file": "paint/matte-white.json", "sha256": "a6fbfed5b02e4825c27403a3d7bc6e82a48e3f9d308c6d57b332a705e3c623b4"}, + {"id": "paint/metallic-black", "name": "Metallic paint, black", "category": "Paint", "type": "paint_metallic", "tags": ["paint", "coat", "black", "gloss", "automotive", "needs-graph"], "file": "paint/metallic-black.json", "sha256": "fcae9e243ebde50585b6edd70f5c735cab9161334e1e690414a6a77fa0c30e1d"}, + {"id": "paint/metallic-blue", "name": "Metallic paint, blue", "category": "Paint", "type": "paint_metallic", "tags": ["paint", "coat", "blue", "gloss", "automotive", "needs-graph"], "file": "paint/metallic-blue.json", "sha256": "18b73f9ab409bee929cf0f62770ec79c020d8ab4d5d849be4b4f9a5b72f48085"}, + {"id": "paint/metallic-champagne", "name": "Metallic paint, champagne", "category": "Paint", "type": "paint_metallic", "tags": ["paint", "coat", "gold", "gloss", "automotive", "needs-graph"], "file": "paint/metallic-champagne.json", "sha256": "9978f42f32d0e31445a76ed4febb1c4bb395c87c4850e2c8f159ec390a732f3e"}, + {"id": "paint/metallic-gunmetal", "name": "Metallic paint, gunmetal", "category": "Paint", "type": "paint_metallic", "tags": ["paint", "coat", "grey", "gloss", "automotive", "needs-graph"], "file": "paint/metallic-gunmetal.json", "sha256": "926384a686464dcb957795ddd8ccea1e987f24381964f3017a99cdeaa3384ff3"}, + {"id": "paint/metallic-red", "name": "Metallic paint, red", "category": "Paint", "type": "paint_metallic", "tags": ["paint", "coat", "red", "gloss", "automotive", "needs-graph"], "file": "paint/metallic-red.json", "sha256": "37ba392160e1421c489c22a81417daa3a32457fe0cd1c6b23b65f9d60d850e8b"}, + {"id": "paint/metallic-silver", "name": "Metallic paint, silver", "category": "Paint", "type": "paint_metallic", "tags": ["paint", "coat", "silver", "gloss", "automotive", "needs-graph"], "file": "paint/metallic-silver.json", "sha256": "4c4307f097f8c0cc29b82fa84b0d935ad12cd4c784c153724c4af8c64d719149"}, + {"id": "paint/pearl-blue", "name": "Pearl paint, blue", "category": "Paint", "type": "paint_metallic", "tags": ["paint", "coat", "thin-film", "blue", "gloss", "automotive", "needs-graph"], "file": "paint/pearl-blue.json", "sha256": "fd4cca065fdc0ef59ab8d284537b51149a095b015814de16ad83928232dd4918"}, + {"id": "paint/pearl-white", "name": "Pearl paint, white", "category": "Paint", "type": "paint_metallic", "tags": ["paint", "coat", "thin-film", "white", "gloss", "automotive", "needs-graph"], "file": "paint/pearl-white.json", "sha256": "5a0e86bfb1cfcfb78c82a744bdfd2d91db27149cee4f140ad38a2379e338a6de"}, + {"id": "paint/satin-blue", "name": "Satin paint, blue", "category": "Paint", "type": "paint", "tags": ["paint", "satin", "coat", "blue", "opaque", "furniture"], "file": "paint/satin-blue.json", "sha256": "46b0d166b8980a02038d79ec2e3cd6a3bc14c0c412075b6c9afd8c8ba8a2f704"}, + {"id": "paint/satin-grey", "name": "Satin paint, grey", "category": "Paint", "type": "paint", "tags": ["paint", "satin", "coat", "grey", "opaque", "architectural"], "file": "paint/satin-grey.json", "sha256": "93f58c82eeeff3a93196a205de1937f5600ec02938331b86f5b67a3eb1486529"}, + {"id": "paint/satin-white", "name": "Satin paint, white", "category": "Paint", "type": "paint", "tags": ["paint", "satin", "coat", "white", "opaque", "architectural"], "file": "paint/satin-white.json", "sha256": "cf68321d59e8e123de208d2208eed35fd38fc62e10af6200c71540d0e49f8ae4"}, + {"id": "rubber/black-rubber-matte", "name": "Black rubber, matte", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "matte", "black", "opaque", "industrial"], "file": "rubber/black-rubber-matte.json", "sha256": "b7ed77663bf4013b2c3210a2e510a5f339d9107dc2cfd7cc4a61b8c251bcdd52"}, + {"id": "rubber/black-rubber-satin", "name": "Black rubber, satin", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "satin", "black", "opaque", "industrial"], "file": "rubber/black-rubber-satin.json", "sha256": "b9b59849b41846501f4bacb437a7b0b1dabb48c0105874efe746e36be72954c8"}, + {"id": "rubber/epdm-grey", "name": "EPDM rubber, grey", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "matte", "grey", "opaque", "architectural"], "file": "rubber/epdm-grey.json", "sha256": "0285c80ffb31952055f50a91d3807b91f99a2c054d12def958568e027a4cd773"}, + {"id": "rubber/gum-rubber-natural", "name": "Gum rubber, natural", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "matte", "brown", "opaque", "apparel"], "file": "rubber/gum-rubber-natural.json", "sha256": "9ba8b5413f4604ad7e9558bf8f1d771a61cce6a14de60fdef9ab956b31c3694a"}, + {"id": "rubber/nitrile-blue", "name": "Nitrile rubber, blue", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "matte", "blue", "opaque", "industrial"], "file": "rubber/nitrile-blue.json", "sha256": "05a9be46f2f332dbdafb9a19b86fa6ae492d4f24198e627b4753da9c85c02983"}, + {"id": "rubber/silicone-rubber-red", "name": "Silicone rubber, red", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "satin", "red", "subsurface", "kitchen"], "file": "rubber/silicone-rubber-red.json", "sha256": "2ae609af296b91b4f3b797916046a8753504d35863d38b9e15f4959223fb6bf9"}, + {"id": "rubber/silicone-rubber-white", "name": "Silicone rubber, white", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "satin", "white", "subsurface", "kitchen"], "file": "rubber/silicone-rubber-white.json", "sha256": "0b96c86673b0f2573962fc18f83478635ea75edb18ab47a2e8e9408ecfc73340"}, + {"id": "rubber/soft-touch-black", "name": "Soft-touch coating, black", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "matte", "black", "opaque", "electronics"], "file": "rubber/soft-touch-black.json", "sha256": "115d6e6bab0f84f8087dade3c07af56ddd2f0ed032bc863c7b9ec97ba49f5dd4"}, + {"id": "rubber/tyre-rubber", "name": "Tyre rubber", "category": "Rubber", "type": "rubber", "tags": ["elastomer", "matte", "black", "opaque", "automotive"], "file": "rubber/tyre-rubber.json", "sha256": "3690d7ff5816dc5c040d26ec56c13ef48a3b701df7cdb74d89086c34db999cb4"}, + {"id": "fabric/cotton-navy", "name": "Cotton, navy", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "matte", "blue", "apparel"], "file": "fabric/cotton-navy.json", "sha256": "bb572102a71a0f38b5f6cc9511ed2a399bcdf03333db1ca95eda353b29fcafad"}, + {"id": "fabric/cotton-red", "name": "Cotton, red", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "matte", "red", "apparel"], "file": "fabric/cotton-red.json", "sha256": "df137464a30bbb4816592627be73659ffb85cb31f89db6eb8fbc56cd0a852ef8"}, + {"id": "fabric/cotton-white", "name": "Cotton, white", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "matte", "white", "apparel"], "file": "fabric/cotton-white.json", "sha256": "d2caaa1dff7750de0f4cd4a24d616c2b6d1e3584c20f7a6ada4784ed433b8902"}, + {"id": "fabric/denim-blue", "name": "Denim, indigo", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "matte", "blue", "apparel"], "file": "fabric/denim-blue.json", "sha256": "39548cac6e912a6bc8b49dccfaa32d3acb3d0a7f9c439dc77514be3270c5256c"}, + {"id": "fabric/felt-charcoal", "name": "Felt, charcoal", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "matte", "grey", "apparel"], "file": "fabric/felt-charcoal.json", "sha256": "3196022b46798182706e3a77b7206087a7e4381b6f6852af20724d554905e52d"}, + {"id": "fabric/linen-natural", "name": "Linen, natural", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "matte", "brown", "apparel"], "file": "fabric/linen-natural.json", "sha256": "7f7cf0db2f51d9ea819642a6f0a11045c7c3d38f17c199b160bf1789605defa7"}, + {"id": "fabric/polyester-black", "name": "Polyester, black", "category": "Fabric", "type": "fabric", "tags": ["synthetic-fibre", "fuzz", "matte", "black", "apparel"], "file": "fabric/polyester-black.json", "sha256": "df408732c7bddde9e12fcdfecf883e281a5304d8c5564598a0cc73bb9fe80401"}, + {"id": "fabric/polyester-grey", "name": "Polyester, grey", "category": "Fabric", "type": "fabric", "tags": ["synthetic-fibre", "fuzz", "matte", "grey", "apparel"], "file": "fabric/polyester-grey.json", "sha256": "8087f505e16b83dbffe9acb5952aa5618c9d98de1c58b50a28038f52b0e0e030"}, + {"id": "fabric/silk-ivory", "name": "Silk, ivory", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "satin", "anisotropic", "white", "apparel"], "file": "fabric/silk-ivory.json", "sha256": "1e6260dec76b10961565dbc661e96ed339993a59ab4f06573b1e4bfffa47abad"}, + {"id": "fabric/velvet-black", "name": "Velvet, black", "category": "Fabric", "type": "fabric", "tags": ["synthetic-fibre", "fuzz", "matte", "black", "furniture"], "file": "fabric/velvet-black.json", "sha256": "d0cd41bd9b09d97ad7f4b46a2a45163087afc0867d62c855a03dad3e29b075d7"}, + {"id": "fabric/velvet-burgundy", "name": "Velvet, burgundy", "category": "Fabric", "type": "fabric", "tags": ["synthetic-fibre", "fuzz", "matte", "red", "furniture"], "file": "fabric/velvet-burgundy.json", "sha256": "ecd3af61748c656cabf98483ac3d7de303e7a406cab19c8774dd7e91fdc04086"}, + {"id": "fabric/wool-camel", "name": "Wool, camel", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "matte", "brown", "apparel"], "file": "fabric/wool-camel.json", "sha256": "fac618974c9926d232d6d389198947886aaca388466a618d6877729cc5f71642"}, + {"id": "fabric/wool-grey", "name": "Wool, grey", "category": "Fabric", "type": "fabric", "tags": ["natural-fibre", "fuzz", "matte", "grey", "apparel"], "file": "fabric/wool-grey.json", "sha256": "3a788e8c274ceb537501fcd22f4d748536774783467c02ebaf3930fa8f36c714"}, + {"id": "wood/ash-oiled", "name": "Ash, oiled", "category": "Wood", "type": "wood", "tags": ["wood", "satin", "brown", "needs-graph", "furniture"], "file": "wood/ash-oiled.json", "sha256": "e9496d61be7a1c8422aa9b14d49db523c100cb1424486b57e0d6bb4a10c4360d"}, + {"id": "wood/cherry-oiled", "name": "Cherry, oiled", "category": "Wood", "type": "wood", "tags": ["wood", "satin", "red", "needs-graph", "furniture"], "file": "wood/cherry-oiled.json", "sha256": "7497998ac807953e0418069caebb174b6f110b6c5ef6e950535cf31c071940bf"}, + {"id": "wood/ebony-polished", "name": "Ebony, polished", "category": "Wood", "type": "wood", "tags": ["wood", "gloss", "black", "needs-graph", "furniture", "coat"], "file": "wood/ebony-polished.json", "sha256": "50c69af92af19f2e6911cb3c7b1f0f847c946e78c489f6f6dfe286b3cea05898"}, + {"id": "wood/maple-lacquered", "name": "Maple, lacquered", "category": "Wood", "type": "wood", "tags": ["wood", "gloss", "yellow", "needs-graph", "furniture", "coat"], "file": "wood/maple-lacquered.json", "sha256": "5ca75fd20a85eecd248e31384f03968b84a3a2f080eec2bd7cd40761b3a4d884"}, + {"id": "wood/oak-lacquered", "name": "Oak, lacquered", "category": "Wood", "type": "wood", "tags": ["wood", "gloss", "brown", "needs-graph", "furniture", "coat"], "file": "wood/oak-lacquered.json", "sha256": "e5c10b31e3204f0b45da2d6fb63c12f861021e4b74131e60a9947628a2c1f424"}, + {"id": "wood/oak-oiled", "name": "Oak, oiled", "category": "Wood", "type": "wood", "tags": ["wood", "satin", "brown", "needs-graph", "furniture"], "file": "wood/oak-oiled.json", "sha256": "7d04f2d8ebe0f75ed54060ef5ce4801710405eabf6840264f7e595a8136b65f7"}, + {"id": "wood/pine-raw", "name": "Pine, raw", "category": "Wood", "type": "wood", "tags": ["wood", "matte", "yellow", "needs-graph", "furniture"], "file": "wood/pine-raw.json", "sha256": "d29bab325b9bc13d61e83ba0f08a3019750cfe53ed246458dbff510b8fae56f3"}, + {"id": "wood/teak-oiled", "name": "Teak, oiled", "category": "Wood", "type": "wood", "tags": ["wood", "satin", "brown", "needs-graph", "furniture"], "file": "wood/teak-oiled.json", "sha256": "0386c4472db41a7d87c6fd31ba6e4f89e1072c9ef812d6cc8e544d49d7b7ae11"}, + {"id": "wood/walnut-lacquered", "name": "Walnut, lacquered", "category": "Wood", "type": "wood", "tags": ["wood", "gloss", "brown", "needs-graph", "furniture", "coat"], "file": "wood/walnut-lacquered.json", "sha256": "1afdaf72df5f1e12359d15a86fe77b8d0e42df3a6c1a4ee46ea5539e4b8e7432"}, + {"id": "wood/walnut-oiled", "name": "Walnut, oiled", "category": "Wood", "type": "wood", "tags": ["wood", "satin", "brown", "needs-graph", "furniture"], "file": "wood/walnut-oiled.json", "sha256": "01f188938a2c3eb4a98bd483a89d0e439b34f0c5b1ed25f272b7bb1dd2a09199"}, + {"id": "stone/concrete", "name": "Concrete, smooth", "category": "Stone", "type": "stone", "tags": ["stone", "matte", "grey", "needs-graph", "architectural"], "file": "stone/concrete.json", "sha256": "feacea5b86844001119c6d98aea44f3f7172e1fa112f134516c6adf08163ca9b"}, + {"id": "stone/granite-black-polished", "name": "Granite, black polished", "category": "Stone", "type": "stone", "tags": ["stone", "polished", "black", "needs-graph", "architectural"], "file": "stone/granite-black-polished.json", "sha256": "3f80626f5b1a49c45df16c9e0e3a43c2abbca0e8213f1c73f56ecdedf53d3d56"}, + {"id": "stone/granite-grey-honed", "name": "Granite, grey honed", "category": "Stone", "type": "stone", "tags": ["stone", "satin", "grey", "needs-graph", "architectural"], "file": "stone/granite-grey-honed.json", "sha256": "0f86dd653488f33c28bc781e4a0909ff52fe9a7675095c4c4805a658e629d777"}, + {"id": "stone/limestone", "name": "Limestone, sawn", "category": "Stone", "type": "stone", "tags": ["stone", "matte", "white", "needs-graph", "architectural"], "file": "stone/limestone.json", "sha256": "e73277652fce9c4aef6810ff1bb404a625d8c01ffd966804cc16e82ab3345c5d"}, + {"id": "stone/marble-black-polished", "name": "Marble, black polished", "category": "Stone", "type": "stone", "tags": ["stone", "polished", "black", "needs-graph", "architectural"], "file": "stone/marble-black-polished.json", "sha256": "7ce8d47a5177d89a72f43fa871051d3b3e5649b2256a57269e0092326942bf5d"}, + {"id": "stone/marble-white-honed", "name": "Marble, white honed", "category": "Stone", "type": "stone", "tags": ["stone", "satin", "white", "subsurface", "needs-graph", "architectural"], "file": "stone/marble-white-honed.json", "sha256": "7c22da53ec0ba4f6529468cde4fc6de72fddb4bc505466374911fe8dbcdee7d5"}, + {"id": "stone/marble-white-polished", "name": "Marble, white polished", "category": "Stone", "type": "stone", "tags": ["stone", "polished", "white", "subsurface", "needs-graph", "architectural"], "file": "stone/marble-white-polished.json", "sha256": "80e2498c82e8bd3ec345d48e29d6c8b4409978c19b5b902e42a851d0c804fd07"}, + {"id": "stone/sandstone", "name": "Sandstone, sawn", "category": "Stone", "type": "stone", "tags": ["stone", "matte", "brown", "needs-graph", "architectural"], "file": "stone/sandstone.json", "sha256": "1c9759f7230134335eb070b9e96c8a4dfdf801f574e355fc134f9b6a1582c80c"}, + {"id": "stone/slate", "name": "Slate, riven", "category": "Stone", "type": "stone", "tags": ["stone", "matte", "grey", "needs-graph", "architectural"], "file": "stone/slate.json", "sha256": "14c954be6812b0f64e07432372ad49f05d650225fbd1c5dd14c5f4b75650eab9"}, + {"id": "stone/travertine-honed", "name": "Travertine, honed", "category": "Stone", "type": "stone", "tags": ["stone", "satin", "brown", "needs-graph", "architectural"], "file": "stone/travertine-honed.json", "sha256": "df637c1208687cc73e4f9c91e279f077d9fa6d6a7e5aedcb6ea9d2abd42ada89"}, + {"id": "ceramic/alumina-technical", "name": "Alumina ceramic, technical", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "satin", "white", "opaque", "industrial"], "file": "ceramic/alumina-technical.json", "sha256": "1f9bd95a209d968d8bc7c72bfcd0a2e5f4ff35fcd2defc58f85fb000d9bca4c0"}, + {"id": "ceramic/bisque-white-unglazed", "name": "Bisque, unglazed white", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "matte", "white", "opaque", "tableware"], "file": "ceramic/bisque-white-unglazed.json", "sha256": "a9c6ecaabb8e8215e3fd6123bee9c530469bfd2ad4b22cb4317a7a7356aad46d"}, + {"id": "ceramic/glazed-black", "name": "Glazed ceramic, black", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "gloss", "coat", "black", "opaque", "tableware"], "file": "ceramic/glazed-black.json", "sha256": "2a3e5c33ea3ecf36a86362452cae197f1dddd251054da8be6857d649e74998d8"}, + {"id": "ceramic/glazed-celadon", "name": "Glazed ceramic, celadon", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "gloss", "coat", "green", "opaque", "tableware"], "file": "ceramic/glazed-celadon.json", "sha256": "5c9d2669ba87f1113fea7d5368fcbea4c48c9d7590ed28280c90a3a04875c405"}, + {"id": "ceramic/glazed-cobalt-blue", "name": "Glazed ceramic, cobalt blue", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "gloss", "coat", "blue", "opaque", "tableware"], "file": "ceramic/glazed-cobalt-blue.json", "sha256": "ff94ebe40b4ee27ea9a5edc9d27bbf55281adcb06b414e2ae848b1139bc1809b"}, + {"id": "ceramic/glazed-white", "name": "Glazed ceramic, white", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "gloss", "coat", "white", "opaque", "tableware"], "file": "ceramic/glazed-white.json", "sha256": "48f33659c08505c5384abb9a65424c05ceebd7daa071f5c071aad6057eafac85"}, + {"id": "ceramic/glazed-tile-white", "name": "Glazed tile, white", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "gloss", "coat", "white", "opaque", "architectural"], "file": "ceramic/glazed-tile-white.json", "sha256": "a7225d5efde799356f3b00126823d5ada67f69c47e2f6a9ce1f8fe1fc333045f"}, + {"id": "ceramic/porcelain-glazed", "name": "Porcelain, glazed", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "gloss", "coat", "subsurface", "white", "tableware"], "file": "ceramic/porcelain-glazed.json", "sha256": "2d57ed2a847b184c2722d3b8405ab42e49655ef39d28ce810d249ab5920270cf"}, + {"id": "ceramic/stoneware-matte-glaze", "name": "Stoneware, matte glaze", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "matte", "coat", "grey", "opaque", "tableware"], "file": "ceramic/stoneware-matte-glaze.json", "sha256": "212fd0b7fc896ec04c1f50165ccd5b6c8504c8e8b86c265c69215def90e9548b"}, + {"id": "ceramic/terracotta-unglazed", "name": "Terracotta, unglazed", "category": "Ceramic", "type": "ceramic", "tags": ["ceramic", "matte", "orange", "opaque", "architectural"], "file": "ceramic/terracotta-unglazed.json", "sha256": "1c6b132ec4eab7e8a3e107e3e178bd8f563ddb3d10fbae6c5eb575c76862ee2e"}, + {"id": "liquid/apple-juice", "name": "Apple juice, clear", "category": "Liquid", "type": "liquid", "tags": ["beverage", "transparent", "tinted", "orange", "kitchen"], "file": "liquid/apple-juice.json", "sha256": "8630409c49f91b427600d6c39e473c24f24ce6ab067206af21760e5aebcc42a1"}, + {"id": "liquid/beer-lager", "name": "Beer, lager", "category": "Liquid", "type": "liquid", "tags": ["transparent", "tinted", "gold", "beverage"], "file": "liquid/beer-lager.json", "sha256": "e2408e561b7ab89c4f72e5be2ab9d30afc6c1d3a1582437bd7111f4e9bf9fb42"}, + {"id": "liquid/coffee-black", "name": "Coffee, black", "category": "Liquid", "type": "liquid", "tags": ["transparent", "tinted", "brown", "beverage"], "file": "liquid/coffee-black.json", "sha256": "4b05e9b149de894812a557ce83660b1c7ad52474c48614ab9a4ab289b054b720"}, + {"id": "liquid/cola", "name": "Cola", "category": "Liquid", "type": "liquid", "tags": ["beverage", "transparent", "tinted", "brown", "kitchen"], "file": "liquid/cola.json", "sha256": "e835bba437d1745fed25b515c92b6ba30a48c358490e18ef60748a1ddd7918b6"}, + {"id": "liquid/ethanol", "name": "Ethanol", "category": "Liquid", "type": "liquid", "tags": ["transparent", "clear"], "file": "liquid/ethanol.json", "sha256": "fa76e240cf86133aa7e5830b14f90a3de486c809939655a5c856741e43677c17"}, + {"id": "liquid/glycerol", "name": "Glycerol", "category": "Liquid", "type": "liquid", "tags": ["transparent", "clear"], "file": "liquid/glycerol.json", "sha256": "4309d7465da2dd8dc0870f257976aa1eb5501b0fe16e67f8875fb3241a9de7be"}, + {"id": "liquid/honey", "name": "Honey", "category": "Liquid", "type": "liquid", "tags": ["food", "transparent", "tinted", "orange", "kitchen"], "file": "liquid/honey.json", "sha256": "e817ee53f8cd5085146b535f323903a69a98a139c5b5b71e3fc451839c3dc0de"}, + {"id": "liquid/maple-syrup", "name": "Maple syrup", "category": "Liquid", "type": "liquid", "tags": ["food", "transparent", "tinted", "brown", "kitchen"], "file": "liquid/maple-syrup.json", "sha256": "8495455bce6f2328302a65a745e0f85456bd637a45f863203b3ebf695af6176f"}, + {"id": "liquid/milk", "name": "Milk", "category": "Liquid", "type": "liquid", "tags": ["beverage", "food", "subsurface", "translucent", "white"], "file": "liquid/milk.json", "sha256": "ec0da264af5b0ee55ce7e1b44ed88ca1d8015e675d5bc81eb64992763c152e58"}, + {"id": "liquid/motor-oil", "name": "Motor oil", "category": "Liquid", "type": "liquid", "tags": ["transparent", "tinted", "orange", "oil", "industrial"], "file": "liquid/motor-oil.json", "sha256": "7e777178375ef0a7f9838f5d2870312d6837bdb4b12cc8e474930a75ca4a326a"}, + {"id": "liquid/olive-oil", "name": "Olive oil", "category": "Liquid", "type": "liquid", "tags": ["oil", "food", "transparent", "tinted", "yellow", "kitchen"], "file": "liquid/olive-oil.json", "sha256": "f09cf0febc9b99db12d110b2c0eaf4f3ab99a3dba0ca9877f83b038d8b9aa172"}, + {"id": "liquid/orange-juice", "name": "Orange juice", "category": "Liquid", "type": "liquid", "tags": ["beverage", "food", "subsurface", "translucent", "orange"], "file": "liquid/orange-juice.json", "sha256": "3b8ee25460a0131b195bd05ea5539faf5f8b151e9a3accef681f1e6034895c3f"}, + {"id": "liquid/red-wine", "name": "Red wine", "category": "Liquid", "type": "liquid", "tags": ["transparent", "tinted", "red", "beverage"], "file": "liquid/red-wine.json", "sha256": "a88e662df285590a84d8db89fdba1e3b30eb0df0eead74671194bcd34109ae07"}, + {"id": "liquid/tea", "name": "Tea", "category": "Liquid", "type": "liquid", "tags": ["transparent", "tinted", "brown", "beverage"], "file": "liquid/tea.json", "sha256": "d31d936ef165ba5d4c73180a821cc47a56b7437eaf31ce361a49b96b2ce9f4b2"}, + {"id": "liquid/vegetable-oil", "name": "Vegetable oil, light", "category": "Liquid", "type": "liquid", "tags": ["oil", "food", "transparent", "tinted", "yellow", "kitchen"], "file": "liquid/vegetable-oil.json", "sha256": "94693ce1986f622fb862de2e2716c3aa62bc4e2ce5503609a11e16dfcb5988ca"}, + {"id": "liquid/water", "name": "Water", "category": "Liquid", "type": "liquid", "tags": ["water", "transparent", "clear", "beverage"], "file": "liquid/water.json", "sha256": "847f47e26168952709c358d42c1e9e15309bcef19583ce33f6b9a5027cab2119"}, + {"id": "liquid/white-wine", "name": "White wine", "category": "Liquid", "type": "liquid", "tags": ["transparent", "tinted", "yellow", "beverage"], "file": "liquid/white-wine.json", "sha256": "7dc1a398878696716a8fde34d25560d8e863a9db7250ee21d61f1aa23b5bf600"}, + {"id": "gem/amethyst", "name": "Amethyst", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "purple", "tinted", "jewellery"], "file": "gem/amethyst.json", "sha256": "da291f5ca5c06caef9505922138f27e5e500a648aff3e9ebc2b29fe2c298cd5d"}, + {"id": "gem/aquamarine", "name": "Aquamarine", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "blue", "tinted", "jewellery"], "file": "gem/aquamarine.json", "sha256": "2a4a5d97119bd47fb41fc79b0348ca76a42a05cb7f79695e6e47c338ad88e0ee"}, + {"id": "gem/chrysoberyl", "name": "Chrysoberyl", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "yellow", "tinted", "jewellery"], "file": "gem/chrysoberyl.json", "sha256": "ac64f658588af4539acff998842e094892b1dbafcfe3a79b074ba8dd6f9bfa85"}, + {"id": "gem/citrine", "name": "Citrine", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "yellow", "tinted", "jewellery"], "file": "gem/citrine.json", "sha256": "17f0fb5ed1a8ce7adc479bd0a6f3a63abefc169265ab98711428dbda579d3e44"}, + {"id": "gem/cubic-zirconia", "name": "Cubic zirconia", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery", "synthetic"], "file": "gem/cubic-zirconia.json", "sha256": "5ecf2429f24db5e8e7f56a93cba3918358fe9d9bbff8fff799d3d92710084ee5"}, + {"id": "gem/diamond", "name": "Diamond", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery"], "file": "gem/diamond.json", "sha256": "8836774a0905122b63bb2fa2b2e2dcd79dc22e5212f748bcdcbec835477501d6"}, + {"id": "gem/emerald", "name": "Emerald", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "green", "tinted", "jewellery"], "file": "gem/emerald.json", "sha256": "9634d6833d996627eeab60f5b8340c1c24598692a7bfdcf6094518bc5476f1f5"}, + {"id": "gem/fluorite-purple", "name": "Fluorite, purple", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "purple", "tinted", "mineral"], "file": "gem/fluorite-purple.json", "sha256": "1bfd1d92f7c578434d7110382fb82c1f727174027700d1c4d0c6f80dd940a7fe"}, + {"id": "gem/garnet-almandine", "name": "Garnet, almandine", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "red", "tinted", "jewellery"], "file": "gem/garnet-almandine.json", "sha256": "9d4b26f808967fe1048c2d43796b2e75c308c924523316e423cea720828a5d2f"}, + {"id": "gem/moissanite", "name": "Moissanite", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery", "synthetic"], "file": "gem/moissanite.json", "sha256": "479cf259ad0b497ac12da8c123f859267cb263b8a3f7061d2899ca26e0bc512e"}, + {"id": "gem/peridot", "name": "Peridot", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "green", "tinted", "jewellery"], "file": "gem/peridot.json", "sha256": "e8fbb0dd44e7603cf99329a8be2bdbafd1d66f7598ffb56de5a055fd2f82f296"}, + {"id": "gem/rock-crystal", "name": "Quartz, rock crystal", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "clear", "mineral"], "file": "gem/rock-crystal.json", "sha256": "7010dbd11a905b52baf774e0988827d7feceea2a105548cbd98b0a862aa69959"}, + {"id": "gem/smoky-quartz", "name": "Quartz, smoky", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "brown", "tinted", "mineral"], "file": "gem/smoky-quartz.json", "sha256": "a3ae97d64a0dfd01ec0c415eb4fdc65be406e86ebca6bcaa553125ea8fe7c581"}, + {"id": "gem/ruby", "name": "Ruby", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "red", "tinted", "jewellery"], "file": "gem/ruby.json", "sha256": "28018171b7ba83e880a6f61c432f52ead70137c4d2ec44d73ebe064926160e2b"}, + {"id": "gem/sapphire-blue", "name": "Sapphire, blue", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "blue", "tinted", "jewellery"], "file": "gem/sapphire-blue.json", "sha256": "7e94d8143dcbef9e22a4e533b0d7b1f1566f6024676da47e57b502a53dcf7ccf"}, + {"id": "gem/white-sapphire", "name": "Sapphire, colourless", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery"], "file": "gem/white-sapphire.json", "sha256": "8fc99ba64d9d031b285289096b06785e51074a3b6dbb5ff12e7bca25384b7aff"}, + {"id": "gem/spinel-red", "name": "Spinel, red", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "red", "tinted", "jewellery"], "file": "gem/spinel-red.json", "sha256": "9d34550f1ff16a906b562cb1eaac2c758801c05d5d6e8bcb2e95368ea0305bf5"}, + {"id": "gem/topaz-blue", "name": "Topaz, blue", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "blue", "tinted", "jewellery"], "file": "gem/topaz-blue.json", "sha256": "91981c5c043aeb9e490f83729e5e3794f32b7ddba0a3ee5659a304a130c5cecf"}, + {"id": "gem/tourmaline-green", "name": "Tourmaline, green", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "green", "tinted", "jewellery"], "file": "gem/tourmaline-green.json", "sha256": "54ae3fc276f51c191b4109f30d55cbfec5cb32b3ff965270d8af61675448116e"}, + {"id": "gem/tourmaline-pink", "name": "Tourmaline, pink", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "pink", "tinted", "jewellery"], "file": "gem/tourmaline-pink.json", "sha256": "b95f2947e8b81894293b2ff8fd6e937de2aad7cb2ea85d4709814bf0a61d30ec"}, + {"id": "gem/yag", "name": "YAG, colourless", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "clear", "optics", "synthetic"], "file": "gem/yag.json", "sha256": "002bb08504366b2db7ba4810439876e342e2f8502a6651a1b57e398b7c0c77cf"}, + {"id": "gem/zircon", "name": "Zircon, colourless", "category": "Gem", "type": "gem", "tags": ["crystal", "transparent", "dispersion", "clear", "jewellery"], "file": "gem/zircon.json", "sha256": "35716c19b1d8c9b6dc2361d6d4f4d16b711b76782db79c948c76c9dd2ae1e2e3"}, + {"id": "emissive/display-white-srgb", "name": "Display white, sRGB reference", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "display", "white", "electronics"], "file": "emissive/display-white-srgb.json", "sha256": "ce60fdd12d195b43ee2b7ddf5a5848299d082ea397ba051855722c4ec15275f4"}, + {"id": "emissive/electroluminescent-green", "name": "Electroluminescent panel, green", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "green", "display"], "file": "emissive/electroluminescent-green.json", "sha256": "6821292fc731da73bdcddb03210411ff3011bc4893dd668ae23f6ab84873ae85"}, + {"id": "emissive/fluorescent-tube-4000k", "name": "Fluorescent tube, 4000 K", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "white", "lighting"], "file": "emissive/fluorescent-tube-4000k.json", "sha256": "4c0c992723757a6e3f2aa748747ddc131639f08c803f438e26df69c428f38aa6"}, + {"id": "emissive/hdr-display-peak", "name": "HDR display, peak white", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "display", "white", "electronics"], "file": "emissive/hdr-display-peak.json", "sha256": "0ea75be8cd983d44478934879b822afd730f06f30fd85e02321b5c538e51793c"}, + {"id": "emissive/incandescent-frosted-2700k", "name": "Incandescent bulb, frosted", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "orange", "lighting"], "file": "emissive/incandescent-frosted-2700k.json", "sha256": "cf471630c28c4ce332be7acfd414d34d78eafd7499d3d6d8210ae5075576bfcc"}, + {"id": "emissive/indicator-led-red", "name": "Indicator LED, red", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "red", "electronics"], "file": "emissive/indicator-led-red.json", "sha256": "2f2111d92eb738021c1de7a09448ded7a5d3ddcac17011edfaf77511195e8bc1"}, + {"id": "emissive/monitor-white-lcd", "name": "LCD monitor, white", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "display", "white", "electronics"], "file": "emissive/monitor-white-lcd.json", "sha256": "223ebb08068a406b9ddda7a7027b949a24cdbb67f854676c096901697cbcddc5"}, + {"id": "emissive/light-box-6500k", "name": "Light box, daylight", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "white", "lighting"], "file": "emissive/light-box-6500k.json", "sha256": "69cc4c7c0985be5a2dcd52d4983ffd5b4cd7cf9979425a3955537c036b3acdf0"}, + {"id": "emissive/sodium-lamp-low-pressure", "name": "Sodium lamp, low pressure", "category": "Emissive", "type": "emissive", "tags": ["light-source", "emissive", "orange", "lighting"], "file": "emissive/sodium-lamp-low-pressure.json", "sha256": "9ee60465bf69a8db46c1d30c0d402ae7c53c8ce05869c338bbc908e2d567ac76"} + ] +} diff --git a/assets/library/materials/liquid/apple-juice.json b/assets/library/materials/liquid/apple-juice.json new file mode 100644 index 00000000..d06b08e5 --- /dev/null +++ b/assets/library/materials/liquid/apple-juice.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/apple-juice", + "name": "Apple juice, clear", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.3506, + "transmission_weight": 1.0, + "transmission_color": [0.5318, 0.3446, 0.0697], + "transmission_depth": 0.05 + }, + "tags": ["beverage", "transparent", "tinted", "orange", "kitchen"], + "source": { + "kind": "published", + "reference": "USDA AMS, Sucrose Conversion Table, SCI Division Technical Procedures Manual, Appendix XV (refractive index of sucrose solutions at 20 C, ICUMSA basis)", + "urls": ["https://www.ams.usda.gov/sites/default/files/media/SucroseConversionTableXV.pdf"], + "notes": "Clear apple juice is about 11 to 12 degrees Brix; specular_ior 1.3506 is the tabulated index of a 11.8 degree Brix sucrose solution at 20 C (the Brix level is authored). transmission_color authored as sRGB #d89a2a, the colour through a glass's width of 5 cm.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/beer-lager.json b/assets/library/materials/liquid/beer-lager.json new file mode 100644 index 00000000..a8e9e489 --- /dev/null +++ b/assets/library/materials/liquid/beer-lager.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/beer-lager", + "name": "Beer, lager", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.341, + "transmission_weight": 1.0, + "transmission_color": [0.5139, 0.3425, 0.0591], + "transmission_depth": 0.05 + }, + "tags": ["transparent", "tinted", "gold", "beverage"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Lager at about 5 percent ethanol and 3 to 4 degrees of residual extract: index 1.341 authored. transmission_color authored as sRGB #d49a1c, the colour through transmission_depth 0.05 m. Smooth free surface (roughness 0).", + "authored": ["base_color", "specular_roughness", "specular_ior", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/coffee-black.json b/assets/library/materials/liquid/coffee-black.json new file mode 100644 index 00000000..486050af --- /dev/null +++ b/assets/library/materials/liquid/coffee-black.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/coffee-black", + "name": "Coffee, black", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.335, + "transmission_weight": 1.0, + "transmission_color": [0.0167, 0.0081, 0.0034], + "transmission_depth": 0.005 + }, + "tags": ["transparent", "tinted", "brown", "beverage"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Brewed coffee is about 1.5 percent dissolved solids: index 1.335 authored just above water. transmission_color authored as sRGB #2a1408, the colour through transmission_depth 0.005 m. Smooth free surface (roughness 0).", + "authored": ["base_color", "specular_roughness", "specular_ior", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/cola.json b/assets/library/materials/liquid/cola.json new file mode 100644 index 00000000..14bd7b25 --- /dev/null +++ b/assets/library/materials/liquid/cola.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/cola", + "name": "Cola", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.3487, + "transmission_weight": 1.0, + "transmission_color": [0.0296, 0.0125, 0.0046], + "transmission_depth": 0.02 + }, + "tags": ["beverage", "transparent", "tinted", "brown", "kitchen"], + "source": { + "kind": "published", + "reference": "USDA AMS, Sucrose Conversion Table, SCI Division Technical Procedures Manual, Appendix XV (refractive index of sucrose solutions at 20 C, ICUMSA basis)", + "urls": ["https://www.ams.usda.gov/sites/default/files/media/SucroseConversionTableXV.pdf"], + "notes": "Cola carries about 10.6 g of sugar per 100 g; specular_ior 1.3487 is the tabulated index of a 10.6 degree Brix sucrose solution at 20 C (the Brix level is authored). transmission_color authored as sRGB #3a1a0a, the colour through 2 cm.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/ethanol.json b/assets/library/materials/liquid/ethanol.json new file mode 100644 index 00000000..ac72c96f --- /dev/null +++ b/assets/library/materials/liquid/ethanol.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/ethanol", + "name": "Ethanol", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.3617, + "transmission_weight": 1.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 59.4 + }, + "tags": ["transparent", "clear"], + "source": { + "kind": "measured", + "reference": "J. Rheims, J Köser, T Wriedt. Refractive-index measurements in the near-IR using an Abbe refractometer. Meas. Sci. Technol. 8, 601-605 (1997); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/C2H6O%20-%20ethanol/nk/Rheims.yml"], + "notes": "Clear spirit base (pure ethanol). specular_ior 1.3617 and Abbe number 59.4 from measured n; absorption negligible at product scale.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/glycerol.json b/assets/library/materials/liquid/glycerol.json new file mode 100644 index 00000000..a93bdc62 --- /dev/null +++ b/assets/library/materials/liquid/glycerol.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/glycerol", + "name": "Glycerol", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.4713, + "transmission_weight": 1.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 64.4 + }, + "tags": ["transparent", "clear"], + "source": { + "kind": "measured", + "reference": "V. Gupta, O. Aftenieva, P. T. Probst, S. Sarkar, A. M. Steiner, N. Vogel, A. Fery, T. A. F. König. Advanced colloidal sensors enabled by an out-of-plane lattice resonance. Adv. Photonics Res. 2022, 2200152 (see supporting information); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/C3H8O3%20-%20glycerol/nk/Gupta.yml"], + "notes": "Clear viscous glycerol. specular_ior 1.4713 and Abbe number 64.4 from measured n; absorption negligible at product scale.", + "authored": [] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/honey.json b/assets/library/materials/liquid/honey.json new file mode 100644 index 00000000..dd2e9c8c --- /dev/null +++ b/assets/library/materials/liquid/honey.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/honey", + "name": "Honey", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.4906, + "transmission_weight": 1.0, + "transmission_color": [0.4447, 0.274, 0.0451], + "transmission_depth": 0.02 + }, + "tags": ["food", "transparent", "tinted", "orange", "kitchen"], + "source": { + "kind": "published", + "reference": "USDA AMS, Sucrose Conversion Table, SCI Division Technical Procedures Manual, Appendix XV (refractive index of sucrose solutions at 20 C, ICUMSA basis)", + "urls": ["https://www.ams.usda.gov/sites/default/files/media/SucroseConversionTableXV.pdf"], + "notes": "Honey is about 80 degrees Brix (17 to 20 percent water); specular_ior 1.4906 is the tabulated index of a 80.0 degree Brix sucrose solution at 20 C (the Brix level is authored). transmission_color authored as sRGB #c98a12, the colour through a jar's depth of 2 cm.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/maple-syrup.json b/assets/library/materials/liquid/maple-syrup.json new file mode 100644 index 00000000..a46b7fe2 --- /dev/null +++ b/assets/library/materials/liquid/maple-syrup.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/maple-syrup", + "name": "Maple syrup", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.4558, + "transmission_weight": 1.0, + "transmission_color": [0.2243, 0.0926, 0.0203], + "transmission_depth": 0.02 + }, + "tags": ["food", "transparent", "tinted", "brown", "kitchen"], + "source": { + "kind": "published", + "reference": "USDA AMS, Sucrose Conversion Table, SCI Division Technical Procedures Manual, Appendix XV (refractive index of sucrose solutions at 20 C, ICUMSA basis)", + "urls": ["https://www.ams.usda.gov/sites/default/files/media/SucroseConversionTableXV.pdf"], + "notes": "Maple syrup is standardised at about 66 degrees Brix; specular_ior 1.4558 is the tabulated index of a 66.0 degree Brix sucrose solution at 20 C (the Brix level is authored). transmission_color authored as sRGB #9a4e12, the colour through 2 cm.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/milk.json b/assets/library/materials/liquid/milk.json new file mode 100644 index 00000000..3cccf632 --- /dev/null +++ b/assets/library/materials/liquid/milk.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/milk", + "name": "Milk", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [0.9127, 0.9052, 0.8618], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.347, + "transmission_weight": 0.0, + "subsurface_weight": 1.0, + "subsurface_color": [0.9127, 0.9052, 0.8618], + "subsurface_radius": 0.0005, + "subsurface_radius_scale": [1.0, 0.9, 0.75] + }, + "tags": ["beverage", "food", "subsurface", "translucent", "white"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Whole milk: fat globules and casein micelles scatter strongly, so it is modelled with subsurface (transmission off); mean free path 0.5 mm, shorter in blue, authored. Index 1.347 authored within the published 1.344 to 1.349 of milk at 20 C.", + "authored": ["base_color", "specular_roughness", "specular_ior", "subsurface_color", "subsurface_radius", "subsurface_radius_scale"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/motor-oil.json b/assets/library/materials/liquid/motor-oil.json new file mode 100644 index 00000000..e094167e --- /dev/null +++ b/assets/library/materials/liquid/motor-oil.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/motor-oil", + "name": "Motor oil", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.48, + "transmission_weight": 1.0, + "transmission_color": [0.2956, 0.1761, 0.0348], + "transmission_depth": 0.02 + }, + "tags": ["transparent", "tinted", "orange", "oil", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Mineral base oil: index 1.48 authored, typical of paraffinic lubricating oils. transmission_color authored as sRGB #a8701a, the colour through transmission_depth 0.02 m. Smooth free surface (roughness 0).", + "authored": ["base_color", "specular_roughness", "specular_ior", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/olive-oil.json b/assets/library/materials/liquid/olive-oil.json new file mode 100644 index 00000000..b0ebe08a --- /dev/null +++ b/assets/library/materials/liquid/olive-oil.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/olive-oil", + "name": "Olive oil", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.4695, + "transmission_weight": 1.0, + "transmission_color": [0.4424, 0.4318, 0.0776], + "transmission_depth": 0.05 + }, + "tags": ["oil", "food", "transparent", "tinted", "yellow", "kitchen"], + "source": { + "kind": "published", + "reference": "S. H. Jones, M. D. King, A. D. Ward. Atmospherically relevant core-shell aerosol studied using optical trapping and Mie scattering. Chem. Commun. 51, 4914-4917 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/C18H34O2%20-%20oleic%20acid/nk/Jones.yml"], + "notes": "specular_ior 1.4695 is the measured n of oleic acid at 587.6 nm; vegetable oils are mostly oleic and linoleic triglycerides and their standard index range (olive oil 1.4677 to 1.4705) contains it. transmission_color authored as sRGB #b8b02a, the oil's colour through 0.05 m, a bottle's width.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/orange-juice.json b/assets/library/materials/liquid/orange-juice.json new file mode 100644 index 00000000..1697439d --- /dev/null +++ b/assets/library/materials/liquid/orange-juice.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/orange-juice", + "name": "Orange juice", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [0.6597, 0.3592, 0.0629], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.3506, + "transmission_weight": 0.0, + "subsurface_weight": 1.0, + "subsurface_color": [0.6597, 0.3592, 0.0629], + "subsurface_radius": 0.002, + "subsurface_radius_scale": [1.0, 0.7, 0.4] + }, + "tags": ["beverage", "food", "subsurface", "translucent", "orange"], + "source": { + "kind": "published", + "reference": "USDA AMS, Sucrose Conversion Table, SCI Division Technical Procedures Manual, Appendix XV (refractive index of sucrose solutions at 20 C, ICUMSA basis)", + "urls": ["https://www.ams.usda.gov/sites/default/files/media/SucroseConversionTableXV.pdf"], + "notes": "Orange juice carries pulp and cloud that scatter: subsurface (transmission off), 2 mm mean free path, colour sRGB #f39a1a, authored. specular_ior is the tabulated index of an 11.8 degree Brix sucrose solution (USDA's minimum for orange juice from concentrate; the Brix level is authored).", + "authored": ["base_color", "subsurface_color", "subsurface_radius", "subsurface_radius_scale"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/red-wine.json b/assets/library/materials/liquid/red-wine.json new file mode 100644 index 00000000..ce0e1e0a --- /dev/null +++ b/assets/library/materials/liquid/red-wine.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/red-wine", + "name": "Red wine", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.343, + "transmission_weight": 1.0, + "transmission_color": [0.0642, 0.0101, 0.0114], + "transmission_depth": 0.01 + }, + "tags": ["transparent", "tinted", "red", "beverage"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "About 12 percent ethanol in water with a little residual sugar and extract: index 1.343 authored between water (1.333) and the mixture's components. transmission_color authored as sRGB #5a0a1a, the colour through transmission_depth 0.01 m. Smooth free surface (roughness 0).", + "authored": ["base_color", "specular_roughness", "specular_ior", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/tea.json b/assets/library/materials/liquid/tea.json new file mode 100644 index 00000000..898559d6 --- /dev/null +++ b/assets/library/materials/liquid/tea.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/tea", + "name": "Tea", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.334, + "transmission_weight": 1.0, + "transmission_color": [0.2217, 0.0855, 0.0202], + "transmission_depth": 0.03 + }, + "tags": ["transparent", "tinted", "brown", "beverage"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Brewed black tea, under 1 percent solids: index 1.334 authored just above water. transmission_color authored as sRGB #9a4a14, the colour through transmission_depth 0.03 m. Smooth free surface (roughness 0).", + "authored": ["base_color", "specular_roughness", "specular_ior", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/vegetable-oil.json b/assets/library/materials/liquid/vegetable-oil.json new file mode 100644 index 00000000..858c6a10 --- /dev/null +++ b/assets/library/materials/liquid/vegetable-oil.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/vegetable-oil", + "name": "Vegetable oil, light", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.4695, + "transmission_weight": 1.0, + "transmission_color": [0.7114, 0.6298, 0.1739], + "transmission_depth": 0.05 + }, + "tags": ["oil", "food", "transparent", "tinted", "yellow", "kitchen"], + "source": { + "kind": "published", + "reference": "S. H. Jones, M. D. King, A. D. Ward. Atmospherically relevant core-shell aerosol studied using optical trapping and Mie scattering. Chem. Commun. 51, 4914-4917 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/C18H34O2%20-%20oleic%20acid/nk/Jones.yml"], + "notes": "specular_ior 1.4695 is the measured n of oleic acid at 587.6 nm; vegetable oils are mostly oleic and linoleic triglycerides and their standard index range (olive oil 1.4677 to 1.4705) contains it. transmission_color authored as sRGB #e8cf5a, the oil's colour through 0.05 m, a bottle's width.", + "authored": ["transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/water.json b/assets/library/materials/liquid/water.json new file mode 100644 index 00000000..6865e9d2 --- /dev/null +++ b/assets/library/materials/liquid/water.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/water", + "name": "Water", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.3334, + "transmission_weight": 1.0, + "transmission_color": [0.4782, 0.8, 0.8848], + "transmission_depth": 4.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 55.8 + }, + "tags": ["water", "transparent", "clear", "beverage"], + "source": { + "kind": "measured", + "reference": "M. Daimon and A. Masumura. Measurement of the refractive index of distilled water from the near-infrared region to the ultraviolet region. Appl. Opt. 46, 3811-3820 (2007); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024); G. M. Hale and M. R. Querry. Optical constants of water in the 200-nm to 200-µm wavelength region. Appl. Opt. 12, 555-563 (1973) See also Segelstein 1981 for more recent data from the same group.; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/H2O/nk/Daimon-20.0C.yml", "https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/H2O/nk/Hale.yml"], + "notes": "Pure water at 20 C: specular_ior 1.3334 and Abbe number 55.8 from Daimon and Masumura's measured n. transmission_color is the Beer-Lambert transmittance of Hale and Querry's measured absorption k through transmission_depth 4 m (CIE 1931 under D65): water's own faint blue, only visible in deep volumes. The 4 m depth was chosen so the colour keeps its hue in RGB; it is the same absorption at every scale.", + "authored": ["transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/liquid/white-wine.json b/assets/library/materials/liquid/white-wine.json new file mode 100644 index 00000000..1403067c --- /dev/null +++ b/assets/library/materials/liquid/white-wine.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "liquid/white-wine", + "name": "White wine", + "category": "Liquid", + "type": "liquid", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.0, + "specular_ior": 1.342, + "transmission_weight": 1.0, + "transmission_color": [0.7255, 0.6752, 0.3111], + "transmission_depth": 0.05 + }, + "tags": ["transparent", "tinted", "yellow", "beverage"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Dry white wine: index 1.342 authored as for red wine with less extract. transmission_color authored as sRGB #e6d68a, the colour through transmission_depth 0.05 m. Smooth free surface (roughness 0).", + "authored": ["base_color", "specular_roughness", "specular_ior", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-anodised-black.json b/assets/library/materials/metal/aluminium-anodised-black.json new file mode 100644 index 00000000..d5ae2bf8 --- /dev/null +++ b/assets/library/materials/metal/aluminium-anodised-black.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-anodised-black", + "name": "Aluminium, anodised black", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "coat_weight": 1.0, + "coat_color": [0.007, 0.007, 0.007], + "coat_roughness": 0.15, + "coat_ior": 1.65 + }, + "tags": ["anodised", "black", "satin", "coat", "electronics"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "Aluminium under a dyed anodic oxide layer. The metal is measured (see the polished aluminium preset). The oxide is modelled as a coat: coat_color authored as sRGB #141414, the dye's look over bright aluminium; coat_ior 1.65 authored, in the range of amorphous anodic alumina, below crystalline sapphire's ordinary index of 1.7682; roughness 0.3 for the etched metal and 0.15 for the sealed oxide, a typical bead-blasted and anodised product finish.", + "authored": ["specular_roughness", "coat_color", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-anodised-blue.json b/assets/library/materials/metal/aluminium-anodised-blue.json new file mode 100644 index 00000000..1c4f423c --- /dev/null +++ b/assets/library/materials/metal/aluminium-anodised-blue.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-anodised-blue", + "name": "Aluminium, anodised blue", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "coat_weight": 1.0, + "coat_color": [0.0555, 0.0784, 0.3865], + "coat_roughness": 0.15, + "coat_ior": 1.65 + }, + "tags": ["anodised", "blue", "satin", "coat", "electronics"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "Aluminium under a dyed anodic oxide layer. The metal is measured (see the polished aluminium preset). The oxide is modelled as a coat: coat_color authored as sRGB #1f4fb0, the dye's look over bright aluminium; coat_ior 1.65 authored, in the range of amorphous anodic alumina, below crystalline sapphire's ordinary index of 1.7682; roughness 0.3 for the etched metal and 0.15 for the sealed oxide, a typical bead-blasted and anodised product finish.", + "authored": ["specular_roughness", "coat_color", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-anodised-bronze.json b/assets/library/materials/metal/aluminium-anodised-bronze.json new file mode 100644 index 00000000..7c96c13f --- /dev/null +++ b/assets/library/materials/metal/aluminium-anodised-bronze.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-anodised-bronze", + "name": "Aluminium, anodised bronze", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "coat_weight": 1.0, + "coat_color": [0.156, 0.1079, 0.052], + "coat_roughness": 0.15, + "coat_ior": 1.65 + }, + "tags": ["anodised", "brown", "satin", "coat", "electronics"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "Aluminium under a dyed anodic oxide layer. The metal is measured (see the polished aluminium preset). The oxide is modelled as a coat: coat_color authored as sRGB #7a5a3a, the dye's look over bright aluminium; coat_ior 1.65 authored, in the range of amorphous anodic alumina, below crystalline sapphire's ordinary index of 1.7682; roughness 0.3 for the etched metal and 0.15 for the sealed oxide, a typical bead-blasted and anodised product finish.", + "authored": ["specular_roughness", "coat_color", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-anodised-gold.json b/assets/library/materials/metal/aluminium-anodised-gold.json new file mode 100644 index 00000000..02909d4a --- /dev/null +++ b/assets/library/materials/metal/aluminium-anodised-gold.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-anodised-gold", + "name": "Aluminium, anodised gold", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "coat_weight": 1.0, + "coat_color": [0.5543, 0.3938, 0.0765], + "coat_roughness": 0.15, + "coat_ior": 1.65 + }, + "tags": ["anodised", "gold", "satin", "coat", "electronics"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "Aluminium under a dyed anodic oxide layer. The metal is measured (see the polished aluminium preset). The oxide is modelled as a coat: coat_color authored as sRGB #d9a52b, the dye's look over bright aluminium; coat_ior 1.65 authored, in the range of amorphous anodic alumina, below crystalline sapphire's ordinary index of 1.7682; roughness 0.3 for the etched metal and 0.15 for the sealed oxide, a typical bead-blasted and anodised product finish.", + "authored": ["specular_roughness", "coat_color", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-anodised-green.json b/assets/library/materials/metal/aluminium-anodised-green.json new file mode 100644 index 00000000..d2d0efd0 --- /dev/null +++ b/assets/library/materials/metal/aluminium-anodised-green.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-anodised-green", + "name": "Aluminium, anodised green", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "coat_weight": 1.0, + "coat_color": [0.1127, 0.2543, 0.0675], + "coat_roughness": 0.15, + "coat_ior": 1.65 + }, + "tags": ["anodised", "green", "satin", "coat", "electronics"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "Aluminium under a dyed anodic oxide layer. The metal is measured (see the polished aluminium preset). The oxide is modelled as a coat: coat_color authored as sRGB #2f8f3a, the dye's look over bright aluminium; coat_ior 1.65 authored, in the range of amorphous anodic alumina, below crystalline sapphire's ordinary index of 1.7682; roughness 0.3 for the etched metal and 0.15 for the sealed oxide, a typical bead-blasted and anodised product finish.", + "authored": ["specular_roughness", "coat_color", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-anodised-purple.json b/assets/library/materials/metal/aluminium-anodised-purple.json new file mode 100644 index 00000000..81015158 --- /dev/null +++ b/assets/library/materials/metal/aluminium-anodised-purple.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-anodised-purple", + "name": "Aluminium, anodised purple", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "coat_weight": 1.0, + "coat_color": [0.1127, 0.0377, 0.2949], + "coat_roughness": 0.15, + "coat_ior": 1.65 + }, + "tags": ["anodised", "purple", "satin", "coat", "electronics"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "Aluminium under a dyed anodic oxide layer. The metal is measured (see the polished aluminium preset). The oxide is modelled as a coat: coat_color authored as sRGB #6a2c9c, the dye's look over bright aluminium; coat_ior 1.65 authored, in the range of amorphous anodic alumina, below crystalline sapphire's ordinary index of 1.7682; roughness 0.3 for the etched metal and 0.15 for the sealed oxide, a typical bead-blasted and anodised product finish.", + "authored": ["specular_roughness", "coat_color", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-anodised-red.json b/assets/library/materials/metal/aluminium-anodised-red.json new file mode 100644 index 00000000..2e63add8 --- /dev/null +++ b/assets/library/materials/metal/aluminium-anodised-red.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-anodised-red", + "name": "Aluminium, anodised red", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "coat_weight": 1.0, + "coat_color": [0.3292, 0.0505, 0.0326], + "coat_roughness": 0.15, + "coat_ior": 1.65 + }, + "tags": ["anodised", "red", "satin", "coat", "electronics"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "Aluminium under a dyed anodic oxide layer. The metal is measured (see the polished aluminium preset). The oxide is modelled as a coat: coat_color authored as sRGB #c0202a, the dye's look over bright aluminium; coat_ior 1.65 authored, in the range of amorphous anodic alumina, below crystalline sapphire's ordinary index of 1.7682; roughness 0.3 for the etched metal and 0.15 for the sealed oxide, a typical bead-blasted and anodised product finish.", + "authored": ["specular_roughness", "coat_color", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-anodised-rose.json b/assets/library/materials/metal/aluminium-anodised-rose.json new file mode 100644 index 00000000..0996a20f --- /dev/null +++ b/assets/library/materials/metal/aluminium-anodised-rose.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-anodised-rose", + "name": "Aluminium, anodised rose", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "coat_weight": 1.0, + "coat_color": [0.4725, 0.2268, 0.242], + "coat_roughness": 0.15, + "coat_ior": 1.65 + }, + "tags": ["anodised", "pink", "satin", "coat", "electronics"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "Aluminium under a dyed anodic oxide layer. The metal is measured (see the polished aluminium preset). The oxide is modelled as a coat: coat_color authored as sRGB #d27a86, the dye's look over bright aluminium; coat_ior 1.65 authored, in the range of amorphous anodic alumina, below crystalline sapphire's ordinary index of 1.7682; roughness 0.3 for the etched metal and 0.15 for the sealed oxide, a typical bead-blasted and anodised product finish.", + "authored": ["specular_roughness", "coat_color", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-as-cast.json b/assets/library/materials/metal/aluminium-as-cast.json new file mode 100644 index 00000000..6904479f --- /dev/null +++ b/assets/library/materials/metal/aluminium-as-cast.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-as-cast", + "name": "Aluminium, as cast", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.55 + }, + "tags": ["pure-metal", "silver", "electronics", "rough", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0067 of the exact Fresnel reflectance at every angle. Roughness authored, as cast or hot rolled: coarse surface, broad highlight.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-bead-blasted.json b/assets/library/materials/metal/aluminium-bead-blasted.json new file mode 100644 index 00000000..1f6b0533 --- /dev/null +++ b/assets/library/materials/metal/aluminium-bead-blasted.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-bead-blasted", + "name": "Aluminium, bead blasted", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.45 + }, + "tags": ["pure-metal", "silver", "electronics", "rough", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0067 of the exact Fresnel reflectance at every angle. Roughness authored, bead blasted: uniform micro-roughness, reflections blurred to a sheen.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-brushed.json b/assets/library/materials/metal/aluminium-brushed.json new file mode 100644 index 00000000..1904f282 --- /dev/null +++ b/assets/library/materials/metal/aluminium-brushed.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-brushed", + "name": "Aluminium, brushed", + "category": "Metal", + "type": "metal_brushed", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.3, + "specular_roughness_anisotropy": 0.8 + }, + "tags": ["pure-metal", "silver", "electronics", "brushed", "opaque", "anisotropic"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0067 of the exact Fresnel reflectance at every angle. Roughness authored, brushed: directional grain; anisotropy 0.8 stretches the highlight across the grain.", + "authored": ["specular_roughness", "specular_roughness_anisotropy"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-polished.json b/assets/library/materials/metal/aluminium-polished.json new file mode 100644 index 00000000..46eb6f95 --- /dev/null +++ b/assets/library/materials/metal/aluminium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-polished", + "name": "Aluminium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0067 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/aluminium-satin.json b/assets/library/materials/metal/aluminium-satin.json new file mode 100644 index 00000000..c3ba4a33 --- /dev/null +++ b/assets/library/materials/metal/aluminium-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/aluminium-satin", + "name": "Aluminium, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9104, 0.9156, 0.9215], + "base_metalness": 1.0, + "specular_color": [0.9009, 0.9166, 0.9429], + "specular_roughness": 0.25 + }, + "tags": ["pure-metal", "silver", "electronics", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Al/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0067 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/beryllium-polished.json b/assets/library/materials/metal/beryllium-polished.json new file mode 100644 index 00000000..f1b65b82 --- /dev/null +++ b/assets/library/materials/metal/beryllium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/beryllium-polished", + "name": "Beryllium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5373, 0.5357, 0.5355], + "base_metalness": 1.0, + "specular_color": [0.7323, 0.7356, 0.752], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "A. D. Rakić, A. B. Djurišic, J. M. Elazar, M. L. Majewski. Optical properties of metallic films for vertical-cavity optoelectronic devices. Appl. Opt. 37, 5271-5283 (1998) [Calculation script (Python)]; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Be/nk/Rakic-LD.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0273 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/bismuth-polished.json b/assets/library/materials/metal/bismuth-polished.json new file mode 100644 index 00000000..7183c223 --- /dev/null +++ b/assets/library/materials/metal/bismuth-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/bismuth-polished", + "name": "Bismuth, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5471, 0.5319, 0.4915], + "base_metalness": 1.0, + "specular_color": [0.8263, 0.8447, 0.8943], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "H.-J. Hagemann, W. Gudat, C. Kunz. Optical constants from the far infrared to the x-ray region: Mg, Al, Cu, Ag, Au, Bi, C, and Al2O3. J. Opt. Soc. Am. 65, 742-744 (1975); H.-J. Hagemann, W. Gudat, and C. Kunz. DESY report SR-74/7 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Bi/nk/Hagemann.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0077 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/brass-brushed.json b/assets/library/materials/metal/brass-brushed.json new file mode 100644 index 00000000..5ad39daf --- /dev/null +++ b/assets/library/materials/metal/brass-brushed.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/brass-brushed", + "name": "Brass, brushed", + "category": "Metal", + "type": "metal_brushed", + "params": { + "base_color": [0.842, 0.7827, 0.4718], + "base_metalness": 1.0, + "specular_color": [0.9631, 0.9771, 1.0], + "specular_roughness": 0.3, + "specular_roughness_anisotropy": 0.8 + }, + "tags": ["alloy", "gold", "architectural", "brushed", "opaque", "anisotropic"], + "source": { + "kind": "measured", + "reference": "M. R. Querry. Optical constants, Contractor Report CRDC-CR-85034 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/Cu-Zn/nk/Querry-Cu70Zn30.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0214 of the exact Fresnel reflectance at every angle. Roughness authored, brushed: directional grain; anisotropy 0.8 stretches the highlight across the grain.", + "authored": ["specular_roughness", "specular_roughness_anisotropy"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/brass-polished.json b/assets/library/materials/metal/brass-polished.json new file mode 100644 index 00000000..3aff3f66 --- /dev/null +++ b/assets/library/materials/metal/brass-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/brass-polished", + "name": "Brass (Cu70 Zn30), polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.842, 0.7827, 0.4718], + "base_metalness": 1.0, + "specular_color": [0.9631, 0.9771, 1.0], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "gold", "architectural", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "M. R. Querry. Optical constants, Contractor Report CRDC-CR-85034 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/Cu-Zn/nk/Querry-Cu70Zn30.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0214 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/brass-satin.json b/assets/library/materials/metal/brass-satin.json new file mode 100644 index 00000000..7baf426f --- /dev/null +++ b/assets/library/materials/metal/brass-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/brass-satin", + "name": "Brass, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.842, 0.7827, 0.4718], + "base_metalness": 1.0, + "specular_color": [0.9631, 0.9771, 1.0], + "specular_roughness": 0.25 + }, + "tags": ["alloy", "gold", "architectural", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "M. R. Querry. Optical constants, Contractor Report CRDC-CR-85034 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/Cu-Zn/nk/Querry-Cu70Zn30.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0214 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/chromium-polished.json b/assets/library/materials/metal/chromium-polished.json new file mode 100644 index 00000000..735abec6 --- /dev/null +++ b/assets/library/materials/metal/chromium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/chromium-polished", + "name": "Chromium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6457, 0.6498, 0.6538], + "base_metalness": 1.0, + "specular_color": [0.7404, 0.7584, 0.8073], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "automotive", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "A. D. Rakić, A. B. Djurišic, J. M. Elazar, M. L. Majewski. Optical properties of metallic films for vertical-cavity optoelectronic devices. Appl. Opt. 37, 5271-5283 (1998) [Calculation script (Python)]; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Cr/nk/Rakic-LD.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0273 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/chromium-satin.json b/assets/library/materials/metal/chromium-satin.json new file mode 100644 index 00000000..e8384182 --- /dev/null +++ b/assets/library/materials/metal/chromium-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/chromium-satin", + "name": "Chromium, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6457, 0.6498, 0.6538], + "base_metalness": 1.0, + "specular_color": [0.7404, 0.7584, 0.8073], + "specular_roughness": 0.25 + }, + "tags": ["pure-metal", "silver", "automotive", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "A. D. Rakić, A. B. Djurišic, J. M. Elazar, M. L. Majewski. Optical properties of metallic films for vertical-cavity optoelectronic devices. Appl. Opt. 37, 5271-5283 (1998) [Calculation script (Python)]; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Cr/nk/Rakic-LD.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0273 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/cobalt-polished.json b/assets/library/materials/metal/cobalt-polished.json new file mode 100644 index 00000000..78de9fab --- /dev/null +++ b/assets/library/materials/metal/cobalt-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/cobalt-polished", + "name": "Cobalt, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6704, 0.6566, 0.6217], + "base_metalness": 1.0, + "specular_color": [0.8087, 0.8187, 0.8531], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Co/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0125 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/copper-bead-blasted.json b/assets/library/materials/metal/copper-bead-blasted.json new file mode 100644 index 00000000..2a1a16cf --- /dev/null +++ b/assets/library/materials/metal/copper-bead-blasted.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/copper-bead-blasted", + "name": "Copper, bead blasted", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9015, 0.7108, 0.5855], + "base_metalness": 1.0, + "specular_color": [0.9872, 0.9665, 0.9613], + "specular_roughness": 0.45 + }, + "tags": ["pure-metal", "orange", "kitchen", "rough", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Cu/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0074 of the exact Fresnel reflectance at every angle. Roughness authored, bead blasted: uniform micro-roughness, reflections blurred to a sheen.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/copper-brushed.json b/assets/library/materials/metal/copper-brushed.json new file mode 100644 index 00000000..cc25619f --- /dev/null +++ b/assets/library/materials/metal/copper-brushed.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/copper-brushed", + "name": "Copper, brushed", + "category": "Metal", + "type": "metal_brushed", + "params": { + "base_color": [0.9015, 0.7108, 0.5855], + "base_metalness": 1.0, + "specular_color": [0.9872, 0.9665, 0.9613], + "specular_roughness": 0.3, + "specular_roughness_anisotropy": 0.8 + }, + "tags": ["pure-metal", "orange", "kitchen", "brushed", "opaque", "anisotropic"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Cu/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0074 of the exact Fresnel reflectance at every angle. Roughness authored, brushed: directional grain; anisotropy 0.8 stretches the highlight across the grain.", + "authored": ["specular_roughness", "specular_roughness_anisotropy"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/copper-polished.json b/assets/library/materials/metal/copper-polished.json new file mode 100644 index 00000000..216426cb --- /dev/null +++ b/assets/library/materials/metal/copper-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/copper-polished", + "name": "Copper, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9015, 0.7108, 0.5855], + "base_metalness": 1.0, + "specular_color": [0.9872, 0.9665, 0.9613], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "orange", "kitchen", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Cu/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0074 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/copper-satin.json b/assets/library/materials/metal/copper-satin.json new file mode 100644 index 00000000..785f1352 --- /dev/null +++ b/assets/library/materials/metal/copper-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/copper-satin", + "name": "Copper, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9015, 0.7108, 0.5855], + "base_metalness": 1.0, + "specular_color": [0.9872, 0.9665, 0.9613], + "specular_roughness": 0.25 + }, + "tags": ["pure-metal", "orange", "kitchen", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Cu/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0074 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/electrum-polished.json b/assets/library/materials/metal/electrum-polished.json new file mode 100644 index 00000000..55998758 --- /dev/null +++ b/assets/library/materials/metal/electrum-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/electrum-polished", + "name": "Electrum (Au50 Ag50), polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9047, 0.896, 0.6597], + "base_metalness": 1.0, + "specular_color": [0.9732, 0.9765, 1.0], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "gold", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "D. Rioux, S. Vallières, S. Besner, P. Muñoz, E. Mazur, M. Meunier. An analytic model for the dielectric function of Au, Ag, and their alloys. Adv. Opt. Mater. 2, 176-182 (2014) (See Supporting information for MATLAB model); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/Au-Ag/nk/Rioux-Au50Ag50.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0203 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/gilding-metal-polished.json b/assets/library/materials/metal/gilding-metal-polished.json new file mode 100644 index 00000000..69e6bd11 --- /dev/null +++ b/assets/library/materials/metal/gilding-metal-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/gilding-metal-polished", + "name": "Gilding metal (Cu90 Zn10), polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.8544, 0.7275, 0.5016], + "base_metalness": 1.0, + "specular_color": [0.9795, 0.9921, 1.0], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "orange", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "M. R. Querry. Optical constants, Contractor Report CRDC-CR-85034 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/Cu-Zn/nk/Querry-Cu90Zn10.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0195 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/gold-brushed.json b/assets/library/materials/metal/gold-brushed.json new file mode 100644 index 00000000..0760eb20 --- /dev/null +++ b/assets/library/materials/metal/gold-brushed.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/gold-brushed", + "name": "Gold, brushed", + "category": "Metal", + "type": "metal_brushed", + "params": { + "base_color": [0.9277, 0.7966, 0.4057], + "base_metalness": 1.0, + "specular_color": [0.982, 1.0, 0.9713], + "specular_roughness": 0.3, + "specular_roughness_anisotropy": 0.8 + }, + "tags": ["pure-metal", "gold", "jewellery", "brushed", "opaque", "anisotropic"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Au/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0171 of the exact Fresnel reflectance at every angle. Roughness authored, brushed: directional grain; anisotropy 0.8 stretches the highlight across the grain.", + "authored": ["specular_roughness", "specular_roughness_anisotropy"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/gold-polished.json b/assets/library/materials/metal/gold-polished.json new file mode 100644 index 00000000..80ec64fb --- /dev/null +++ b/assets/library/materials/metal/gold-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/gold-polished", + "name": "Gold, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9277, 0.7966, 0.4057], + "base_metalness": 1.0, + "specular_color": [0.982, 1.0, 0.9713], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "gold", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Au/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0171 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/gold-satin.json b/assets/library/materials/metal/gold-satin.json new file mode 100644 index 00000000..1cae277c --- /dev/null +++ b/assets/library/materials/metal/gold-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/gold-satin", + "name": "Gold, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9277, 0.7966, 0.4057], + "base_metalness": 1.0, + "specular_color": [0.982, 1.0, 0.9713], + "specular_roughness": 0.25 + }, + "tags": ["pure-metal", "gold", "jewellery", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Au/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0171 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/gold-silver-au60-polished.json b/assets/library/materials/metal/gold-silver-au60-polished.json new file mode 100644 index 00000000..c3b50e53 --- /dev/null +++ b/assets/library/materials/metal/gold-silver-au60-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/gold-silver-au60-polished", + "name": "Gold-silver alloy (Au60 Ag40), polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.8975, 0.883, 0.5932], + "base_metalness": 1.0, + "specular_color": [0.9722, 0.9769, 1.0], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "gold", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "D. Rioux, S. Vallières, S. Besner, P. Muñoz, E. Mazur, M. Meunier. An analytic model for the dielectric function of Au, Ag, and their alloys. Adv. Opt. Mater. 2, 176-182 (2014) (See Supporting information for MATLAB model); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/Au-Ag/nk/Rioux-Au60Ag40.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0226 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/gold-silver-au80-polished.json b/assets/library/materials/metal/gold-silver-au80-polished.json new file mode 100644 index 00000000..c379890f --- /dev/null +++ b/assets/library/materials/metal/gold-silver-au80-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/gold-silver-au80-polished", + "name": "Gold-silver alloy (Au80 Ag20), polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9, 0.8511, 0.4819], + "base_metalness": 1.0, + "specular_color": [0.9749, 0.985, 1.0], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "gold", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "D. Rioux, S. Vallières, S. Besner, P. Muñoz, E. Mazur, M. Meunier. An analytic model for the dielectric function of Au, Ag, and their alloys. Adv. Opt. Mater. 2, 176-182 (2014) (See Supporting information for MATLAB model); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/Au-Ag/nk/Rioux-Au80Ag20.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.022 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/iridium-polished.json b/assets/library/materials/metal/iridium-polished.json new file mode 100644 index 00000000..629e14d9 --- /dev/null +++ b/assets/library/materials/metal/iridium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/iridium-polished", + "name": "Iridium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.7384, 0.7323, 0.7049], + "base_metalness": 1.0, + "specular_color": [0.7653, 0.7763, 0.8018], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "P. Schmitt, N. Felde, T. Doehring, M. Stollenwerk, I. Uschmann, K. Hanemann, M. Siegler, G. Klemm, N. Gratzke, A. Tuennermann, S. Schwinde, S. Schroeder, A. Szeghalmi. Optical, structural, and functional properties of highly reflective and stable iridium mirror coatings for infrared applications. Opt. Mater. Express 12, 545-559 (2022) (See supplementary materials. High-resolution data kindly provided by Paul Schmitt.); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ir/nk/Schmitt-MS.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0268 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/iron-as-cast.json b/assets/library/materials/metal/iron-as-cast.json new file mode 100644 index 00000000..14f51884 --- /dev/null +++ b/assets/library/materials/metal/iron-as-cast.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/iron-as-cast", + "name": "Iron, as cast", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5224, 0.5141, 0.4971], + "base_metalness": 1.0, + "specular_color": [0.7674, 0.7676, 0.797], + "specular_roughness": 0.55 + }, + "tags": ["pure-metal", "grey", "industrial", "rough", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Fe/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0175 of the exact Fresnel reflectance at every angle. Roughness authored, as cast or hot rolled: coarse surface, broad highlight.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/iron-bead-blasted.json b/assets/library/materials/metal/iron-bead-blasted.json new file mode 100644 index 00000000..935b9018 --- /dev/null +++ b/assets/library/materials/metal/iron-bead-blasted.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/iron-bead-blasted", + "name": "Iron, bead blasted", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5224, 0.5141, 0.4971], + "base_metalness": 1.0, + "specular_color": [0.7674, 0.7676, 0.797], + "specular_roughness": 0.45 + }, + "tags": ["pure-metal", "grey", "industrial", "rough", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Fe/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0175 of the exact Fresnel reflectance at every angle. Roughness authored, bead blasted: uniform micro-roughness, reflections blurred to a sheen.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/iron-polished.json b/assets/library/materials/metal/iron-polished.json new file mode 100644 index 00000000..45058005 --- /dev/null +++ b/assets/library/materials/metal/iron-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/iron-polished", + "name": "Iron, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5224, 0.5141, 0.4971], + "base_metalness": 1.0, + "specular_color": [0.7674, 0.7676, 0.797], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Fe/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0175 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/iron-satin.json b/assets/library/materials/metal/iron-satin.json new file mode 100644 index 00000000..ea3be260 --- /dev/null +++ b/assets/library/materials/metal/iron-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/iron-satin", + "name": "Iron, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5224, 0.5141, 0.4971], + "base_metalness": 1.0, + "specular_color": [0.7674, 0.7676, 0.797], + "specular_roughness": 0.25 + }, + "tags": ["pure-metal", "grey", "industrial", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Fe/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0175 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/lead-polished.json b/assets/library/materials/metal/lead-polished.json new file mode 100644 index 00000000..9d1852d4 --- /dev/null +++ b/assets/library/materials/metal/lead-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/lead-polished", + "name": "Lead, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6599, 0.661, 0.6886], + "base_metalness": 1.0, + "specular_color": [0.7787, 0.7795, 0.809], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "A. G. Mathewson and H. P. Myers. Absolute values of the optical constants of some pure metals. Phys. Scr. 4, 291-292 (1971); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Pb/nk/Mathewson-298K.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0139 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/magnesium-polished.json b/assets/library/materials/metal/magnesium-polished.json new file mode 100644 index 00000000..7afcc34d --- /dev/null +++ b/assets/library/materials/metal/magnesium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/magnesium-polished", + "name": "Magnesium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.8889, 0.8825, 0.8927], + "base_metalness": 1.0, + "specular_color": [0.9049, 0.9129, 0.9437], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "K. J. Palm, J. B. Murray, T. C. Narayan, J. N. Munday. Dynamic optical properties of metal hydrides. ACS Photonics 5, 4677-4686 (2018) (Numerical data kindly provided by Kevin Palm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Mg/nk/Palm.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0096 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/mercury-polished.json b/assets/library/materials/metal/mercury-polished.json new file mode 100644 index 00000000..580f0cbf --- /dev/null +++ b/assets/library/materials/metal/mercury-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/mercury-polished", + "name": "Mercury (liquid), polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.7806, 0.7796, 0.7786], + "base_metalness": 1.0, + "specular_color": [0.8304, 0.8497, 0.8948], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "T. Inagaki, E. T. Arakawa, and M. W. Williams. Optical properties of liquid mercury. Phys. Rev. B 23, 5246-5262 (1981); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Hg/nk/Inagaki.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0137 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/molybdenum-polished.json b/assets/library/materials/metal/molybdenum-polished.json new file mode 100644 index 00000000..6aacadb4 --- /dev/null +++ b/assets/library/materials/metal/molybdenum-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/molybdenum-polished", + "name": "Molybdenum, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5765, 0.5838, 0.5829], + "base_metalness": 1.0, + "specular_color": [0.7302, 0.7322, 0.7632], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "M. M. Kirillova, L. V. Nomerovannaya, M. M. Noskov. Optical properties of molybdenum single crystals , Sov. Phys. JETP 33, 1210-1214 (1971); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Mo/nk/Kirillova.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0282 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/nickel-brushed.json b/assets/library/materials/metal/nickel-brushed.json new file mode 100644 index 00000000..07e87378 --- /dev/null +++ b/assets/library/materials/metal/nickel-brushed.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/nickel-brushed", + "name": "Nickel, brushed", + "category": "Metal", + "type": "metal_brushed", + "params": { + "base_color": [0.6715, 0.6434, 0.5745], + "base_metalness": 1.0, + "specular_color": [0.8239, 0.8332, 0.8653], + "specular_roughness": 0.3, + "specular_roughness_anisotropy": 0.8 + }, + "tags": ["pure-metal", "silver", "industrial", "brushed", "opaque", "anisotropic"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ni/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0126 of the exact Fresnel reflectance at every angle. Roughness authored, brushed: directional grain; anisotropy 0.8 stretches the highlight across the grain.", + "authored": ["specular_roughness", "specular_roughness_anisotropy"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/nickel-polished.json b/assets/library/materials/metal/nickel-polished.json new file mode 100644 index 00000000..4c2086a4 --- /dev/null +++ b/assets/library/materials/metal/nickel-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/nickel-polished", + "name": "Nickel, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6715, 0.6434, 0.5745], + "base_metalness": 1.0, + "specular_color": [0.8239, 0.8332, 0.8653], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ni/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0126 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/nickel-satin.json b/assets/library/materials/metal/nickel-satin.json new file mode 100644 index 00000000..ad63f742 --- /dev/null +++ b/assets/library/materials/metal/nickel-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/nickel-satin", + "name": "Nickel, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6715, 0.6434, 0.5745], + "base_metalness": 1.0, + "specular_color": [0.8239, 0.8332, 0.8653], + "specular_roughness": 0.25 + }, + "tags": ["pure-metal", "silver", "industrial", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ni/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0126 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/niobium-polished.json b/assets/library/materials/metal/niobium-polished.json new file mode 100644 index 00000000..4b365782 --- /dev/null +++ b/assets/library/materials/metal/niobium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/niobium-polished", + "name": "Niobium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5027, 0.5066, 0.5017], + "base_metalness": 1.0, + "specular_color": [0.7706, 0.7692, 0.7904], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "J. H. Weaver, D. W. Lynch, C. G. Olson. Optical properties of niobium from 0.1 to 36.4 eV. Phys. Rev. B 7, 4311-4318 (1973) (Data points extracted from a figure); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Nb/nk/Weaver.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0173 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/palladium-polished.json b/assets/library/materials/metal/palladium-polished.json new file mode 100644 index 00000000..879d1757 --- /dev/null +++ b/assets/library/materials/metal/palladium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/palladium-polished", + "name": "Palladium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.7167, 0.6988, 0.6589], + "base_metalness": 1.0, + "specular_color": [0.8409, 0.8509, 0.8818], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Pd/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0134 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/platinum-polished.json b/assets/library/materials/metal/platinum-polished.json new file mode 100644 index 00000000..4839a35e --- /dev/null +++ b/assets/library/materials/metal/platinum-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/platinum-polished", + "name": "Platinum, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6598, 0.6398, 0.5915], + "base_metalness": 1.0, + "specular_color": [0.804, 0.8172, 0.8482], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "A. D. Rakić, A. B. Djurišic, J. M. Elazar, M. L. Majewski. Optical properties of metallic films for vertical-cavity optoelectronic devices. Appl. Opt. 37, 5271-5283 (1998) [Calculation script (Python)]; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Pt/nk/Rakic-LD.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0123 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/red-brass-polished.json b/assets/library/materials/metal/red-brass-polished.json new file mode 100644 index 00000000..92ce9418 --- /dev/null +++ b/assets/library/materials/metal/red-brass-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/red-brass-polished", + "name": "Red brass (Cu85 Zn15), polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.8218, 0.7241, 0.4623], + "base_metalness": 1.0, + "specular_color": [0.9809, 1.0, 1.0], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "orange", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "M. R. Querry. Optical constants, Contractor Report CRDC-CR-85034 (1985); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/Cu-Zn/nk/Querry-Cu85Zn15.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0421 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/rhodium-polished.json b/assets/library/materials/metal/rhodium-polished.json new file mode 100644 index 00000000..3f26924e --- /dev/null +++ b/assets/library/materials/metal/rhodium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/rhodium-polished", + "name": "Rhodium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.7834, 0.7665, 0.746], + "base_metalness": 1.0, + "specular_color": [0.8127, 0.8177, 0.834], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "J. H. Weaver, C. G. Olson, D. W. Lynch. Optical investigation of the electronic structure of bulk Rh and Ir. Phys. Rev. B 15, 4115 (1977); Handbook of Optical Constants of Solids, Edward D. Palik, ed. Academic Press, Boston, 1985 * Ref. 2 provides numerical values for the graphical data reported in Ref. 1; M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Rh/nk/Weaver.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0129 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/rose-gold-polished.json b/assets/library/materials/metal/rose-gold-polished.json new file mode 100644 index 00000000..e06c9299 --- /dev/null +++ b/assets/library/materials/metal/rose-gold-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/rose-gold-polished", + "name": "Rose gold, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9159, 0.758, 0.4866], + "base_metalness": 1.0, + "specular_color": [0.9843, 0.9849, 0.9668], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "pink", "polished", "jewellery", "opaque"], + "source": { + "kind": "authored", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024); K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Au/nk/McPeak.yml", "https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Cu/nk/McPeak.yml"], + "notes": "Authored approximation: no measured n and k for gold-copper alloys in the database. Colour and edge tint are a 55 to 45 blend of the measured gold and copper values, close to an 18 carat rose alloy's look. Roughness authored, polished finish.", + "authored": ["base_color", "specular_color", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/silver-brushed.json b/assets/library/materials/metal/silver-brushed.json new file mode 100644 index 00000000..ea99840d --- /dev/null +++ b/assets/library/materials/metal/silver-brushed.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/silver-brushed", + "name": "Silver, brushed", + "category": "Metal", + "type": "metal_brushed", + "params": { + "base_color": [0.9886, 0.9876, 0.9803], + "base_metalness": 1.0, + "specular_color": [0.9946, 0.9955, 0.9984], + "specular_roughness": 0.3, + "specular_roughness_anisotropy": 0.8 + }, + "tags": ["pure-metal", "silver", "jewellery", "brushed", "opaque", "anisotropic"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ag/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0016 of the exact Fresnel reflectance at every angle. Roughness authored, brushed: directional grain; anisotropy 0.8 stretches the highlight across the grain.", + "authored": ["specular_roughness", "specular_roughness_anisotropy"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/silver-polished.json b/assets/library/materials/metal/silver-polished.json new file mode 100644 index 00000000..ee90e691 --- /dev/null +++ b/assets/library/materials/metal/silver-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/silver-polished", + "name": "Silver, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9886, 0.9876, 0.9803], + "base_metalness": 1.0, + "specular_color": [0.9946, 0.9955, 0.9984], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "silver", "jewellery", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ag/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0016 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/silver-satin.json b/assets/library/materials/metal/silver-satin.json new file mode 100644 index 00000000..dfb51f87 --- /dev/null +++ b/assets/library/materials/metal/silver-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/silver-satin", + "name": "Silver, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.9886, 0.9876, 0.9803], + "base_metalness": 1.0, + "specular_color": [0.9946, 0.9955, 0.9984], + "specular_roughness": 0.25 + }, + "tags": ["pure-metal", "silver", "jewellery", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "K. M. McPeak, S. V. Jayanti, S. J. P. Kress, S. Meyer, S. Iotti, A. Rossinelli, D. J. Norris. Plasmonic films can easily be better: Rules and recipes. ACS Photonics 2, 326-333 (2015); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ag/nk/McPeak.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0016 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/stainless-steel-austenitic-polished.json b/assets/library/materials/metal/stainless-steel-austenitic-polished.json new file mode 100644 index 00000000..7b2897fd --- /dev/null +++ b/assets/library/materials/metal/stainless-steel-austenitic-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/stainless-steel-austenitic-polished", + "name": "Stainless steel, austenitic, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6557, 0.6405, 0.6043], + "base_metalness": 1.0, + "specular_color": [0.8039, 0.8214, 0.8632], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "silver", "kitchen", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "Björn Karlsson, Carl G. Ribbing. Optical constants and spectral selectivity of stainless steel and its oxides. J. Appl. Phys. 53, 6340-6346 (1982) (Data extracted from a figure); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/stainless%20steel/nk/Karlsson-austenitic.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0122 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/stainless-steel-bead-blasted.json b/assets/library/materials/metal/stainless-steel-bead-blasted.json new file mode 100644 index 00000000..b58dc4ff --- /dev/null +++ b/assets/library/materials/metal/stainless-steel-bead-blasted.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/stainless-steel-bead-blasted", + "name": "Stainless steel, bead blasted", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6557, 0.6405, 0.6043], + "base_metalness": 1.0, + "specular_color": [0.8039, 0.8214, 0.8632], + "specular_roughness": 0.45 + }, + "tags": ["alloy", "silver", "kitchen", "rough", "opaque"], + "source": { + "kind": "measured", + "reference": "Björn Karlsson, Carl G. Ribbing. Optical constants and spectral selectivity of stainless steel and its oxides. J. Appl. Phys. 53, 6340-6346 (1982) (Data extracted from a figure); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/stainless%20steel/nk/Karlsson-austenitic.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0122 of the exact Fresnel reflectance at every angle. Roughness authored, bead blasted: uniform micro-roughness, reflections blurred to a sheen.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/stainless-steel-brushed.json b/assets/library/materials/metal/stainless-steel-brushed.json new file mode 100644 index 00000000..89a2ec39 --- /dev/null +++ b/assets/library/materials/metal/stainless-steel-brushed.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/stainless-steel-brushed", + "name": "Stainless steel, brushed", + "category": "Metal", + "type": "metal_brushed", + "params": { + "base_color": [0.6557, 0.6405, 0.6043], + "base_metalness": 1.0, + "specular_color": [0.8039, 0.8214, 0.8632], + "specular_roughness": 0.3, + "specular_roughness_anisotropy": 0.8 + }, + "tags": ["alloy", "silver", "kitchen", "brushed", "opaque", "anisotropic"], + "source": { + "kind": "measured", + "reference": "Björn Karlsson, Carl G. Ribbing. Optical constants and spectral selectivity of stainless steel and its oxides. J. Appl. Phys. 53, 6340-6346 (1982) (Data extracted from a figure); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/stainless%20steel/nk/Karlsson-austenitic.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0122 of the exact Fresnel reflectance at every angle. Roughness authored, brushed: directional grain; anisotropy 0.8 stretches the highlight across the grain.", + "authored": ["specular_roughness", "specular_roughness_anisotropy"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/stainless-steel-ferritic-polished.json b/assets/library/materials/metal/stainless-steel-ferritic-polished.json new file mode 100644 index 00000000..0ca74868 --- /dev/null +++ b/assets/library/materials/metal/stainless-steel-ferritic-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/stainless-steel-ferritic-polished", + "name": "Stainless steel, ferritic, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5967, 0.5877, 0.5707], + "base_metalness": 1.0, + "specular_color": [0.829, 0.8451, 0.8945], + "specular_roughness": 0.04 + }, + "tags": ["alloy", "silver", "kitchen", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "Björn Karlsson, Carl G. Ribbing. Optical constants and spectral selectivity of stainless steel and its oxides. J. Appl. Phys. 53, 6340-6346 (1982) (Data extracted from a figure); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/stainless%20steel/nk/Karlsson-ferritic.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0103 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/stainless-steel-mirror.json b/assets/library/materials/metal/stainless-steel-mirror.json new file mode 100644 index 00000000..a7afbe6a --- /dev/null +++ b/assets/library/materials/metal/stainless-steel-mirror.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/stainless-steel-mirror", + "name": "Stainless steel, mirror", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6557, 0.6405, 0.6043], + "base_metalness": 1.0, + "specular_color": [0.8039, 0.8214, 0.8632], + "specular_roughness": 0.02 + }, + "tags": ["alloy", "silver", "kitchen", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "Björn Karlsson, Carl G. Ribbing. Optical constants and spectral selectivity of stainless steel and its oxides. J. Appl. Phys. 53, 6340-6346 (1982) (Data extracted from a figure); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/stainless%20steel/nk/Karlsson-austenitic.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0122 of the exact Fresnel reflectance at every angle. Roughness authored, mirror finish: the sharpest highlight a real buffed part keeps.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/stainless-steel-satin.json b/assets/library/materials/metal/stainless-steel-satin.json new file mode 100644 index 00000000..b59352c0 --- /dev/null +++ b/assets/library/materials/metal/stainless-steel-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/stainless-steel-satin", + "name": "Stainless steel, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6557, 0.6405, 0.6043], + "base_metalness": 1.0, + "specular_color": [0.8039, 0.8214, 0.8632], + "specular_roughness": 0.25 + }, + "tags": ["alloy", "silver", "kitchen", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "Björn Karlsson, Carl G. Ribbing. Optical constants and spectral selectivity of stainless steel and its oxides. J. Appl. Phys. 53, 6340-6346 (1982) (Data extracted from a figure); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/alloys/stainless%20steel/nk/Karlsson-austenitic.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0122 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-anodised-blue.json b/assets/library/materials/metal/titanium-anodised-blue.json new file mode 100644 index 00000000..6594d727 --- /dev/null +++ b/assets/library/materials/metal/titanium-anodised-blue.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-anodised-blue", + "name": "Titanium, anodised blue", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.12, + "thin_film_weight": 1.0, + "thin_film_thickness": 0.05, + "thin_film_ior": 2.449 + }, + "tags": ["anodised", "blue", "thin-film", "polished", "jewellery"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024); A. Jolivet et al. Structural, optical, and electrical properties of TiO2 thin films deposited by ALD. Appl. Surf. Sci. 608, 155214 (2023)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml", "https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/TiO2/nk/Jolivet-amorphous.yml"], + "notes": "Titanium coloured by an anodic oxide film: interference colour, no dye. The film thickness 0.05 um was chosen by computing the reflectance of an amorphous TiO2 film (n 2.449 at 550 nm) on measured titanium with the Airy formula for thicknesses 0 to 0.155 um and picking the one whose colour reads as blue. Needs the thin-film lobe; without it the preset renders as plain titanium. Roughness authored.", + "authored": ["specular_roughness", "thin_film_thickness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-anodised-bronze.json b/assets/library/materials/metal/titanium-anodised-bronze.json new file mode 100644 index 00000000..9bc3a815 --- /dev/null +++ b/assets/library/materials/metal/titanium-anodised-bronze.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-anodised-bronze", + "name": "Titanium, anodised bronze", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.12, + "thin_film_weight": 1.0, + "thin_film_thickness": 0.025, + "thin_film_ior": 2.449 + }, + "tags": ["anodised", "brown", "thin-film", "polished", "jewellery"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024); A. Jolivet et al. Structural, optical, and electrical properties of TiO2 thin films deposited by ALD. Appl. Surf. Sci. 608, 155214 (2023)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml", "https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/TiO2/nk/Jolivet-amorphous.yml"], + "notes": "Titanium coloured by an anodic oxide film: interference colour, no dye. The film thickness 0.025 um was chosen by computing the reflectance of an amorphous TiO2 film (n 2.449 at 550 nm) on measured titanium with the Airy formula for thicknesses 0 to 0.155 um and picking the one whose colour reads as bronze. Needs the thin-film lobe; without it the preset renders as plain titanium. Roughness authored.", + "authored": ["specular_roughness", "thin_film_thickness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-anodised-gold.json b/assets/library/materials/metal/titanium-anodised-gold.json new file mode 100644 index 00000000..2e776d2f --- /dev/null +++ b/assets/library/materials/metal/titanium-anodised-gold.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-anodised-gold", + "name": "Titanium, anodised gold", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.12, + "thin_film_weight": 1.0, + "thin_film_thickness": 0.115, + "thin_film_ior": 2.449 + }, + "tags": ["anodised", "gold", "thin-film", "polished", "jewellery"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024); A. Jolivet et al. Structural, optical, and electrical properties of TiO2 thin films deposited by ALD. Appl. Surf. Sci. 608, 155214 (2023)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml", "https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/TiO2/nk/Jolivet-amorphous.yml"], + "notes": "Titanium coloured by an anodic oxide film: interference colour, no dye. The film thickness 0.115 um was chosen by computing the reflectance of an amorphous TiO2 film (n 2.449 at 550 nm) on measured titanium with the Airy formula for thicknesses 0 to 0.155 um and picking the one whose colour reads as gold. Needs the thin-film lobe; without it the preset renders as plain titanium. Roughness authored.", + "authored": ["specular_roughness", "thin_film_thickness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-anodised-light-blue.json b/assets/library/materials/metal/titanium-anodised-light-blue.json new file mode 100644 index 00000000..cc2d43e4 --- /dev/null +++ b/assets/library/materials/metal/titanium-anodised-light-blue.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-anodised-light-blue", + "name": "Titanium, anodised light blue", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.12, + "thin_film_weight": 1.0, + "thin_film_thickness": 0.065, + "thin_film_ior": 2.449 + }, + "tags": ["anodised", "blue", "thin-film", "polished", "jewellery"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024); A. Jolivet et al. Structural, optical, and electrical properties of TiO2 thin films deposited by ALD. Appl. Surf. Sci. 608, 155214 (2023)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml", "https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/TiO2/nk/Jolivet-amorphous.yml"], + "notes": "Titanium coloured by an anodic oxide film: interference colour, no dye. The film thickness 0.065 um was chosen by computing the reflectance of an amorphous TiO2 film (n 2.449 at 550 nm) on measured titanium with the Airy formula for thicknesses 0 to 0.155 um and picking the one whose colour reads as light blue. Needs the thin-film lobe; without it the preset renders as plain titanium. Roughness authored.", + "authored": ["specular_roughness", "thin_film_thickness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-anodised-magenta.json b/assets/library/materials/metal/titanium-anodised-magenta.json new file mode 100644 index 00000000..453e3af8 --- /dev/null +++ b/assets/library/materials/metal/titanium-anodised-magenta.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-anodised-magenta", + "name": "Titanium, anodised magenta", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.12, + "thin_film_weight": 1.0, + "thin_film_thickness": 0.14, + "thin_film_ior": 2.449 + }, + "tags": ["anodised", "pink", "thin-film", "polished", "jewellery"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024); A. Jolivet et al. Structural, optical, and electrical properties of TiO2 thin films deposited by ALD. Appl. Surf. Sci. 608, 155214 (2023)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml", "https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/TiO2/nk/Jolivet-amorphous.yml"], + "notes": "Titanium coloured by an anodic oxide film: interference colour, no dye. The film thickness 0.14 um was chosen by computing the reflectance of an amorphous TiO2 film (n 2.449 at 550 nm) on measured titanium with the Airy formula for thicknesses 0 to 0.155 um and picking the one whose colour reads as magenta. Needs the thin-film lobe; without it the preset renders as plain titanium. Roughness authored.", + "authored": ["specular_roughness", "thin_film_thickness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-anodised-purple.json b/assets/library/materials/metal/titanium-anodised-purple.json new file mode 100644 index 00000000..69fb3af8 --- /dev/null +++ b/assets/library/materials/metal/titanium-anodised-purple.json @@ -0,0 +1,26 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-anodised-purple", + "name": "Titanium, anodised purple", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.12, + "thin_film_weight": 1.0, + "thin_film_thickness": 0.04, + "thin_film_ior": 2.449 + }, + "tags": ["anodised", "purple", "thin-film", "polished", "jewellery"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024); A. Jolivet et al. Structural, optical, and electrical properties of TiO2 thin films deposited by ALD. Appl. Surf. Sci. 608, 155214 (2023)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml", "https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/TiO2/nk/Jolivet-amorphous.yml"], + "notes": "Titanium coloured by an anodic oxide film: interference colour, no dye. The film thickness 0.04 um was chosen by computing the reflectance of an amorphous TiO2 film (n 2.449 at 550 nm) on measured titanium with the Airy formula for thicknesses 0 to 0.155 um and picking the one whose colour reads as purple. Needs the thin-film lobe; without it the preset renders as plain titanium. Roughness authored.", + "authored": ["specular_roughness", "thin_film_thickness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-bead-blasted.json b/assets/library/materials/metal/titanium-bead-blasted.json new file mode 100644 index 00000000..d55ceae0 --- /dev/null +++ b/assets/library/materials/metal/titanium-bead-blasted.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-bead-blasted", + "name": "Titanium, bead blasted", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.45 + }, + "tags": ["pure-metal", "grey", "industrial", "rough", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0134 of the exact Fresnel reflectance at every angle. Roughness authored, bead blasted: uniform micro-roughness, reflections blurred to a sheen.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-brushed.json b/assets/library/materials/metal/titanium-brushed.json new file mode 100644 index 00000000..b1c90d0e --- /dev/null +++ b/assets/library/materials/metal/titanium-brushed.json @@ -0,0 +1,24 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-brushed", + "name": "Titanium, brushed", + "category": "Metal", + "type": "metal_brushed", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.3, + "specular_roughness_anisotropy": 0.8 + }, + "tags": ["pure-metal", "grey", "industrial", "brushed", "opaque", "anisotropic"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0134 of the exact Fresnel reflectance at every angle. Roughness authored, brushed: directional grain; anisotropy 0.8 stretches the highlight across the grain.", + "authored": ["specular_roughness", "specular_roughness_anisotropy"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-nitride-polished.json b/assets/library/materials/metal/titanium-nitride-polished.json new file mode 100644 index 00000000..d2222ff8 --- /dev/null +++ b/assets/library/materials/metal/titanium-nitride-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-nitride-polished", + "name": "Titanium nitride coating, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.544, 0.4691, 0.2656], + "base_metalness": 1.0, + "specular_color": [0.9306, 0.9788, 1.0], + "specular_roughness": 0.04 + }, + "tags": ["coating", "gold", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "J. Pflüger, J. Fink. Determination of optical constants by high-energy, electron-energy-loss spectroscopy (EELS), in Handbook of optical constants of solids II, Edward D. Palik, ed. Academic Press, 1991. pp. 293-310; J. Pflüger, J. Fink, W. Weber, K. P. Bohnen, G. Crecelius. Dielectric properties of TiCx, TiNx, VCx, and VNx from 1.5 to 40 eV determined by electron-energy-loss spectroscopy. Phys. Rev. B 30, 1155-1163 (1984); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/TiN/nk/Pfluger.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0405 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-polished.json b/assets/library/materials/metal/titanium-polished.json new file mode 100644 index 00000000..42c95ee4 --- /dev/null +++ b/assets/library/materials/metal/titanium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-polished", + "name": "Titanium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0134 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/titanium-satin.json b/assets/library/materials/metal/titanium-satin.json new file mode 100644 index 00000000..60592955 --- /dev/null +++ b/assets/library/materials/metal/titanium-satin.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/titanium-satin", + "name": "Titanium, satin", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.6017, 0.5816, 0.5481], + "base_metalness": 1.0, + "specular_color": [0.7783, 0.7893, 0.8161], + "specular_roughness": 0.25 + }, + "tags": ["pure-metal", "grey", "industrial", "satin", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Ti/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0134 of the exact Fresnel reflectance at every angle. Roughness authored, satin: fine abrasive finish, soft highlight, reflections still recognisable.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/tungsten-polished.json b/assets/library/materials/metal/tungsten-polished.json new file mode 100644 index 00000000..2a58092e --- /dev/null +++ b/assets/library/materials/metal/tungsten-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/tungsten-polished", + "name": "Tungsten, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.5069, 0.4973, 0.4716], + "base_metalness": 1.0, + "specular_color": [0.7237, 0.7287, 0.742], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "J. H. Weaver, C. G. Olson, D. W. Lynch. Optical properties of crystalline tungsten. Phys. Rev. B 12, 1293-1297 (1975) (Data points extracted from a figure); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/W/nk/Weaver.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0305 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/vanadium-polished.json b/assets/library/materials/metal/vanadium-polished.json new file mode 100644 index 00000000..f93f2642 --- /dev/null +++ b/assets/library/materials/metal/vanadium-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/vanadium-polished", + "name": "Vanadium, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.527, 0.5343, 0.5623], + "base_metalness": 1.0, + "specular_color": [0.7183, 0.7028, 0.7167], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "P. B. Johnson and R. W. Christy. Optical constants of transition metals: Ti, V, Cr, Mn, Fe, Co, Ni, and Pd. Phys. Rev. B 9, 5056-5070 (1974); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/V/nk/Johnson.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0384 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/metal/zinc-polished.json b/assets/library/materials/metal/zinc-polished.json new file mode 100644 index 00000000..068613a7 --- /dev/null +++ b/assets/library/materials/metal/zinc-polished.json @@ -0,0 +1,23 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "metal/zinc-polished", + "name": "Zinc, polished", + "category": "Metal", + "type": "metal", + "params": { + "base_color": [0.8229, 0.8419, 0.8612], + "base_metalness": 1.0, + "specular_color": [0.7934, 0.8294, 0.8869], + "specular_roughness": 0.04 + }, + "tags": ["pure-metal", "grey", "industrial", "polished", "opaque"], + "source": { + "kind": "measured", + "reference": "W. S. M. Werner, K. Glantschnig, C. Ambrosch-Draxl. Optical constants and inelastic electron-scattering data for 17 elemental metals. J. Phys Chem Ref. Data 38, 1013-1092 (2009); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/Zn/nk/Werner-DFT.yml"], + "notes": "base_color is the normal-incidence reflectance and specular_color the F82 edge tint, both computed from the measured n and k (380-780 nm, CIE 1931 2 degree observer, D65, ACEScg); the F82 fit stays within 0.0352 of the exact Fresnel reflectance at every angle. Roughness authored, polished: a near-mirror reflection with a slight blur, GGX alpha 0.0016.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/gloss-black.json b/assets/library/materials/paint/gloss-black.json new file mode 100644 index 00000000..0f005adf --- /dev/null +++ b/assets/library/materials/paint/gloss-black.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/gloss-black", + "name": "Gloss enamel, black", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.004, 0.004, 0.004], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "gloss", "coat", "black", "opaque", "automotive"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #0d0d0d. Gloss enamel: pigment layer under a smooth binder film, coat roughness 0.03; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/gloss-blue.json b/assets/library/materials/paint/gloss-blue.json new file mode 100644 index 00000000..aab90e03 --- /dev/null +++ b/assets/library/materials/paint/gloss-blue.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/gloss-blue", + "name": "Gloss enamel, blue", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.038, 0.0503, 0.2633], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "gloss", "coat", "blue", "opaque", "automotive"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #1c3f94. Gloss enamel: pigment layer under a smooth binder film, coat roughness 0.03; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/gloss-green.json b/assets/library/materials/paint/gloss-green.json new file mode 100644 index 00000000..2652bfbe --- /dev/null +++ b/assets/library/materials/paint/gloss-green.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/gloss-green", + "name": "Gloss enamel, green", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.0603, 0.1363, 0.0532], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "gloss", "coat", "green", "opaque", "automotive"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #1f6b3a. Gloss enamel: pigment layer under a smooth binder film, coat roughness 0.03; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/gloss-orange.json b/assets/library/materials/paint/gloss-orange.json new file mode 100644 index 00000000..5bdc7724 --- /dev/null +++ b/assets/library/materials/paint/gloss-orange.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/gloss-orange", + "name": "Gloss enamel, orange", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.5288, 0.1482, 0.0308], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "gloss", "coat", "orange", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #e8590c. Gloss enamel: pigment layer under a smooth binder film, coat roughness 0.03; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/gloss-red.json b/assets/library/materials/paint/gloss-red.json new file mode 100644 index 00000000..fc44240d --- /dev/null +++ b/assets/library/materials/paint/gloss-red.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/gloss-red", + "name": "Gloss enamel, red", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.2859, 0.0381, 0.0197], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "gloss", "coat", "red", "opaque", "automotive"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #b5121b. Gloss enamel: pigment layer under a smooth binder film, coat roughness 0.03; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/gloss-white.json b/assets/library/materials/paint/gloss-white.json new file mode 100644 index 00000000..2a1b0a34 --- /dev/null +++ b/assets/library/materials/paint/gloss-white.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/gloss-white", + "name": "Gloss enamel, white", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.8535, 0.8546, 0.827], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "gloss", "coat", "white", "opaque", "furniture"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #eeeeea. Gloss enamel: pigment layer under a smooth binder film, coat roughness 0.03; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/gloss-yellow.json b/assets/library/materials/paint/gloss-yellow.json new file mode 100644 index 00000000..0fbeb5c2 --- /dev/null +++ b/assets/library/materials/paint/gloss-yellow.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/gloss-yellow", + "name": "Gloss enamel, yellow", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.7472, 0.5699, 0.0793], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.03, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "gloss", "coat", "yellow", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #f5c400. Gloss enamel: pigment layer under a smooth binder film, coat roughness 0.03; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/matte-black.json b/assets/library/materials/paint/matte-black.json new file mode 100644 index 00000000..0ffaca0d --- /dev/null +++ b/assets/library/materials/paint/matte-black.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/matte-black", + "name": "Matte paint, black", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.006, 0.006, 0.006], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.7, + "specular_ior": 1.5, + "coat_weight": 0.0 + }, + "tags": ["paint", "matte", "black", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #121212. Flat (matte) paint: pigment-rich surface with no binder film on top, specular roughness 0.7 and a rough diffuse lobe; coat off. specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/matte-sage.json b/assets/library/materials/paint/matte-sage.json new file mode 100644 index 00000000..02e5208f --- /dev/null +++ b/assets/library/materials/paint/matte-sage.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/matte-sage", + "name": "Matte paint, sage green", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.3429, 0.3849, 0.2672], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.7, + "specular_ior": 1.5, + "coat_weight": 0.0 + }, + "tags": ["paint", "matte", "green", "opaque", "architectural"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #9aa889. Flat (matte) paint: pigment-rich surface with no binder film on top, specular roughness 0.7 and a rough diffuse lobe; coat off. specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/matte-terracotta.json b/assets/library/materials/paint/matte-terracotta.json new file mode 100644 index 00000000..bc91d682 --- /dev/null +++ b/assets/library/materials/paint/matte-terracotta.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/matte-terracotta", + "name": "Matte paint, terracotta", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.3254, 0.1403, 0.0656], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.7, + "specular_ior": 1.5, + "coat_weight": 0.0 + }, + "tags": ["paint", "matte", "orange", "opaque", "architectural"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #b5603f. Flat (matte) paint: pigment-rich surface with no binder film on top, specular roughness 0.7 and a rough diffuse lobe; coat off. specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/matte-white.json b/assets/library/materials/paint/matte-white.json new file mode 100644 index 00000000..1c6d1a07 --- /dev/null +++ b/assets/library/materials/paint/matte-white.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/matte-white", + "name": "Matte paint, white", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.8585, 0.8551, 0.8271], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.7, + "specular_ior": 1.5, + "coat_weight": 0.0 + }, + "tags": ["paint", "matte", "white", "opaque", "architectural"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #efeeea. Flat (matte) paint: pigment-rich surface with no binder film on top, specular roughness 0.7 and a rough diffuse lobe; coat off. specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/metallic-black.json b/assets/library/materials/paint/metallic-black.json new file mode 100644 index 00000000..30fb766c --- /dev/null +++ b/assets/library/materials/paint/metallic-black.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/metallic-black", + "name": "Metallic paint, black", + "category": "Paint", + "type": "paint_metallic", + "params": { + "base_color": [0.0106, 0.0109, 0.0121], + "base_metalness": 0.6, + "specular_roughness": 0.35, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "coat", "black", "gloss", "automotive", "needs-graph"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Metallic automotive paint: aluminium flakes in a tinted basecoat under a clear coat. base_color authored as sRGB #1a1b1d; base_metalness 0.6 authored to mix flake reflection with pigment; flake spread as specular roughness 0.35; clear coat roughness 0.02; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). The sparkle needs the type's flakes graph.", + "authored": ["base_color", "base_metalness", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/metallic-blue.json b/assets/library/materials/paint/metallic-blue.json new file mode 100644 index 00000000..a7d4df66 --- /dev/null +++ b/assets/library/materials/paint/metallic-blue.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/metallic-blue", + "name": "Metallic paint, blue", + "category": "Paint", + "type": "paint_metallic", + "params": { + "base_color": [0.0325, 0.0449, 0.1745], + "base_metalness": 0.7, + "specular_roughness": 0.35, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "coat", "blue", "gloss", "automotive", "needs-graph"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Metallic automotive paint: aluminium flakes in a tinted basecoat under a clear coat. base_color authored as sRGB #1e3c7a; base_metalness 0.7 authored to mix flake reflection with pigment; flake spread as specular roughness 0.35; clear coat roughness 0.02; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). The sparkle needs the type's flakes graph.", + "authored": ["base_color", "base_metalness", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/metallic-champagne.json b/assets/library/materials/paint/metallic-champagne.json new file mode 100644 index 00000000..0bd42d10 --- /dev/null +++ b/assets/library/materials/paint/metallic-champagne.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/metallic-champagne", + "name": "Metallic paint, champagne", + "category": "Paint", + "type": "paint_metallic", + "params": { + "base_color": [0.5255, 0.4628, 0.2902], + "base_metalness": 0.7, + "specular_roughness": 0.35, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "coat", "gold", "gloss", "automotive", "needs-graph"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Metallic automotive paint: aluminium flakes in a tinted basecoat under a clear coat. base_color authored as sRGB #c9b48c; base_metalness 0.7 authored to mix flake reflection with pigment; flake spread as specular roughness 0.35; clear coat roughness 0.02; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). The sparkle needs the type's flakes graph.", + "authored": ["base_color", "base_metalness", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/metallic-gunmetal.json b/assets/library/materials/paint/metallic-gunmetal.json new file mode 100644 index 00000000..91f8b51e --- /dev/null +++ b/assets/library/materials/paint/metallic-gunmetal.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/metallic-gunmetal", + "name": "Metallic paint, gunmetal", + "category": "Paint", + "type": "paint_metallic", + "params": { + "base_color": [0.0721, 0.0758, 0.0869], + "base_metalness": 0.7, + "specular_roughness": 0.35, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "coat", "grey", "gloss", "automotive", "needs-graph"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Metallic automotive paint: aluminium flakes in a tinted basecoat under a clear coat. base_color authored as sRGB #4a4e54; base_metalness 0.7 authored to mix flake reflection with pigment; flake spread as specular roughness 0.35; clear coat roughness 0.02; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). The sparkle needs the type's flakes graph.", + "authored": ["base_color", "base_metalness", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/metallic-red.json b/assets/library/materials/paint/metallic-red.json new file mode 100644 index 00000000..a449be45 --- /dev/null +++ b/assets/library/materials/paint/metallic-red.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/metallic-red", + "name": "Metallic paint, red", + "category": "Paint", + "type": "paint_metallic", + "params": { + "base_color": [0.2139, 0.0337, 0.0221], + "base_metalness": 0.7, + "specular_roughness": 0.35, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "coat", "red", "gloss", "automotive", "needs-graph"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Metallic automotive paint: aluminium flakes in a tinted basecoat under a clear coat. base_color authored as sRGB #9e1a22; base_metalness 0.7 authored to mix flake reflection with pigment; flake spread as specular roughness 0.35; clear coat roughness 0.02; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). The sparkle needs the type's flakes graph.", + "authored": ["base_color", "base_metalness", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/metallic-silver.json b/assets/library/materials/paint/metallic-silver.json new file mode 100644 index 00000000..e7da259a --- /dev/null +++ b/assets/library/materials/paint/metallic-silver.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/metallic-silver", + "name": "Metallic paint, silver", + "category": "Paint", + "type": "paint_metallic", + "params": { + "base_color": [0.4896, 0.5016, 0.5235], + "base_metalness": 0.8, + "specular_roughness": 0.35, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "coat", "silver", "gloss", "automotive", "needs-graph"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Metallic automotive paint: aluminium flakes in a tinted basecoat under a clear coat. base_color authored as sRGB #b8bcc0; base_metalness 0.8 authored to mix flake reflection with pigment; flake spread as specular roughness 0.35; clear coat roughness 0.02; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). The sparkle needs the type's flakes graph.", + "authored": ["base_color", "base_metalness", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/pearl-blue.json b/assets/library/materials/paint/pearl-blue.json new file mode 100644 index 00000000..1b997dab --- /dev/null +++ b/assets/library/materials/paint/pearl-blue.json @@ -0,0 +1,30 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/pearl-blue", + "name": "Pearl paint, blue", + "category": "Paint", + "type": "paint_metallic", + "params": { + "base_color": [0.0524, 0.0715, 0.2365], + "base_metalness": 0.3, + "specular_roughness": 0.3, + "specular_ior": 1.5, + "thin_film_weight": 0.8, + "thin_film_thickness": 0.065, + "thin_film_ior": 2.4, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "coat", "thin-film", "blue", "gloss", "automotive", "needs-graph"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Pearlescent paint: titanium-dioxide coated mica platelets whose interference shifts the colour with angle. base_color authored as sRGB #2c4c8c; thin film ior 2.4 authored (TiO2), thickness 0.065 um authored for the blue interference hue, weight 0.8 so some pigment shows through; base_metalness 0.3 authored for the platelets' mirror-like sheen; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49).", + "authored": ["base_color", "base_metalness", "specular_roughness", "specular_ior", "thin_film_weight", "thin_film_thickness", "thin_film_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/pearl-white.json b/assets/library/materials/paint/pearl-white.json new file mode 100644 index 00000000..28325380 --- /dev/null +++ b/assets/library/materials/paint/pearl-white.json @@ -0,0 +1,30 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/pearl-white", + "name": "Pearl paint, white", + "category": "Paint", + "type": "paint_metallic", + "params": { + "base_color": [0.8706, 0.8636, 0.8146], + "base_metalness": 0.3, + "specular_roughness": 0.3, + "specular_ior": 1.5, + "thin_film_weight": 0.8, + "thin_film_thickness": 0.08, + "thin_film_ior": 2.4, + "coat_weight": 1.0, + "coat_roughness": 0.02, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "coat", "thin-film", "white", "gloss", "automotive", "needs-graph"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Pearlescent paint: titanium-dioxide coated mica platelets whose interference shifts the colour with angle. base_color authored as sRGB #f1efe8; thin film ior 2.4 authored (TiO2), thickness 0.08 um authored for the white interference hue, weight 0.8 so some pigment shows through; base_metalness 0.3 authored for the platelets' mirror-like sheen; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49).", + "authored": ["base_color", "base_metalness", "specular_roughness", "specular_ior", "thin_film_weight", "thin_film_thickness", "thin_film_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/satin-blue.json b/assets/library/materials/paint/satin-blue.json new file mode 100644 index 00000000..3216aca5 --- /dev/null +++ b/assets/library/materials/paint/satin-blue.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/satin-blue", + "name": "Satin paint, blue", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.0768, 0.1113, 0.2345], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.25, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "satin", "coat", "blue", "opaque", "furniture"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #3a5f8a. Satin (eggshell) paint: the binder film is micro-rough, coat roughness 0.25; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/satin-grey.json b/assets/library/materials/paint/satin-grey.json new file mode 100644 index 00000000..7de85824 --- /dev/null +++ b/assets/library/materials/paint/satin-grey.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/satin-grey", + "name": "Satin paint, grey", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.21, 0.2153, 0.2286], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.25, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "satin", "coat", "grey", "opaque", "architectural"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #7d8084. Satin (eggshell) paint: the binder film is micro-rough, coat roughness 0.25; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/paint/satin-white.json b/assets/library/materials/paint/satin-white.json new file mode 100644 index 00000000..1aa9bff6 --- /dev/null +++ b/assets/library/materials/paint/satin-white.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "paint/satin-white", + "name": "Satin paint, white", + "category": "Paint", + "type": "paint", + "params": { + "base_color": [0.8338, 0.8308, 0.7966], + "base_metalness": 0.0, + "specular_roughness": 0.4, + "specular_ior": 1.5, + "coat_weight": 1.0, + "coat_roughness": 0.25, + "coat_ior": 1.5, + "coat_color": [1.0, 1.0, 1.0] + }, + "tags": ["paint", "satin", "coat", "white", "opaque", "architectural"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "base_color authored as sRGB #ecebe6. Satin (eggshell) paint: the binder film is micro-rough, coat roughness 0.25; coat_ior 1.5 authored, typical of acrylic and polyurethane clear binders (cured acrylic is about 1.49). specular_ior 1.5 of the pigment layer authored (binder-dominated).", + "authored": ["base_color", "specular_roughness", "specular_ior", "coat_roughness", "coat_ior", "coat_color"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-black-gloss.json b/assets/library/materials/plastic/abs-black-gloss.json new file mode 100644 index 00000000..93d99588 --- /dev/null +++ b/assets/library/materials/plastic/abs-black-gloss.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-black-gloss", + "name": "ABS, black gloss", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.0052, 0.0052, 0.0052], + "base_metalness": 0.0, + "specular_roughness": 0.08, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "gloss", "black", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #101010. Roughness 0.08 authored: polished mould, sharp highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-black-matte.json b/assets/library/materials/plastic/abs-black-matte.json new file mode 100644 index 00000000..31ae3ad9 --- /dev/null +++ b/assets/library/materials/plastic/abs-black-matte.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-black-matte", + "name": "ABS, black matte", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.008, 0.008, 0.008], + "base_metalness": 0.0, + "specular_roughness": 0.55, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "matte", "black", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #161616. Roughness 0.55 authored: fine spark-eroded mould texture, broad highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-black-satin.json b/assets/library/materials/plastic/abs-black-satin.json new file mode 100644 index 00000000..5cb6b138 --- /dev/null +++ b/assets/library/materials/plastic/abs-black-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-black-satin", + "name": "ABS, black satin", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.007, 0.007, 0.007], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "satin", "black", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #141414. Roughness 0.3 authored: lightly textured mould, soft highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-blue-gloss.json b/assets/library/materials/plastic/abs-blue-gloss.json new file mode 100644 index 00000000..459e5277 --- /dev/null +++ b/assets/library/materials/plastic/abs-blue-gloss.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-blue-gloss", + "name": "ABS, blue gloss", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.0498, 0.077, 0.298], + "base_metalness": 0.0, + "specular_roughness": 0.08, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "gloss", "blue", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #1d4f9c. Roughness 0.08 authored: polished mould, sharp highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-grey-gloss.json b/assets/library/materials/plastic/abs-grey-gloss.json new file mode 100644 index 00000000..f60d5613 --- /dev/null +++ b/assets/library/materials/plastic/abs-grey-gloss.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-grey-gloss", + "name": "ABS, grey gloss", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.2577, 0.2618, 0.2693], + "base_metalness": 0.0, + "specular_roughness": 0.08, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "gloss", "grey", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #8a8c8e. Roughness 0.08 authored: polished mould, sharp highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-grey-matte.json b/assets/library/materials/plastic/abs-grey-matte.json new file mode 100644 index 00000000..8db26140 --- /dev/null +++ b/assets/library/materials/plastic/abs-grey-matte.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-grey-matte", + "name": "ABS, grey matte", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.1587, 0.1617, 0.1701], + "base_metalness": 0.0, + "specular_roughness": 0.55, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "matte", "grey", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #6e7073. Roughness 0.55 authored: fine spark-eroded mould texture, broad highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-red-gloss.json b/assets/library/materials/plastic/abs-red-gloss.json new file mode 100644 index 00000000..f91d8dc4 --- /dev/null +++ b/assets/library/materials/plastic/abs-red-gloss.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-red-gloss", + "name": "ABS, red gloss", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.3417, 0.0463, 0.0224], + "base_metalness": 0.0, + "specular_roughness": 0.08, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "gloss", "red", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #c4161c. Roughness 0.08 authored: polished mould, sharp highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-white-gloss.json b/assets/library/materials/plastic/abs-white-gloss.json new file mode 100644 index 00000000..8e5399fd --- /dev/null +++ b/assets/library/materials/plastic/abs-white-gloss.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-white-gloss", + "name": "ABS, white gloss", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.8535, 0.8546, 0.827], + "base_metalness": 0.0, + "specular_roughness": 0.08, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "gloss", "white", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #eeeeea. Roughness 0.08 authored: polished mould, sharp highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/abs-yellow-gloss.json b/assets/library/materials/plastic/abs-yellow-gloss.json new file mode 100644 index 00000000..749752d6 --- /dev/null +++ b/assets/library/materials/plastic/abs-yellow-gloss.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/abs-yellow-gloss", + "name": "ABS, yellow gloss", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.7275, 0.5567, 0.0774], + "base_metalness": 0.0, + "specular_roughness": 0.08, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "gloss", "yellow", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #f2c200. Roughness 0.08 authored: polished mould, sharp highlight. specular_ior 1.53: authored typical value: ABS sits between its acrylonitrile-butadiene phases (about 1.51 to 1.52) and polystyrene (1.59 measured); grades are quoted around 1.53 to 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/acetal-black-satin.json b/assets/library/materials/plastic/acetal-black-satin.json new file mode 100644 index 00000000..965e5321 --- /dev/null +++ b/assets/library/materials/plastic/acetal-black-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/acetal-black-satin", + "name": "Acetal, black satin", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.0075, 0.0075, 0.0075], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.48, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "satin", "black", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #151515. Roughness 0.3 authored: lightly textured mould, soft highlight. specular_ior 1.48: authored typical value for polyoxymethylene (quoted 1.48).", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/acetal-white-satin.json b/assets/library/materials/plastic/acetal-white-satin.json new file mode 100644 index 00000000..163dd691 --- /dev/null +++ b/assets/library/materials/plastic/acetal-white-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/acetal-white-satin", + "name": "Acetal, white satin", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.8749, 0.8715, 0.8432], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.48, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "satin", "white", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #f1f0ec. Roughness 0.3 authored: lightly textured mould, soft highlight. specular_ior 1.48: authored typical value for polyoxymethylene (quoted 1.48).", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/acrylic-amber.json b/assets/library/materials/plastic/acrylic-amber.json new file mode 100644 index 00000000..0483a86e --- /dev/null +++ b/assets/library/materials/plastic/acrylic-amber.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/acrylic-amber", + "name": "Acrylic, amber tint", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.4906, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 53.2, + "transmission_color": [0.5435, 0.2853, 0.0477], + "transmission_depth": 0.005 + }, + "tags": ["polymer", "transparent", "orange", "tinted", "gloss"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C5H8O2)n%20-%20poly(methyl%20methacrylate)/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.4906 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding. transmission_color authored as sRGB #e08a10, the colour reached through 0.005 m, a typical sheet thickness.", + "authored": ["specular_roughness", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/acrylic-blue.json b/assets/library/materials/plastic/acrylic-blue.json new file mode 100644 index 00000000..9a93ec3b --- /dev/null +++ b/assets/library/materials/plastic/acrylic-blue.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/acrylic-blue", + "name": "Acrylic, blue tint", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.4906, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 53.2, + "transmission_color": [0.0609, 0.082, 0.5114], + "transmission_depth": 0.005 + }, + "tags": ["polymer", "transparent", "blue", "tinted", "gloss"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C5H8O2)n%20-%20poly(methyl%20methacrylate)/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.4906 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding. transmission_color authored as sRGB #1a50c8, the colour reached through 0.005 m, a typical sheet thickness.", + "authored": ["specular_roughness", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/acrylic-clear.json b/assets/library/materials/plastic/acrylic-clear.json new file mode 100644 index 00000000..fb431d36 --- /dev/null +++ b/assets/library/materials/plastic/acrylic-clear.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/acrylic-clear", + "name": "Acrylic, clear", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.4906, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 53.2, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "gloss", "architectural"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C5H8O2)n%20-%20poly(methyl%20methacrylate)/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.4906 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/acrylic-frosted.json b/assets/library/materials/plastic/acrylic-frosted.json new file mode 100644 index 00000000..9c1cf0f5 --- /dev/null +++ b/assets/library/materials/plastic/acrylic-frosted.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/acrylic-frosted", + "name": "Acrylic, frosted", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.35, + "specular_ior": 1.4906, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 53.2, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "frosted", "translucent"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C5H8O2)n%20-%20poly(methyl%20methacrylate)/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.4906 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.35 authored: optically polished sheet or moulding. Frosted: roughness 0.35 authored for a sand-blasted or acid-etched sheet.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/acrylic-red.json b/assets/library/materials/plastic/acrylic-red.json new file mode 100644 index 00000000..27c346d9 --- /dev/null +++ b/assets/library/materials/plastic/acrylic-red.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/acrylic-red", + "name": "Acrylic, red tint", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.4906, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 53.2, + "transmission_color": [0.3892, 0.0492, 0.0261], + "transmission_depth": 0.005 + }, + "tags": ["polymer", "transparent", "red", "tinted", "gloss"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C5H8O2)n%20-%20poly(methyl%20methacrylate)/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.4906 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding. transmission_color authored as sRGB #d01020, the colour reached through 0.005 m, a typical sheet thickness.", + "authored": ["specular_roughness", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/acrylic-smoke.json b/assets/library/materials/plastic/acrylic-smoke.json new file mode 100644 index 00000000..d9418cf1 --- /dev/null +++ b/assets/library/materials/plastic/acrylic-smoke.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/acrylic-smoke", + "name": "Acrylic, smoke grey", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.4906, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 53.2, + "transmission_color": [0.1022, 0.1022, 0.1022], + "transmission_depth": 0.005 + }, + "tags": ["polymer", "transparent", "grey", "tinted", "gloss"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C5H8O2)n%20-%20poly(methyl%20methacrylate)/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.4906 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding. transmission_color authored as sRGB #5a5a5a, the colour reached through 0.005 m, a typical sheet thickness.", + "authored": ["specular_roughness", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/cellulose-acetate-clear.json b/assets/library/materials/plastic/cellulose-acetate-clear.json new file mode 100644 index 00000000..53d9e441 --- /dev/null +++ b/assets/library/materials/plastic/cellulose-acetate-clear.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/cellulose-acetate-clear", + "name": "Cellulose acetate, clear", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.4701, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 54.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "gloss", "apparel"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.4701 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding. Index from measured cellulose, the backbone of cellulose acetate film and spectacle frames.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/cr39-clear.json b/assets/library/materials/plastic/cr39-clear.json new file mode 100644 index 00000000..ff30aa69 --- /dev/null +++ b/assets/library/materials/plastic/cr39-clear.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/cr39-clear", + "name": "CR-39 lens resin, clear", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.498, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 58.0, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "gloss", "optics"], + "source": { + "kind": "published", + "reference": "CR-39 Product Bulletin - PPG Industries (2006); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/other/commercial%20polymers/CR-39/nk/poly.yml"], + "notes": "Transparent plastic. specular_ior 1.498 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding. CR-39 data gives only n at 589.3 nm; the Abbe number 58 is authored from lens makers' commonly quoted value for CR-39.", + "authored": ["specular_roughness", "transmission_dispersion_abbe_number"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/hdpe-natural.json b/assets/library/materials/plastic/hdpe-natural.json new file mode 100644 index 00000000..ec3e7807 --- /dev/null +++ b/assets/library/materials/plastic/hdpe-natural.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/hdpe-natural", + "name": "HDPE, natural translucent", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.9119, 0.905, 0.8477], + "base_metalness": 0.0, + "specular_roughness": 0.35, + "specular_ior": 1.54, + "subsurface_weight": 1.0, + "subsurface_color": [0.9119, 0.905, 0.8477], + "subsurface_radius": 0.003, + "subsurface_radius_scale": [1.0, 1.0, 0.9] + }, + "tags": ["polymer", "satin", "white", "translucent", "subsurface", "packaging"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Unpigmented semicrystalline polyolefin: light scatters in the crystallites, so it glows milky. Modelled with subsurface: colour sRGB #f6f4ec, mean free path 3 mm (authored so a 2 mm wall looks translucent but not clear), slightly shorter in blue. Roughness 0.35 authored. specular_ior 1.54: authored typical value for high-density polyethylene, whose crystalline fraction raises n from the amorphous 1.49 to about 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior", "subsurface_color", "subsurface_radius", "subsurface_radius_scale"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/hdpe-white-matte.json b/assets/library/materials/plastic/hdpe-white-matte.json new file mode 100644 index 00000000..dd86e65b --- /dev/null +++ b/assets/library/materials/plastic/hdpe-white-matte.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/hdpe-white-matte", + "name": "HDPE, white matte", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.8915, 0.8881, 0.8595], + "base_metalness": 0.0, + "specular_roughness": 0.55, + "specular_ior": 1.54, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "matte", "white", "opaque", "packaging"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #f3f2ee. Roughness 0.55 authored: fine spark-eroded mould texture, broad highlight. specular_ior 1.54: authored typical value for high-density polyethylene, whose crystalline fraction raises n from the amorphous 1.49 to about 1.54.", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/nylon-black-matte.json b/assets/library/materials/plastic/nylon-black-matte.json new file mode 100644 index 00000000..2bc6fcbf --- /dev/null +++ b/assets/library/materials/plastic/nylon-black-matte.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/nylon-black-matte", + "name": "Nylon, black matte", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.0103, 0.0103, 0.0103], + "base_metalness": 0.0, + "specular_roughness": 0.55, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "matte", "black", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #1a1a1a. Roughness 0.55 authored: fine spark-eroded mould texture, broad highlight. specular_ior 1.53: authored typical value for polyamide 6 (quoted 1.52 to 1.54).", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/nylon-natural-matte.json b/assets/library/materials/plastic/nylon-natural-matte.json new file mode 100644 index 00000000..d155d734 --- /dev/null +++ b/assets/library/materials/plastic/nylon-natural-matte.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/nylon-natural-matte", + "name": "Nylon, natural matte", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.7678, 0.747, 0.6407], + "base_metalness": 0.0, + "specular_roughness": 0.55, + "specular_ior": 1.53, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "matte", "white", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #e6e0cf. Roughness 0.55 authored: fine spark-eroded mould texture, broad highlight. specular_ior 1.53: authored typical value for polyamide 6 (quoted 1.52 to 1.54).", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/pdms-clear.json b/assets/library/materials/plastic/pdms-clear.json new file mode 100644 index 00000000..156b0afd --- /dev/null +++ b/assets/library/materials/plastic/pdms-clear.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/pdms-clear", + "name": "Silicone (PDMS), clear", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.02, + "specular_ior": 1.4316, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 44.6, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "gloss", "elastomer"], + "source": { + "kind": "published", + "reference": "F. Schneider, J. Draheim, R. Kamberger, U. Wallrabe. Process and material properties of polydimethylsiloxane (PDMS) for Optical MEMS. Sens. Actuators A Phys. 151, 95-99 (2009); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C2H6OSi)n%20-%20polydimethylsiloxane/nk/Schneider-Sylgard184.yml"], + "notes": "Transparent plastic. specular_ior 1.4316 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.02 authored: optically polished sheet or moulding. Measured Sylgard 184 polydimethylsiloxane, the common clear casting silicone.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/pet-amber.json b/assets/library/materials/plastic/pet-amber.json new file mode 100644 index 00000000..7fe10f81 --- /dev/null +++ b/assets/library/materials/plastic/pet-amber.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/pet-amber", + "name": "PET, amber bottle tint", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.5693, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 27.9, + "transmission_color": [0.3118, 0.1524, 0.0336], + "transmission_depth": 0.0005 + }, + "tags": ["polymer", "transparent", "brown", "tinted", "packaging"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C10H8O4)n%20-%20polyethylene%20terephthalate/nk/Zhang.yml"], + "notes": "Transparent plastic. specular_ior 1.5693 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding. transmission_color authored as sRGB #b0661c, the colour reached through 0.0005 m, a typical sheet thickness.", + "authored": ["specular_roughness", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/pet-clear.json b/assets/library/materials/plastic/pet-clear.json new file mode 100644 index 00000000..b3b6796c --- /dev/null +++ b/assets/library/materials/plastic/pet-clear.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/pet-clear", + "name": "PET, clear", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.5693, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 27.9, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "gloss", "packaging"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C10H8O4)n%20-%20polyethylene%20terephthalate/nk/Zhang.yml"], + "notes": "Transparent plastic. specular_ior 1.5693 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/pet-green.json b/assets/library/materials/plastic/pet-green.json new file mode 100644 index 00000000..d071c173 --- /dev/null +++ b/assets/library/materials/plastic/pet-green.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/pet-green", + "name": "PET, green bottle tint", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.5693, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 27.9, + "transmission_color": [0.2207, 0.3978, 0.1741], + "transmission_depth": 0.0005 + }, + "tags": ["polymer", "transparent", "green", "tinted", "packaging"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C10H8O4)n%20-%20polyethylene%20terephthalate/nk/Zhang.yml"], + "notes": "Transparent plastic. specular_ior 1.5693 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding. transmission_color authored as sRGB #5fae6a, the colour reached through 0.0005 m, a typical sheet thickness.", + "authored": ["specular_roughness", "transmission_color", "transmission_depth"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/pla-orange-satin.json b/assets/library/materials/plastic/pla-orange-satin.json new file mode 100644 index 00000000..003b1147 --- /dev/null +++ b/assets/library/materials/plastic/pla-orange-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/pla-orange-satin", + "name": "PLA, orange satin", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.6008, 0.2396, 0.0483], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.4589, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "satin", "orange", "opaque", "industrial"], + "source": { + "kind": "published", + "reference": "I. Bodurov, I. Vlaeva, A. Viraneva, T. Yovcheva, S. Sainov. Modified design of a laser refractometer. Nanosci. Nanotechnol. 16, 31-33 (2016); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C3H4O2)n%20-%20polylactic%20acid/nk/Bodurov.yml"], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #f07a1a. Roughness 0.3 authored: lightly textured mould, soft highlight. specular_ior 1.4589 is the measured n at 587.6 nm.", + "authored": ["base_color", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/pla-white-satin.json b/assets/library/materials/plastic/pla-white-satin.json new file mode 100644 index 00000000..106f4a9b --- /dev/null +++ b/assets/library/materials/plastic/pla-white-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/pla-white-satin", + "name": "PLA, white satin", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.8995, 0.8963, 0.8605], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.4589, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "satin", "white", "opaque", "industrial"], + "source": { + "kind": "published", + "reference": "I. Bodurov, I. Vlaeva, A. Viraneva, T. Yovcheva, S. Sainov. Modified design of a laser refractometer. Nanosci. Nanotechnol. 16, 31-33 (2016); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C3H4O2)n%20-%20polylactic%20acid/nk/Bodurov.yml"], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #f4f3ee. Roughness 0.3 authored: lightly textured mould, soft highlight. specular_ior 1.4589 is the measured n at 587.6 nm.", + "authored": ["base_color", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/polycarbonate-clear.json b/assets/library/materials/plastic/polycarbonate-clear.json new file mode 100644 index 00000000..d9d9f647 --- /dev/null +++ b/assets/library/materials/plastic/polycarbonate-clear.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/polycarbonate-clear", + "name": "Polycarbonate, clear", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.5848, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 27.9, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "gloss", "electronics"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C16H14O3)n%20-%20polycarbonate/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.5848 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/polycarbonate-frosted.json b/assets/library/materials/plastic/polycarbonate-frosted.json new file mode 100644 index 00000000..80981498 --- /dev/null +++ b/assets/library/materials/plastic/polycarbonate-frosted.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/polycarbonate-frosted", + "name": "Polycarbonate, frosted", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.5848, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 27.9, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "frosted", "translucent", "lighting"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C16H14O3)n%20-%20polycarbonate/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.5848 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.3 authored: optically polished sheet or moulding. Frosted: roughness 0.3 authored for a textured diffuser moulding.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/polypropylene-black-satin.json b/assets/library/materials/plastic/polypropylene-black-satin.json new file mode 100644 index 00000000..745421e8 --- /dev/null +++ b/assets/library/materials/plastic/polypropylene-black-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/polypropylene-black-satin", + "name": "Polypropylene, black satin", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.0086, 0.0086, 0.0086], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.49, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "satin", "black", "opaque", "automotive"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #171717. Roughness 0.3 authored: lightly textured mould, soft highlight. specular_ior 1.49: authored typical value for isotactic polypropylene (quoted 1.47 to 1.50).", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/polypropylene-natural.json b/assets/library/materials/plastic/polypropylene-natural.json new file mode 100644 index 00000000..ce148386 --- /dev/null +++ b/assets/library/materials/plastic/polypropylene-natural.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/polypropylene-natural", + "name": "Polypropylene, natural translucent", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.8908, 0.8802, 0.8033], + "base_metalness": 0.0, + "specular_roughness": 0.35, + "specular_ior": 1.49, + "subsurface_weight": 1.0, + "subsurface_color": [0.8908, 0.8802, 0.8033], + "subsurface_radius": 0.003, + "subsurface_radius_scale": [1.0, 1.0, 0.9] + }, + "tags": ["polymer", "satin", "white", "translucent", "subsurface", "packaging"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Unpigmented semicrystalline polyolefin: light scatters in the crystallites, so it glows milky. Modelled with subsurface: colour sRGB #f4f1e6, mean free path 3 mm (authored so a 2 mm wall looks translucent but not clear), slightly shorter in blue. Roughness 0.35 authored. specular_ior 1.49: authored typical value for isotactic polypropylene (quoted 1.47 to 1.50).", + "authored": ["base_color", "specular_roughness", "specular_ior", "subsurface_color", "subsurface_radius", "subsurface_radius_scale"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/polypropylene-white-satin.json b/assets/library/materials/plastic/polypropylene-white-satin.json new file mode 100644 index 00000000..3b5a314c --- /dev/null +++ b/assets/library/materials/plastic/polypropylene-white-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/polypropylene-white-satin", + "name": "Polypropylene, white satin", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.8659, 0.8631, 0.8213], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.49, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "satin", "white", "opaque", "packaging"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #f0efe9. Roughness 0.3 authored: lightly textured mould, soft highlight. specular_ior 1.49: authored typical value for isotactic polypropylene (quoted 1.47 to 1.50).", + "authored": ["base_color", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/polystyrene-clear.json b/assets/library/materials/plastic/polystyrene-clear.json new file mode 100644 index 00000000..de1d81c4 --- /dev/null +++ b/assets/library/materials/plastic/polystyrene-clear.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/polystyrene-clear", + "name": "Polystyrene, clear", + "category": "Plastic", + "type": "plastic_clear", + "params": { + "base_color": [1.0, 1.0, 1.0], + "base_metalness": 0.0, + "specular_roughness": 0.01, + "specular_ior": 1.5916, + "transmission_weight": 1.0, + "transmission_dispersion_scale": 0.0, + "transmission_dispersion_abbe_number": 29.5, + "transmission_color": [1.0, 1.0, 1.0], + "transmission_depth": 0.0 + }, + "tags": ["polymer", "transparent", "clear", "gloss", "packaging"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C8H8)n%20-%20polystyrene/nk/Sultanova.yml"], + "notes": "Transparent plastic. specular_ior 1.5916 is the measured n at 587.6 nm; the Abbe number is (nd - 1)/(nF - nC) from the same data, stored with dispersion off (scale 0) since plastics show little fire; turn the scale to 1 for optics. Roughness 0.01 authored: optically polished sheet or moulding.", + "authored": ["specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/pvc-grey-satin.json b/assets/library/materials/plastic/pvc-grey-satin.json new file mode 100644 index 00000000..69bf85f5 --- /dev/null +++ b/assets/library/materials/plastic/pvc-grey-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/pvc-grey-satin", + "name": "PVC, grey satin", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.27, 0.2742, 0.2819], + "base_metalness": 0.0, + "specular_roughness": 0.3, + "specular_ior": 1.5425, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "satin", "grey", "opaque", "architectural"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C2H3Cl)n%20-%20polyvinyl%20chloride/nk/Zhang.yml"], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #8d8f91. Roughness 0.3 authored: lightly textured mould, soft highlight. specular_ior 1.5425 is the measured n at 587.6 nm.", + "authored": ["base_color", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/plastic/pvc-white-gloss.json b/assets/library/materials/plastic/pvc-white-gloss.json new file mode 100644 index 00000000..9f30c21c --- /dev/null +++ b/assets/library/materials/plastic/pvc-white-gloss.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "plastic/pvc-white-gloss", + "name": "PVC, white gloss", + "category": "Plastic", + "type": "plastic", + "params": { + "base_color": [0.8867, 0.8876, 0.8664], + "base_metalness": 0.0, + "specular_roughness": 0.08, + "specular_ior": 1.5425, + "transmission_weight": 0.0, + "coat_weight": 0.0 + }, + "tags": ["polymer", "gloss", "white", "opaque", "architectural"], + "source": { + "kind": "published", + "reference": "X. Zhang, J. Qiu, X. Li, J. Zhao, L. Liu. Complex refractive indices measurements of polymers in visible and near-infrared bands. Appl. Opt. 59, 2337-2344 (2020) (0.4-2 µm); X. Zhang, J. Qiu, J. Zhao, X. Li, L. Liu. Complex refractive indices measurements of polymers in infrared bands. J. Quant. Spectrosc. Radiat. Transf. 252, 107063 (2020) (2-20 µm); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C2H3Cl)n%20-%20polyvinyl%20chloride/nk/Zhang.yml"], + "notes": "Opaque pigmented plastic. base_color authored as sRGB #f2f2ef. Roughness 0.08 authored: polished mould, sharp highlight. specular_ior 1.5425 is the measured n at 587.6 nm.", + "authored": ["base_color", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/black-rubber-matte.json b/assets/library/materials/rubber/black-rubber-matte.json new file mode 100644 index 00000000..ec1b03cc --- /dev/null +++ b/assets/library/materials/rubber/black-rubber-matte.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/black-rubber-matte", + "name": "Black rubber, matte", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.006, 0.006, 0.006], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.7, + "specular_ior": 1.52, + "coat_weight": 0.0 + }, + "tags": ["elastomer", "matte", "black", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Moulded black rubber with a dull bloom. base_color authored as sRGB #121212; specular roughness 0.7 and diffuse roughness 0.5 authored. specular_ior 1.52 authored: the commonly quoted index of natural rubber (cis-polyisoprene) and of carbon-black filled compounds' binder.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/black-rubber-satin.json b/assets/library/materials/rubber/black-rubber-satin.json new file mode 100644 index 00000000..3fdd35a6 --- /dev/null +++ b/assets/library/materials/rubber/black-rubber-satin.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/black-rubber-satin", + "name": "Black rubber, satin", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.006, 0.006, 0.006], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.4, + "specular_ior": 1.52, + "coat_weight": 0.0 + }, + "tags": ["elastomer", "satin", "black", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Freshly moulded or dressed black rubber. base_color authored as sRGB #121212; specular roughness 0.4 and diffuse roughness 0.5 authored. specular_ior 1.52 authored: the commonly quoted index of natural rubber (cis-polyisoprene) and of carbon-black filled compounds' binder.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/epdm-grey.json b/assets/library/materials/rubber/epdm-grey.json new file mode 100644 index 00000000..38aab0cf --- /dev/null +++ b/assets/library/materials/rubber/epdm-grey.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/epdm-grey", + "name": "EPDM rubber, grey", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.1127, 0.1165, 0.1236], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.6, + "specular_ior": 1.52, + "coat_weight": 0.0 + }, + "tags": ["elastomer", "matte", "grey", "opaque", "architectural"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Light-grey EPDM seal or gasket. base_color authored as sRGB #5d6063; specular roughness 0.6 and diffuse roughness 0.5 authored. specular_ior 1.52 authored: the commonly quoted index of natural rubber (cis-polyisoprene) and of carbon-black filled compounds' binder.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/gum-rubber-natural.json b/assets/library/materials/rubber/gum-rubber-natural.json new file mode 100644 index 00000000..d1eff10e --- /dev/null +++ b/assets/library/materials/rubber/gum-rubber-natural.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/gum-rubber-natural", + "name": "Gum rubber, natural", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.3872, 0.2679, 0.1007], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.5, + "specular_ior": 1.52, + "coat_weight": 0.0 + }, + "tags": ["elastomer", "matte", "brown", "opaque", "apparel"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Unfilled natural crepe or gum rubber, as on shoe soles. base_color authored as sRGB #b98a4c; specular roughness 0.5 and diffuse roughness 0.5 authored. specular_ior 1.52 authored: the commonly quoted index of natural rubber (cis-polyisoprene) and of carbon-black filled compounds' binder.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/nitrile-blue.json b/assets/library/materials/rubber/nitrile-blue.json new file mode 100644 index 00000000..23c8b1f1 --- /dev/null +++ b/assets/library/materials/rubber/nitrile-blue.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/nitrile-blue", + "name": "Nitrile rubber, blue", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.1098, 0.1571, 0.5669], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.5, + "specular_ior": 1.52, + "coat_weight": 0.0 + }, + "tags": ["elastomer", "matte", "blue", "opaque", "industrial"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Blue-dyed nitrile, as in gloves and O-rings. base_color authored as sRGB #3a6fd0; specular roughness 0.5 and diffuse roughness 0.5 authored. specular_ior 1.52 authored: the commonly quoted index of natural rubber (cis-polyisoprene) and of carbon-black filled compounds' binder.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/silicone-rubber-red.json b/assets/library/materials/rubber/silicone-rubber-red.json new file mode 100644 index 00000000..8efda2f3 --- /dev/null +++ b/assets/library/materials/rubber/silicone-rubber-red.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/silicone-rubber-red", + "name": "Silicone rubber, red", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.3343, 0.0644, 0.0342], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.4, + "specular_ior": 1.4316, + "coat_weight": 0.0, + "subsurface_weight": 0.3, + "subsurface_color": [0.3343, 0.0644, 0.0342], + "subsurface_radius": 0.002 + }, + "tags": ["elastomer", "satin", "red", "subsurface", "kitchen"], + "source": { + "kind": "published", + "reference": "F. Schneider, J. Draheim, R. Kamberger, U. Wallrabe. Process and material properties of polydimethylsiloxane (PDMS) for Optical MEMS. Sens. Actuators A Phys. 151, 95-99 (2009); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C2H6OSi)n%20-%20polydimethylsiloxane/nk/Schneider-Sylgard184.yml"], + "notes": "Pigmented silicone (PDMS): specular_ior 1.4316 is the measured n of Sylgard 184 at 587.6 nm. base_color and subsurface colour authored as sRGB #c0302a; subsurface weight 0.3 and 2 mm mean free path authored for the slight translucency of moulded silicone; roughness authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "subsurface_weight", "subsurface_color", "subsurface_radius"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/silicone-rubber-white.json b/assets/library/materials/rubber/silicone-rubber-white.json new file mode 100644 index 00000000..d1affd5c --- /dev/null +++ b/assets/library/materials/rubber/silicone-rubber-white.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/silicone-rubber-white", + "name": "Silicone rubber, white", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.8465, 0.8393, 0.7978], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_roughness": 0.4, + "specular_ior": 1.4316, + "coat_weight": 0.0, + "subsurface_weight": 0.3, + "subsurface_color": [0.8465, 0.8393, 0.7978], + "subsurface_radius": 0.002 + }, + "tags": ["elastomer", "satin", "white", "subsurface", "kitchen"], + "source": { + "kind": "published", + "reference": "F. Schneider, J. Draheim, R. Kamberger, U. Wallrabe. Process and material properties of polydimethylsiloxane (PDMS) for Optical MEMS. Sens. Actuators A Phys. 151, 95-99 (2009); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C2H6OSi)n%20-%20polydimethylsiloxane/nk/Schneider-Sylgard184.yml"], + "notes": "Pigmented silicone (PDMS): specular_ior 1.4316 is the measured n of Sylgard 184 at 587.6 nm. base_color and subsurface colour authored as sRGB #eeece6; subsurface weight 0.3 and 2 mm mean free path authored for the slight translucency of moulded silicone; roughness authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "subsurface_weight", "subsurface_color", "subsurface_radius"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/soft-touch-black.json b/assets/library/materials/rubber/soft-touch-black.json new file mode 100644 index 00000000..fb4f1fde --- /dev/null +++ b/assets/library/materials/rubber/soft-touch-black.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/soft-touch-black", + "name": "Soft-touch coating, black", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.0103, 0.0103, 0.0103], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.55, + "specular_ior": 1.52, + "coat_weight": 0.0 + }, + "tags": ["elastomer", "matte", "black", "opaque", "electronics"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Elastomeric soft-touch paint on plastic housings. base_color authored as sRGB #1a1a1a; specular roughness 0.55 and diffuse roughness 0.5 authored. specular_ior 1.52 authored: the commonly quoted index of natural rubber (cis-polyisoprene) and of carbon-black filled compounds' binder.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/rubber/tyre-rubber.json b/assets/library/materials/rubber/tyre-rubber.json new file mode 100644 index 00000000..048ab75b --- /dev/null +++ b/assets/library/materials/rubber/tyre-rubber.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "rubber/tyre-rubber", + "name": "Tyre rubber", + "category": "Rubber", + "type": "rubber", + "params": { + "base_color": [0.0052, 0.0052, 0.0052], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.65, + "specular_ior": 1.52, + "coat_weight": 0.0 + }, + "tags": ["elastomer", "matte", "black", "opaque", "automotive"], + "source": { + "kind": "authored", + "reference": "", + "urls": [], + "notes": "Carbon-black filled tread compound: albedo about 0.01 linear, worn surface. base_color authored as sRGB #101010; specular roughness 0.65 and diffuse roughness 0.5 authored. specular_ior 1.52 authored: the commonly quoted index of natural rubber (cis-polyisoprene) and of carbon-black filled compounds' binder.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "specular_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/concrete.json b/assets/library/materials/stone/concrete.json new file mode 100644 index 00000000..58395884 --- /dev/null +++ b/assets/library/materials/stone/concrete.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/concrete", + "name": "Concrete, smooth", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.3278, 0.3235, 0.3037], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.65, + "specular_ior": 1.5443, + "coat_weight": 0.0 + }, + "tags": ["stone", "matte", "grey", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #9c9a95 authored as the stone's average tone; roughness 0.65 authored for the finish. specular_ior 1.5443 is the measured n of quartz (ordinary ray), concrete's aggregate at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/granite-black-polished.json b/assets/library/materials/stone/granite-black-polished.json new file mode 100644 index 00000000..43b53e49 --- /dev/null +++ b/assets/library/materials/stone/granite-black-polished.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/granite-black-polished", + "name": "Granite, black polished", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.0168, 0.0168, 0.0168], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.08, + "specular_ior": 1.5443, + "coat_weight": 0.0 + }, + "tags": ["stone", "polished", "black", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #232323 authored as the stone's average tone; roughness 0.08 authored for the finish. specular_ior 1.5443 is the measured n of quartz (ordinary ray) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/granite-grey-honed.json b/assets/library/materials/stone/granite-grey-honed.json new file mode 100644 index 00000000..417aca14 --- /dev/null +++ b/assets/library/materials/stone/granite-grey-honed.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/granite-grey-honed", + "name": "Granite, grey honed", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.2562, 0.2543, 0.2473], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.35, + "specular_ior": 1.5443, + "coat_weight": 0.0 + }, + "tags": ["stone", "satin", "grey", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #8b8a88 authored as the stone's average tone; roughness 0.35 authored for the finish. specular_ior 1.5443 is the measured n of quartz (ordinary ray) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/limestone.json b/assets/library/materials/stone/limestone.json new file mode 100644 index 00000000..0de68d54 --- /dev/null +++ b/assets/library/materials/stone/limestone.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/limestone", + "name": "Limestone, sawn", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.5949, 0.5671, 0.4524], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.6, + "specular_ior": 1.6585, + "coat_weight": 0.0 + }, + "tags": ["stone", "matte", "white", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/CaCO3/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #cfc6b0 authored as the stone's average tone; roughness 0.6 authored for the finish. specular_ior 1.6585 is the measured n of calcite (ordinary ray) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/marble-black-polished.json b/assets/library/materials/stone/marble-black-polished.json new file mode 100644 index 00000000..05b4f7cd --- /dev/null +++ b/assets/library/materials/stone/marble-black-polished.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/marble-black-polished", + "name": "Marble, black polished", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.0117, 0.0116, 0.0128], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.08, + "specular_ior": 1.6585, + "coat_weight": 0.0 + }, + "tags": ["stone", "polished", "black", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/CaCO3/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #1c1c1e authored as the stone's average tone; roughness 0.08 authored for the finish. specular_ior 1.6585 is the measured n of calcite (ordinary ray) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/marble-white-honed.json b/assets/library/materials/stone/marble-white-honed.json new file mode 100644 index 00000000..83eac07f --- /dev/null +++ b/assets/library/materials/stone/marble-white-honed.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/marble-white-honed", + "name": "Marble, white honed", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.7799, 0.7691, 0.723], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.35, + "specular_ior": 1.6585, + "coat_weight": 0.0, + "subsurface_weight": 0.5, + "subsurface_color": [0.7799, 0.7691, 0.723], + "subsurface_radius": 0.005 + }, + "tags": ["stone", "satin", "white", "subsurface", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/CaCO3/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #e6e3dc authored as the stone's average tone; roughness 0.35 authored for the finish. specular_ior 1.6585 is the measured n of calcite (ordinary ray) at 587.6 nm. White marble is translucent: subsurface weight 0.5 with a 5 mm mean free path, authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "subsurface_weight", "subsurface_color", "subsurface_radius"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/marble-white-polished.json b/assets/library/materials/stone/marble-white-polished.json new file mode 100644 index 00000000..d81594e7 --- /dev/null +++ b/assets/library/materials/stone/marble-white-polished.json @@ -0,0 +1,28 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/marble-white-polished", + "name": "Marble, white polished", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.8194, 0.808, 0.7671], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.08, + "specular_ior": 1.6585, + "coat_weight": 0.0, + "subsurface_weight": 0.5, + "subsurface_color": [0.8194, 0.808, 0.7671], + "subsurface_radius": 0.005 + }, + "tags": ["stone", "polished", "white", "subsurface", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/CaCO3/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #ebe8e2 authored as the stone's average tone; roughness 0.08 authored for the finish. specular_ior 1.6585 is the measured n of calcite (ordinary ray) at 587.6 nm. White marble is translucent: subsurface weight 0.5 with a 5 mm mean free path, authored.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "subsurface_weight", "subsurface_color", "subsurface_radius"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/sandstone.json b/assets/library/materials/stone/sandstone.json new file mode 100644 index 00000000..21fb01ea --- /dev/null +++ b/assets/library/materials/stone/sandstone.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/sandstone", + "name": "Sandstone, sawn", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.4985, 0.3977, 0.2237], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.7, + "specular_ior": 1.5443, + "coat_weight": 0.0 + }, + "tags": ["stone", "matte", "brown", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #c9a77a authored as the stone's average tone; roughness 0.7 authored for the finish. specular_ior 1.5443 is the measured n of quartz (ordinary ray) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/slate.json b/assets/library/materials/stone/slate.json new file mode 100644 index 00000000..df58439a --- /dev/null +++ b/assets/library/materials/stone/slate.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/slate", + "name": "Slate, riven", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.0728, 0.0777, 0.089], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.55, + "specular_ior": 1.5443, + "coat_weight": 0.0 + }, + "tags": ["stone", "matte", "grey", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/SiO2/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #4a4f55 authored as the stone's average tone; roughness 0.55 authored for the finish. specular_ior 1.5443 is the measured n of quartz (ordinary ray), slate's main mineral with micas at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/stone/travertine-honed.json b/assets/library/materials/stone/travertine-honed.json new file mode 100644 index 00000000..18e63abf --- /dev/null +++ b/assets/library/materials/stone/travertine-honed.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "stone/travertine-honed", + "name": "Travertine, honed", + "category": "Stone", + "type": "stone", + "params": { + "base_color": [0.6226, 0.5699, 0.4163], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.5, + "specular_roughness": 0.4, + "specular_ior": 1.6585, + "coat_weight": 0.0 + }, + "tags": ["stone", "satin", "brown", "needs-graph", "architectural"], + "source": { + "kind": "published", + "reference": "G. Ghosh. Dispersion-equation coefficients for the refractive index and birefringence of calcite and quartz crystals. Opt. Commun. 163, 95-102 (1999); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/main/CaCO3/nk/Ghosh-o.yml"], + "notes": "Base settings only: veins, grains and speckle come from the type's stone graph, which this preset does not carry yet. base_color sRGB #d6c6a8 authored as the stone's average tone; roughness 0.4 authored for the finish. specular_ior 1.6585 is the measured n of calcite (ordinary ray) at 587.6 nm.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/ash-oiled.json b/assets/library/materials/wood/ash-oiled.json new file mode 100644 index 00000000..11f7d337 --- /dev/null +++ b/assets/library/materials/wood/ash-oiled.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/ash-oiled", + "name": "Ash, oiled", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.5423, 0.4648, 0.3015], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.4, + "coat_weight": 0.0 + }, + "tags": ["wood", "satin", "brown", "needs-graph", "furniture"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #cdb48f authored as the species' average tone. Oil-finished wood keeps its texture: no film, roughness 0.4 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/cherry-oiled.json b/assets/library/materials/wood/cherry-oiled.json new file mode 100644 index 00000000..f84c1816 --- /dev/null +++ b/assets/library/materials/wood/cherry-oiled.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/cherry-oiled", + "name": "Cherry, oiled", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.2348, 0.1169, 0.0547], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.4, + "coat_weight": 0.0 + }, + "tags": ["wood", "satin", "red", "needs-graph", "furniture"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #9a5a3a authored as the species' average tone. Oil-finished wood keeps its texture: no film, roughness 0.4 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/ebony-polished.json b/assets/library/materials/wood/ebony-polished.json new file mode 100644 index 00000000..8fcf0e9c --- /dev/null +++ b/assets/library/materials/wood/ebony-polished.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/ebony-polished", + "name": "Ebony, polished", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.0199, 0.0157, 0.0122], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.45, + "coat_weight": 1.0, + "coat_roughness": 0.06, + "coat_ior": 1.5 + }, + "tags": ["wood", "gloss", "black", "needs-graph", "furniture", "coat"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #2a211c authored as the species' average tone. Lacquer film as a coat with roughness 0.06 and ior 1.5 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/maple-lacquered.json b/assets/library/materials/wood/maple-lacquered.json new file mode 100644 index 00000000..94e3f084 --- /dev/null +++ b/assets/library/materials/wood/maple-lacquered.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/maple-lacquered", + "name": "Maple, lacquered", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.6597, 0.5625, 0.3569], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.45, + "coat_weight": 1.0, + "coat_roughness": 0.06, + "coat_ior": 1.5 + }, + "tags": ["wood", "gloss", "yellow", "needs-graph", "furniture", "coat"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #e0c49a authored as the species' average tone. Lacquer film as a coat with roughness 0.06 and ior 1.5 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/oak-lacquered.json b/assets/library/materials/wood/oak-lacquered.json new file mode 100644 index 00000000..858cdc93 --- /dev/null +++ b/assets/library/materials/wood/oak-lacquered.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/oak-lacquered", + "name": "Oak, lacquered", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.3573, 0.2647, 0.1257], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.45, + "coat_weight": 1.0, + "coat_roughness": 0.06, + "coat_ior": 1.5 + }, + "tags": ["wood", "gloss", "brown", "needs-graph", "furniture", "coat"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #b08a5a authored as the species' average tone. Lacquer film as a coat with roughness 0.06 and ior 1.5 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/oak-oiled.json b/assets/library/materials/wood/oak-oiled.json new file mode 100644 index 00000000..a698d286 --- /dev/null +++ b/assets/library/materials/wood/oak-oiled.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/oak-oiled", + "name": "Oak, oiled", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.3573, 0.2647, 0.1257], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.4, + "coat_weight": 0.0 + }, + "tags": ["wood", "satin", "brown", "needs-graph", "furniture"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #b08a5a authored as the species' average tone. Oil-finished wood keeps its texture: no film, roughness 0.4 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/pine-raw.json b/assets/library/materials/wood/pine-raw.json new file mode 100644 index 00000000..fdf74dd7 --- /dev/null +++ b/assets/library/materials/wood/pine-raw.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/pine-raw", + "name": "Pine, raw", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.6693, 0.5688, 0.3231], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.65, + "coat_weight": 0.0 + }, + "tags": ["wood", "matte", "yellow", "needs-graph", "furniture"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #e2c591 authored as the species' average tone. Raw sawn or sanded wood, roughness 0.65 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/teak-oiled.json b/assets/library/materials/wood/teak-oiled.json new file mode 100644 index 00000000..6409b29b --- /dev/null +++ b/assets/library/materials/wood/teak-oiled.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/teak-oiled", + "name": "Teak, oiled", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.2492, 0.1554, 0.0618], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.4, + "coat_weight": 0.0 + }, + "tags": ["wood", "satin", "brown", "needs-graph", "furniture"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #9a6a3c authored as the species' average tone. Oil-finished wood keeps its texture: no film, roughness 0.4 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/walnut-lacquered.json b/assets/library/materials/wood/walnut-lacquered.json new file mode 100644 index 00000000..da07b0c7 --- /dev/null +++ b/assets/library/materials/wood/walnut-lacquered.json @@ -0,0 +1,27 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/walnut-lacquered", + "name": "Walnut, lacquered", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.0885, 0.0582, 0.034], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.45, + "coat_weight": 1.0, + "coat_roughness": 0.06, + "coat_ior": 1.5 + }, + "tags": ["wood", "gloss", "brown", "needs-graph", "furniture", "coat"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #5e4230 authored as the species' average tone. Lacquer film as a coat with roughness 0.06 and ior 1.5 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness", "coat_roughness", "coat_ior"] + }, + "licence": "Apache-2.0" +} diff --git a/assets/library/materials/wood/walnut-oiled.json b/assets/library/materials/wood/walnut-oiled.json new file mode 100644 index 00000000..f2d4e090 --- /dev/null +++ b/assets/library/materials/wood/walnut-oiled.json @@ -0,0 +1,25 @@ +{ + "format": "formshot-material-preset", + "version": 1, + "id": "wood/walnut-oiled", + "name": "Walnut, oiled", + "category": "Wood", + "type": "wood", + "params": { + "base_color": [0.0885, 0.0582, 0.034], + "base_metalness": 0.0, + "base_diffuse_roughness": 0.3, + "specular_ior": 1.4701, + "specular_roughness": 0.4, + "coat_weight": 0.0 + }, + "tags": ["wood", "satin", "brown", "needs-graph", "furniture"], + "source": { + "kind": "published", + "reference": "N. Sultanova, S. Kasarova, I. Nikolov. Dispersion properties of optical polymers. Acta Physica Polonica A 116, 585-587 (2009) (fit of the experimental data with the Sellmeier dispersion formula: Mikhail Polyanskiy); M. N. Polyanskiy, Refractiveindex.info database of optical constants, Sci. Data 11, 94 (2024)", + "urls": ["https://github.com/polyanskiy/refractiveindex.info-database/blob/e6d15e364f70de1cad8a96a20f75689f2fba8b21/database/data/organic/(C6H10O5)n%20-%20cellulose/nk/Sultanova.yml"], + "notes": "Base settings only: grain, rays and ring contrast come from the type's wood graph, which this preset does not carry yet. base_color sRGB #5e4230 authored as the species' average tone. Oil-finished wood keeps its texture: no film, roughness 0.4 (authored). specular_ior 1.4701 is the measured n of cellulose, the main constituent of wood cell walls.", + "authored": ["base_color", "base_diffuse_roughness", "specular_roughness"] + }, + "licence": "Apache-2.0" +} diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 19993a75..246223f4 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # backend HASHOUT_LOG -Living log for the service side, _v0.4.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. +Living log for the service side, _v0.6.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. ## Org-navi-map @@ -12,7 +12,7 @@ backend/ requirements.txt fastapi 0.143.0, uvicorn 0.54.0, websockets 17.2, ptyprocess 0.7.0 / pywinpty 3.0.5 requirements_macos.txt the same without the Windows terminal package requirements_desktop.txt pyinstaller 6.16.0 - app/__init__.py __version__ = "0.4.0", the single version source + app/__init__.py __version__ = "0.6.0", the single version source app/main.py the app: middleware, /api/health, /api/agent, /api/live, static frontend fallback app/startup.py engine lock, shell watch, stand-alone refusal app/local_guard.py Host and Origin guard @@ -22,9 +22,15 @@ backend/ app/project_library.py the Home library on disk: projects, templates, Trash, previews, stored model, project file app/projects.py routes over the library app/engine.py engine bridge: Binding (fsh_py) and Process (formshot-engine dispatch --journal) transports, - frame_bytes, mesh_bytes (FSHM v1), snapshot_bytes, journal_dir, apply_preferences - app/engine_routes.py /api/engine/* (catalogue, dispatch, status, mesh/{key}, snapshot) and /api/render/* + frame_bytes, mesh_bytes (FSHM v1), snapshot_bytes, journal_dir, apply_preferences, + change_event, Engine.dispatch_outside (relays outside edits to the window) + app/engine_routes.py /api/engine/* (catalogue, dispatch, status, mesh/{key}, snapshot, texture) and /api/render/* app/routers/mcp.py HTTP MCP endpoint /mcp over the engine catalogue + app/routers/imports.py /api/imports (model uploads, scan of dropped folders), the hourly .imports sweep + app/routers/cad.py /api/cad/worker and /worker/fetch: the CAD worker's status and its checked download; CLI main() + app/routers/handoff.py /api/handoff/*: watched family folders, held offers, per-app choices, inspect and open + app/routers/textures.py /api/textures: texture image uploads for material slots + app/routers/library.py /api/library/*: preset thumbnails from the engine's cache, the index, batch queueing app/agent/ agent bus: config, events, commands, router, terminal, cmd_terminal, claude_code, agent_programs, cmd_agents, cmd_chat, cmd_prefs, external, consent, agent_lookup ``` @@ -35,6 +41,7 @@ backend/ - [Engine bridge](#engine-bridge) - [Projects library](#projects-library) - [Agents, MCP and consent](#agents-mcp-and-consent) +- [Import, CAD, hand-offs, textures and the library](#import-cad-hand-offs-textures-and-the-library) - [Verification](#verification) ## Layout and names @@ -117,6 +124,12 @@ Each project is a folder `/` with `project.fshot`, `info.json`, `thumb.web - logged: v0.2.0 · 2026-12-02 FormSculpt's JSON-RPC endpoint (initialize, tools/list, tools/call, ping, prompts/list, server/discover): the tools are the engine catalogue under the same dotted names, and calls go through consent. It sits at `app/routers/mcp.py` because `setup/agents.py` looks for that path. `mcp/server.py` forwards stdio to it with `x-formshot-tab` and `x-formshot-agent`. +### app/engine.py, app/main.py, app/routers/mcp.py · outside edits reach the window +- refers-to: app/engine.py :: change_event, Engine.dispatch_outside, Engine.read_only; app/main.py :: /api/agent; app/routers/mcp.py :: call_tool +- kind: decision +- logged: v0.6.0 · 2026-12-02 +An edit made by an agent left the window's summary stale until the window's own next dispatch. Commands that arrive from outside the window client (`/api/agent` and MCP's `call_tool`) now go through `Engine.dispatch_outside(name, args, source)`, which dispatches and, for a successful command the catalogue does not mark read-only, publishes on `/api/events` `document.changed` (file.* and document.*), `selection.changed`, `history.changed` or `scene.changed` with `{source: "agent"|"mcp", command, change, revision}`; the workspace already refreshes on those. `formshot cli dispatch` runs its own engine process and so never reaches the window. Run (polish): an `/api/agent` material.create and an MCP rename appeared in the open material list, the events seen on `/api/events`. + ### app/agent/consent.py · who may change the scene - refers-to: app/agent/consent.py :: permit, requests; app/main.py :: /api/agent; app/settings.py :: agents - kind: rationale @@ -129,6 +142,62 @@ FormSculpt's JSON-RPC endpoint (initialize, tools/list, tools/call, ping, prompt - logged: v0.2.0 · 2026-12-02 Every route other than GET, HEAD and OPTIONS needs `x-formshot-window-key`, except `/api/agent`, `/mcp` and `POST /api/window/key`. Streams and images take a `?ticket=` from `POST /api/window/ticket` (one use, 30 s). The key is claimed once per start (409 after; 404 when the shell prints it). Tab tokens are kept off the window routes. +## Import, CAD, hand-offs, textures and the library + +### app/routers/imports.py · model uploads without python-multipart +- refers-to: app/routers/imports.py :: POST /api/imports, DELETE /api/imports/{id}, POST /api/imports/scan, clean_name, receive, FIELD_LIMIT +- kind: decision +- logged: v0.6.0 · 2026-12-02 +A browser cannot hand the engine a path, so `POST /api/imports` streams a multipart upload to `/.imports/<16 hex id>/` and answers `{id, path, folder, name, files, bytes}`; `path` is absolute and is what the engine opens. Part `main` is the model (the first file part when none is named), parts `files` are siblings with relative names kept up to 4 folders so glTF texture URIs resolve. A small streaming parser in the router reads the body, so requirements.txt did not grow (python-multipart is not installed and FastAPI's `UploadFile` would need it). Names: NFC, control characters and `<>:"|?*` become `_`, leading dots and trailing dots or spaces dropped, 120 characters per segment with the extension kept, Windows device names prefixed with `_` (`CON.glb` is stored as `_CON.glb`), `..` refused; main must be in `project_library.MESH_SUFFIXES`, siblings a model, `.bin`, `.mtl` or image. Limits: 1 GiB per file (`MESH_LIMIT`), 2 GiB per upload, 256 files; a failed or disconnected upload removes its folder. `POST /api/imports/scan {paths}` expands desktop folder drops into model files (depth 6, 500 files). The window key is required on all three (the guard plus `window_key.require`). + +### app/routers/imports.py · the .imports sweep +- refers-to: app/routers/imports.py :: sweep, sweep_forever, lifespan, KEEP_SECONDS, SWEEP_EVERY +- kind: decision +- logged: v0.6.0 · 2026-12-02 +An upload is kept after a successful import because the imported nodes carry `source.path` and `file.reimport` reads it again; removing it at once would break Reimport. A cancelled, failed or aborted upload is deleted at once by the window. Folders under `/.imports/` whose name is a 16-hex id, that are real directories (not links) and hold nothing modified in the last 24 hours (`KEEP_SECONDS`, the newest modified time of the folder and everything in it) are removed when the service starts and every hour after (`SWEEP_EVERY`) in a worker thread. The router's `lifespan` is merged into the app's by FastAPI's `include_router`, so main.py is untouched. After 24 hours, Reimport of such parts reports a missing source for that file, not a crash; CAD parts still retessellate from their kept source. + +### app/routers/cad.py, setup/cad_worker · fetching the CAD worker +- refers-to: app/routers/cad.py :: GET /api/cad/worker, POST /api/cad/worker/fetch, RELEASE, TAG, RECORD_SHA256, BASE, load_record, target_of, host_triple, status, main +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The engine never touches the network, so the service downloads FormCAD's kernel worker, following FormCAD's own kernel service: tag `occt-8.0.1` from `github.com/nodemode-dev/formai-binaries` releases; the record `occt-licence.json` pinned by SHA-256 (`RECORD_SHA256` 7881704...b621); its `targets[triple]`; `SHA256SUMS` must list the pinned record hash and the archive hash, and the archive is checked against it; `tarfile` with `filter="data"`; every file is checked against the record (links must match `link`) and nothing outside it is accepted; then the folder is renamed to `/formshot/workers/occt-8.0.1`. The record is cached in `workers/.records/`, `.fetch-*` scratch folders older than an hour are removed. `FORMSHOT_CAD_RELEASE_URL` points at a mirror with the same files; `FORMSHOT_CAD_RECORD` names a local record, which must still match the pin. To take a new worker release, change `RELEASE` and `RECORD_SHA256`. `GET /api/cad/worker?probe=` answers `worker` (the engine's `cad.status`, with probe passed on), `published` (tag, triple, archive, file count and bytes, or `available: false` with the reason, waiting at most 15 s for an uncached record), `installed`, `cache` and `fetch` (the job). `POST /api/cad/worker/fetch` (window key) answers 409 with a plain reason when the record has no file for this triple, else starts a thread publishing `cad.worker` events (`state`, `stage`: record, download, unpack, verify, done; `fraction`, `message`). There is no cancel route and the events carry no byte counts; the window handles both if they appear. `python -m app.routers.cad fetch|status` is the same code from the command line. + +### app/routers/handoff.py · watching the family's folders, held for consent +- refers-to: app/routers/handoff.py :: GET/POST /api/handoff/apps, GET /api/handoff/offers, POST /api/handoff/offers/{id}, GET /api/handoff/available, POST /api/handoff/inspect, POST /api/handoff/open +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Anything another program can send is held for the person's consent first, as the dock's outside-agents rule does. Sources: the GoF folder (`FORMSHOT_HANDOFF_GOF`, else `FORMSCULPT_GOF`, else `~/Formsculpt/GoF`) and FormSurface's exports (`FORMSHOT_HANDOFF_SURFACE/exports`, else `FORMSURFACE_DATA/exports`, else the `data` its service reports at `FORMSURFACE_SERVICE` or `127.0.0.1:FORMSURFACE_PORT|8766/api/health` with a 1 s timeout, cached 30 s, no proxy, else `~/FormSurface/exports`). A daemon thread started by the first `GET /offers` scans every 2 s only while the window is live (an SSE subscriber or a `GET /offers` in the last 8 s). An item counts when it is meant for FormShot (GoF target `any` or `formshot`; every FormSurface export folder) and unchanged for 1.5 s; the first scan of a place only records, so nothing old is offered. Per app: `blocked` drops (`handoff.blocked`), `allowed` opens as `add` at once (`handoff.opened` with `auto: true`), `ask` holds an offer (`handoff.offered`); a newer version of an item replaces its waiting offer. `POST /offers/{id} {answer: deny|once|always, as: add|new}`: `always` stores the app as allowed and opens its other waiting offers; a failed open puts the offer back. Choices and marks live in `/handoff.json`, not settings.json, whose `clean()` keeps known keys only. `/inspect` and `/open` are the window's own choice, with no prompt; every open publishes `document.changed` and `handoff.opened`. Outside agents reach the engine's `handoff.*` commands through MCP and its consent. + +### app/routers/textures.py · texture uploads +- refers-to: app/routers/textures.py :: POST /api/textures, DELETE /api/textures/{id} +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`POST /api/textures` (window key, multipart, one PNG, JPEG, HDR or EXR image under any file part name, `file` or `image`) stores the file at `/.textures/<16 hex id>/` and answers `{id, path, name, bytes}`; `DELETE /api/textures/{id}` removes it. It reuses `clean_name`, `receive` and `FIELD_LIMIT` from imports.py, so no python-multipart. 512 MiB per image (413, also from Content-Length before reading), an empty image 400, one image per upload, failed uploads remove their folder. At first the engine kept that absolute path, so a project depended on the `.textures` folder; since the QA pass the engine embeds the image into the project when the command naming it runs (`embed_command_path`), so the upload folder is only a staging place. Nothing sweeps `.textures` yet. + +### app/routers/library.py · thumbnails without holding the engine lock +- refers-to: app/routers/library.py :: GET /api/library/thumbnail/{id}, GET /api/library/index, POST /api/library/thumbnails, bundled_library +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`GET /thumbnail/{id}?size=128&h=` serves `image/png` straight from the engine's cache when `h` matches a cached file (`Cache-Control: public, max-age=31536000, immutable`), without asking the engine; otherwise it asks `library.thumbnail` (no wait) and polls every 150 ms for up to 60 s, so the service's engine lock is never held for a render, then answers 200, 503 with `Retry-After: 2` while rendering, 500 with the reason on failure, 404 for an unknown id, 422 for a bad size. `ETag: "-"` and `If-None-Match` give 304; without `h` it answers `no-cache`. `GET /index` passes `category`, `query` and `shelf` to `library.list`. `POST /thumbnails {ids, size}` queues a batch (window key by the guard). When frozen and `FORMSHOT_LIBRARY` is unset, `bundled_library()` finds the bundled library from `sys.executable` by the same places the engine checks and sets `FORMSHOT_LIBRARY` for the engine it starts, because the engine unpacked by PyInstaller sits in a temporary folder where "beside the program" finds nothing. + +### app/engine_routes.py · the document's outside texture files for the window +- refers-to: app/engine_routes.py :: GET /api/engine/texture, TEXTURE_PATH_CHARS, TEXTURE_EMBEDDED +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The window's own engine needs the bytes of textures that live outside the project (embedded ones come in the snapshot). `GET /api/engine/texture?path=` requires the window key (no ticket); `fshot:` paths answer 400; it answers only paths in the union of the `material.program {key}` texture lists over the `scene.summary` materials (cached by `content_revision`), so it can never be used to read an arbitrary file, else 404 ("The current document samples no texture at that path"); not a regular file 404 (the reply says plainly that the file is not there, lead commit 3e69008); above 512 MiB 413. It sends `ETag: "size-mtime_ns"`, `X-Formshot-Texture-Size`, `X-Formshot-Texture-Mtime`, `Cache-Control: no-cache`, and 304 on `If-None-Match`. The imports `stat` and `pathlib.Path` sit inside this region. An engine command listing the snapshot's textures would save one `material.program` call per material per content change. Run: an allowed path 200 with its ETag, revalidation 304, `/etc/passwd` 404, `fshot:` 400, a `..` path 404, no window key 403. + +### app/engine_routes.py · optional uv0 and tangent sections in the mesh block +- refers-to: app/engine_routes.py :: mesh_block, GET /api/engine/mesh/{key} +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`mesh_block(reply)` wraps `app.engine.mesh_bytes` (unchanged) and appends uv set 0 (2 f32 per vertex) and tangents (4 f32 per vertex) when `scene.mesh_data` gives `uv0_b64` and `tangents_b64`, signalled by bits 16 and 17 of header word 1, whose low 16 bits stay the version 1. Readers that read the prefix and ignore trailing bytes (the WebGPU mirror checks `byteLength >= need` only) keep working. The imports `base64`, `binascii` and `struct` sit inside this region (marked `noqa: E402`) so the shared import block was not touched. Checked on synthetic replies: 100 bytes with word 1 = 1; with both sections 172 bytes and word 1 = 0x30001. + +### (import, CAD, hand-off, texture and library routes) · verification +- refers-to: app/routers/imports.py, cad.py, handoff.py, textures.py, library.py +- kind: verification +- logged: v0.6.0 · 2026-12-02 +Each against a running service from the shared venv on its own loopback port. Imports: 403 without the window key, 200 with it (glTF plus bin byte-identical on disk), 400 for a `.py` main and for `../../x.glb`, `CON.glb` stored as `_CON.glb`, 413 for a 1.1 GB file with its partial folder removed, DELETE 403, 200, 404; scan expanded a folder to three model files. Sweep: after start a 3-day-old id folder was gone, a new one and a non-id folder stayed; at +25 h the new one went too. CAD: the fetch through the service installed occt-8.0.1 (7061 files) into a fresh cache with 34 events, 403 without the key; a patched aarch64 triple got 409; wrong hash, extra file, unrecorded link, unsafe path and a changed record were refused. Hand-offs: real FormSculpt sends and FormSurface exports produced prompts in headless Chrome, Always allow opened three, a blocked app produced none, requests without the key got 403. Textures: 403, 200 with identical bytes, `file` and `image` part names, 400 for `.py`, empty, `../../evil.png`, two files and non-multipart, 413 for 600 MB, DELETE 403, 200, 404. Library: index passthrough, ETag and 304, immutable with `h`, a miss rendered in 10.4 s then 0.005 s, 404, 422, batch 403 then 200. `python -c "import app.main"` passes. Not run: `GET /api/cad/worker?probe=true` through a running service, Windows and macOS, the frozen build. + ## Verification ### (service) · run in this workspace diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 6a9beea8..906d362f 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.4.0" +__version__ = "0.6.0" diff --git a/backend/app/engine.py b/backend/app/engine.py index c5e8fd47..a7f81d78 100644 --- a/backend/app/engine.py +++ b/backend/app/engine.py @@ -10,7 +10,7 @@ import threading from pathlib import Path -from app.agent import config +from app.agent import config, events BINARY = "formshot-engine" + (".exe" if os.name == "nt" else "") NOT_BUILT = ("The FormShot engine is not built: neither the fsh_py module nor the formshot-engine program was found. " @@ -256,6 +256,16 @@ def apply_preferences(transport) -> list[str]: return applied +def change_event(name: str) -> str: + if name.startswith(("file.", "document.")): + return "document.changed" + if name.startswith("selection."): + return "selection.changed" + if name.startswith("history."): + return "history.changed" + return "scene.changed" + + class Engine: def __init__(self) -> None: self.lock = threading.Lock() @@ -312,6 +322,14 @@ def dispatch_meta(self, name: str, args: dict | None = None): result = transport.dispatch(name, args or {}) return result, getattr(transport, "meta", None) + def dispatch_outside(self, name: str, args: dict | None, source: str): + result = self.dispatch(name, args) + failed = isinstance(result, dict) and result.get("ok") is False + if not failed and not self.read_only(name): + reply = result if isinstance(result, dict) else {} + events.publish(change_event(name), source=source, command=name, change=reply.get("change"), revision=reply.get("revision")) + return result + def read_only(self, name: str) -> bool: try: listed = self.catalogue() diff --git a/backend/app/engine_routes.py b/backend/app/engine_routes.py index 2c74365f..8b6bd182 100644 --- a/backend/app/engine_routes.py +++ b/backend/app/engine_routes.py @@ -67,6 +67,37 @@ async def dispatch(call: Call, response: Response): return result +import base64 # noqa: E402 +import binascii # noqa: E402 +import struct # noqa: E402 + +MESH_FLAG_UV0 = 1 +MESH_FLAG_TANGENTS = 2 +MESH_SECTIONS = (("uv0_b64", MESH_FLAG_UV0, 8), ("tangents_b64", MESH_FLAG_TANGENTS, 16)) + + +def mesh_block(reply) -> bytes: + data = mesh_bytes(reply) + vertices = struct.unpack_from(" Response: window_key.held_or_ticket(request) @@ -74,7 +105,7 @@ async def mesh(key: str, request: Request) -> Response: raise HTTPException(400, "A mesh key is a decimal number from scene.meshes") reply = await run("scene.mesh_data", {"key": key}) try: - data = mesh_bytes(reply) + data = mesh_block(reply) except EngineError as error: raise HTTPException(error.status, str(error)) from None return Response(content=data, media_type="application/octet-stream", headers={"Cache-Control": "no-store"}) @@ -92,6 +123,63 @@ async def snapshot(request: Request) -> Response: return Response(content=data, media_type="application/octet-stream", headers=headers) +import stat +from pathlib import Path + +TEXTURE_EMBEDDED = "fshot:" +TEXTURE_LIMIT = 512 << 20 +TEXTURE_PATH_CHARS = 4096 +TEXTURE_LISTS: dict[str, Any] = {"revision": None, "paths": frozenset()} + + +async def texture_paths() -> frozenset: + summary = await run("scene.summary", {}) + revision = summary.get("content_revision") if isinstance(summary, dict) else None + if revision is not None and TEXTURE_LISTS["revision"] == revision: + return TEXTURE_LISTS["paths"] + found: set[str] = set() + for m in summary.get("materials") or [] if isinstance(summary, dict) else []: + key = m.get("key") if isinstance(m, dict) else None + if key is None: + continue + program = await run("material.program", {"key": key}) + for t in program.get("textures") or [] if isinstance(program, dict) else []: + path = t.get("path") if isinstance(t, dict) else None + if isinstance(path, str) and path and not path.startswith(TEXTURE_EMBEDDED): + found.add(path) + paths = frozenset(found) + if revision is not None: + TEXTURE_LISTS.update(revision=revision, paths=paths) + return paths + + +@router.get("/api/engine/texture") +async def texture(request: Request, path: str = "") -> Response: + window_key.require(request) + if not path or len(path) > TEXTURE_PATH_CHARS or path.startswith(TEXTURE_EMBEDDED): + raise HTTPException(400, "Name a texture file path the current document uses (embedded textures travel in the snapshot)") + if path not in await texture_paths(): + raise HTTPException(404, "The current document samples no texture at that path") + file = Path(path) + try: + info = await run_in_threadpool(file.stat) + except OSError: + raise HTTPException(404, "The texture file was not found") from None + if not stat.S_ISREG(info.st_mode): + raise HTTPException(404, "The texture path is not a file") + if info.st_size > TEXTURE_LIMIT: + raise HTTPException(413, "The texture file is larger than 512 MiB") + tag = f'"{info.st_size}-{info.st_mtime_ns}"' + headers = {"Cache-Control": "no-cache", "ETag": tag, "X-Formshot-Texture-Size": str(info.st_size), "X-Formshot-Texture-Mtime": str(info.st_mtime_ns)} + if request.headers.get("if-none-match") == tag: + return Response(status_code=304, headers=headers) + try: + data = await run_in_threadpool(file.read_bytes) + except OSError: + raise HTTPException(404, "The texture file could not be read") from None + return Response(content=data, media_type="application/octet-stream", headers=headers) + + @router.post("/api/render/start") async def render_start(request: Request): return await run("render.start", await body_object(request)) diff --git a/backend/app/main.py b/backend/app/main.py index c2b8ae4d..509a4ddc 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -14,7 +14,7 @@ from app.agent import router as agent_router from app.engine import EngineError, EngineUnavailable, engine from app.local_guard import LocalGuard -from app.routers import mcp +from app.routers import cad, handoff, imports, library, mcp, textures mimetypes.add_type("text/javascript", ".js") mimetypes.add_type("text/javascript", ".mjs") @@ -45,6 +45,11 @@ async def lifespan(app): app.include_router(window_key.router) app.include_router(notices.router) app.include_router(mcp.router) +app.include_router(imports.router) +app.include_router(cad.router) +app.include_router(handoff.router) +app.include_router(library.router) +app.include_router(textures.router) @app.middleware("http") @@ -147,7 +152,7 @@ async def agent(request: Request): if target == WINDOW: return {"command": command, "result": await relay.send(command, args, timeout)} try: - result = await run_in_threadpool(engine.dispatch, command, args) + result = await run_in_threadpool(engine.dispatch_outside, command, args, "agent") except EngineUnavailable as error: raise HTTPException(503, str(error)) from None except EngineError as error: diff --git a/backend/app/routers/cad.py b/backend/app/routers/cad.py new file mode 100644 index 00000000..64c3a496 --- /dev/null +++ b/backend/app/routers/cad.py @@ -0,0 +1,419 @@ +"""FormCAD's kernel worker: whether it is here, and fetching it from formai-binaries (0.5.0).""" + +import hashlib +import json +import os +import platform +import shutil +import sys +import tarfile +import tempfile +import threading +import time +import urllib.error +import urllib.request +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Request +from starlette.concurrency import run_in_threadpool + +from app import window_key + +PROGRAM = "formcad-kernel" +RELEASE = "8.0.1" +TAG = f"occt-{RELEASE}" +RECORD_NAME = "occt-licence.json" +RECORD_SHA256 = "78817041308252ee544019c8f73e9663db8249975e08a1a5dacb4a85eaa0b621" +SUMS_NAME = "SHA256SUMS" +PROTOCOL = 2 +BASE = "https://github.com/nodemode-dev/formai-binaries/releases/download" +AGENT = "formshot-cad-fetch" +CHUNK = 1 << 20 + +router = APIRouter(prefix="/api/cad", tags=["cad"]) + +_lock = threading.Lock() +_job = {"state": "idle", "stage": "", "fraction": 0.0, "message": "", "tag": TAG} + + +class FetchError(RuntimeError): + pass + + +def host_triple() -> str: + machine = platform.machine().lower() + arch = "aarch64" if machine in ("arm64", "aarch64") else "x86_64" if machine in ("x86_64", "amd64") else machine + if sys.platform == "darwin": + return f"{arch}-apple-darwin" + if sys.platform.startswith("win"): + return f"{arch}-pc-windows-msvc" + return f"{arch}-unknown-linux-gnu" + + +def exe_name() -> str: + return PROGRAM + (".exe" if sys.platform.startswith("win") else "") + + +def cache_dir() -> Path: + override = os.environ.get("FORMSHOT_CACHE", "").strip() + if override: + return Path(override).expanduser() + if sys.platform == "darwin": + return Path.home() / "Library" / "Caches" + if sys.platform.startswith("win"): + return Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") + xdg = os.environ.get("XDG_CACHE_HOME", "").strip() + return Path(xdg) if xdg and Path(xdg).is_absolute() else Path.home() / ".cache" + + +def workers_dir() -> Path: + return cache_dir() / "formshot" / "workers" + + +def release_base() -> str: + return (os.environ.get("FORMSHOT_CAD_RELEASE_URL", "").strip() or f"{BASE}/{TAG}").rstrip("/") + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(CHUNK), b""): + digest.update(block) + return digest.hexdigest() + + +def download(url: str, target: Path | None, progress=None, timeout: float = 60.0) -> tuple[bytes | None, str]: + request = urllib.request.Request(url, headers={"User-Agent": AGENT}) + digest = hashlib.sha256() + held = bytearray() + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + total = int(response.headers.get("content-length") or 0) + done = 0 + handle = target.open("wb") if target is not None else None + try: + while True: + block = response.read(CHUNK) + if not block: + break + digest.update(block) + done += len(block) + if handle is not None: + handle.write(block) + else: + held.extend(block) + if progress is not None: + progress(done, total) + finally: + if handle is not None: + handle.close() + except urllib.error.HTTPError as error: + raise FetchError(f"{url} answered {error.code}.") from None + except (urllib.error.URLError, OSError, ValueError) as error: + raise FetchError(f"{url} could not be downloaded ({getattr(error, 'reason', error)}).") from None + return (None if target is not None else bytes(held)), digest.hexdigest() + + +def record_cache() -> Path: + return workers_dir() / ".records" / f"{TAG}.json" + + +def parse_record(raw: bytes, where: str) -> dict: + found = hashlib.sha256(raw).hexdigest() + if found != RECORD_SHA256: + raise FetchError(f"The record from {where} does not match the SHA-256 this FormShot pins for {TAG}. Nothing was installed.") + try: + record = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + raise FetchError(f"The record from {where} is not JSON.") from None + if not isinstance(record, dict) or record.get("program") != PROGRAM or str(record.get("release")) != RELEASE: + raise FetchError(f"The record from {where} is not the {PROGRAM} {RELEASE} record.") + return record + + +def load_record(allow_network: bool = True, timeout: float = 60.0) -> dict: + local = os.environ.get("FORMSHOT_CAD_RECORD", "").strip() + if local: + try: + return parse_record(Path(local).read_bytes(), local) + except OSError as error: + raise FetchError(f"The record {local} could not be read ({error}).") from None + cached = record_cache() + if cached.is_file(): + try: + return parse_record(cached.read_bytes(), str(cached)) + except (OSError, FetchError): + pass + if not allow_network: + raise FetchError("The published record has not been downloaded yet.") + url = f"{release_base()}/{RECORD_NAME}" + raw, _ = download(url, None, timeout=timeout) + record = parse_record(raw or b"", url) + try: + cached.parent.mkdir(parents=True, exist_ok=True) + tmp = cached.with_suffix(".tmp") + tmp.write_bytes(raw or b"") + os.replace(tmp, cached) + except OSError: + pass + return record + + +def target_of(record: dict, triple: str) -> dict: + target = (record.get("targets") or {}).get(triple) + if not isinstance(target, dict) or not target.get("files") or not target.get("archive") or not target.get("folder"): + have = ", ".join(sorted((record.get("targets") or {}).keys())) or "none" + raise FetchError(f"The published record for {TAG} has no worker for this computer ({triple}); it has {have}. Nothing was downloaded.") + return target + + +def published(allow_network: bool = True) -> dict: + triple = host_triple() + out = {"tag": TAG, "release": RELEASE, "triple": triple, "source": release_base()} + try: + target = target_of(load_record(allow_network, timeout=15.0), triple) + except FetchError as error: + out.update(available=False, reason=str(error)) + return out + files = target.get("files") or [] + out.update( + available=True, + archive=target.get("archive"), + folder=target.get("folder"), + program=(target.get("programs") or [exe_name()])[0], + protocol=target.get("protocol"), + files=len(files), + bytes=sum(int(f.get("bytes") or 0) for f in files), + minimum_os=target.get("minimum_os"), + ) + return out + + +def archive_sha256(sums: bytes, archive: str) -> str: + want = None + record_line = None + for line in sums.decode("utf-8", "replace").splitlines(): + parts = line.strip().split() + if len(parts) != 2: + continue + digest, name = parts[0].lower(), parts[1].lstrip("*") + if name == archive: + want = digest + elif name == RECORD_NAME: + record_line = digest + if record_line != RECORD_SHA256: + raise FetchError(f"{SUMS_NAME} of {TAG} does not list the pinned record. Nothing was installed.") + if not want: + raise FetchError(f"{SUMS_NAME} of {TAG} does not list {archive}. Nothing was installed.") + return want + + +def inside(root: Path, path: Path) -> bool: + try: + path.resolve().relative_to(root.resolve()) + return True + except (OSError, ValueError): + return False + + +def verify_tree(root: Path, target: dict, progress=None) -> None: + files = target.get("files") or [] + expected = {} + for entry in files: + rel = str(entry.get("path") or "") + if not rel or rel.startswith("/") or ".." in Path(rel).parts: + raise FetchError(f"The record names an unsafe path {rel!r}. Nothing was installed.") + expected[rel] = entry + present = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file() or p.is_symlink()} + for rel in present: + if rel not in expected: + raise FetchError(f"{rel} is in the download but not in the record. Nothing was installed.") + for i, (rel, entry) in enumerate(expected.items()): + path = root / rel + if rel not in present or not path.is_file(): + raise FetchError(f"{rel} is missing from the download. Nothing was installed.") + link = entry.get("link") + if link: + if not path.is_symlink() or os.readlink(path) != link or not inside(root, path): + raise FetchError(f"{rel} is not the link the record describes. Nothing was installed.") + elif path.is_symlink(): + raise FetchError(f"{rel} is a link the record does not describe. Nothing was installed.") + if sha256_file(path) != str(entry.get("sha256") or "").lower(): + raise FetchError(f"{rel} does not match the SHA-256 in the record. Nothing was installed.") + if progress is not None and i % 50 == 0: + progress(i, len(expected)) + + +def install(report=print) -> Path: + triple = host_triple() + report("record", 0.0, f"Reading the published record for {TAG}.") + record = load_record() + target = target_of(record, triple) + if int(target.get("protocol") or 0) != PROTOCOL: + raise FetchError(f"The published worker speaks protocol {target.get('protocol')}; this FormShot speaks {PROTOCOL}. Nothing was installed.") + archive = str(target["archive"]) + folder = str(target["folder"]) + if "/" in archive or "/" in folder or folder in ("", ".", ".."): + raise FetchError("The record names an unsafe archive or folder. Nothing was installed.") + sums, _ = download(f"{release_base()}/{SUMS_NAME}", None) + want = archive_sha256(sums or b"", archive) + root = workers_dir() + root.mkdir(parents=True, exist_ok=True) + for stale in root.glob(".fetch-*"): + if stale.is_dir() and time.time() - stale.stat().st_mtime > 3600: + shutil.rmtree(stale, ignore_errors=True) + work = Path(tempfile.mkdtemp(prefix=".fetch-", dir=root)) + try: + bundle = work / archive + report("download", 0.0, f"Downloading {archive}.") + _, got = download(f"{release_base()}/{archive}", bundle, lambda done, total: report("download", done / total if total else 0.0, f"Downloading {archive}."), timeout=120.0) + if got != want: + raise FetchError(f"{archive} does not match its SHA-256 in {SUMS_NAME}. Nothing was installed.") + report("unpack", 0.0, "Unpacking.") + unpacked = work / "u" + unpacked.mkdir() + try: + with tarfile.open(bundle) as tar: + tar.extractall(unpacked, filter="data") + except (tarfile.TarError, OSError) as error: + raise FetchError(f"{archive} could not be unpacked ({error}). Nothing was installed.") from None + bundle.unlink() + tree = unpacked / folder + if not tree.is_dir(): + raise FetchError(f"{archive} does not hold the folder {folder}. Nothing was installed.") + report("verify", 0.0, "Checking every file against the record.") + verify_tree(tree, target, lambda i, n: report("verify", i / n if n else 1.0, "Checking every file against the record.")) + program = tree / str((target.get("programs") or [exe_name()])[0]) + if not program.is_file(): + raise FetchError(f"{program.name} is not in the download. Nothing was installed.") + if not sys.platform.startswith("win"): + program.chmod(0o755) + destination = root / TAG + if destination.exists(): + os.replace(destination, work / "old") + os.replace(tree, destination) + finally: + shutil.rmtree(work, ignore_errors=True) + report("done", 1.0, f"{TAG} is installed in {destination}.") + return destination + + +def installed() -> list[dict]: + root = workers_dir() + out = [] + if root.is_dir(): + for folder in sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith(".")): + program = folder / exe_name() + if program.is_file(): + out.append({"tag": folder.name, "path": str(program)}) + return out + + +def _set(state: str, stage: str, fraction: float, message: str) -> None: + with _lock: + _job.update(state=state, stage=stage, fraction=round(max(0.0, min(1.0, fraction)), 4), message=message, at=time.time()) + snapshot = dict(_job) + try: + from app.agent import events + + events.publish("cad.worker", **snapshot) + except Exception: + pass + + +def _run() -> None: + last = {"at": 0.0, "stage": ""} + + def report(stage: str, fraction: float, message: str) -> None: + now = time.monotonic() + if stage != last["stage"] or now - last["at"] > 0.25 or fraction >= 1.0: + last.update(at=now, stage=stage) + _set("running" if stage != "done" else "done", stage, fraction, message) + + try: + install(report) + except FetchError as error: + _set("failed", "", 0.0, str(error)) + except Exception as error: + _set("failed", "", 0.0, f"The worker could not be installed ({error}). Nothing was installed.") + + +def engine_status(probe: bool = False) -> dict: + try: + from app.engine import EngineError, EngineUnavailable, engine + + try: + return engine.dispatch("cad.status", {"probe": True} if probe else {}) + except (EngineError, EngineUnavailable) as error: + return {"available": False, "reason": f"The engine could not be asked ({error})."} + except Exception as error: + return {"available": False, "reason": f"The engine could not be asked ({error})."} + + +def status(allow_network: bool = True, probe: bool = False) -> dict: + with _lock: + job = dict(_job) + return { + "worker": engine_status(probe), + "published": published(allow_network), + "installed": installed(), + "cache": str(workers_dir()), + "fetch": job, + } + + +@router.get("/worker") +async def worker_status(probe: bool = False) -> dict: + return await run_in_threadpool(status, True, probe) + + +@router.post("/worker/fetch") +async def worker_fetch(request: Request) -> dict: + window_key.require(request) + with _lock: + if _job["state"] == "running": + return {"started": False, "fetch": dict(_job)} + + def check() -> dict: + try: + return target_of(load_record(), host_triple()) + except FetchError as error: + raise HTTPException(409, str(error)) from None + + await run_in_threadpool(check) + with _lock: + if _job["state"] == "running": + return {"started": False, "fetch": dict(_job)} + _job.update(state="running", stage="record", fraction=0.0, message="Starting.") + threading.Thread(target=_run, name="cad-worker-fetch", daemon=True).start() + with _lock: + return {"started": True, "fetch": dict(_job)} + + +def main(argv: list[str]) -> int: + command = argv[0] if argv else "fetch" + if command == "status": + print(json.dumps({"published": published(), "installed": installed(), "cache": str(workers_dir())}, indent=2)) + return 0 + if command != "fetch": + print("usage: cad_worker [fetch|status]", file=sys.stderr) + return 2 + shown = {"stage": None, "tenth": -1} + + def report(stage: str, fraction: float, message: str) -> None: + tenth = int(fraction * 10) + if stage != shown["stage"] or tenth != shown["tenth"]: + shown.update(stage=stage, tenth=tenth) + print(f"[formshot] {stage:8} {fraction * 100:5.1f}% {message}", flush=True) + + try: + where = install(report) + except FetchError as error: + print(f"[formshot] error: {error}", file=sys.stderr) + return 1 + print(f"[formshot] worker ready: {where / exe_name()}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/backend/app/routers/handoff.py b/backend/app/routers/handoff.py new file mode 100644 index 00000000..9c6d60c2 --- /dev/null +++ b/backend/app/routers/handoff.py @@ -0,0 +1,403 @@ +"""Models and materials handed over by other Form apps (0.5.0). + +The family hands work over through two places: the GoF folder (FORMSCULPT_GOF, else Formsculpt/GoF in the home folder), +where FormSculpt and FormFabric write files and gof.json, and FormSurface's exports folder (FORMSURFACE_DATA, else the +data folder its service reports at /api/health, else FormSurface in the home folder). This router watches both while the +window is open, holds what arrives for FormShot, and asks the person in the window before anything is opened. Each app +can be asked about, always allowed or blocked; the choice is kept in handoff.json in the data folder.""" + +import json +import os +import secrets +import threading +import time +import urllib.error +import urllib.request +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Request +from starlette.concurrency import run_in_threadpool + +from app import window_key +from app.agent import config, events +from app.engine import EngineError, EngineUnavailable, engine + +router = APIRouter(prefix="/api/handoff", tags=["handoff"]) + +APPS = {"formcad": "FormCAD", "formsculpt": "FormSculpt", "formsurface": "FormSurface", "formfabric": "FormFabric"} +CHOICES = ("ask", "allowed", "blocked") +GOF_MANIFEST = "gof.json" +GOF_TARGETS = ("formshot", "any") +SURFACE_PORT = 8766 +HEALTH_SECONDS = 30.0 +SCAN_SECONDS = 2.0 +STABLE_SECONDS = 1.5 +LIVE_SECONDS = 8.0 +MAP_EXTENSIONS = ("png", "tif", "tiff", "exr", "hdr", "jpg", "jpeg", "psd") +MODES = ("new", "add") +ANSWERS = ("deny", "once", "always") +_lock = threading.RLock() +_opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) +_health = {"at": -HEALTH_SECONDS, "data": None} +_offers: dict[str, dict] = {} +_watch: dict = {"thread": None, "window": -LIVE_SECONDS} + + +def _store_path() -> Path: + return config.data_dir() / "handoff.json" + + +def stored() -> dict: + try: + found = json.loads(_store_path().read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return found if isinstance(found, dict) else {} + + +def _save(values: dict) -> None: + part = _store_path().with_name("handoff.json.part") + part.write_text(json.dumps(values, indent=1), encoding="utf-8") + part.replace(_store_path()) + + +def app_choices() -> dict: + kept = stored().get("apps") + kept = kept if isinstance(kept, dict) else {} + return {app: kept.get(app) if kept.get(app) in CHOICES else "ask" for app in APPS} + + +def set_choice(app: str, choice: str) -> dict: + if app not in APPS: + raise HTTPException(400, f"app is one of {', '.join(APPS)}") + if choice not in CHOICES: + raise HTTPException(400, f"choice is one of {', '.join(CHOICES)}") + with _lock: + values = stored() + apps = values.get("apps") if isinstance(values.get("apps"), dict) else {} + apps[app] = choice + values["apps"] = apps + _save(values) + return app_choices() + + +def gof_folder() -> Path: + given = config.env("HANDOFF_GOF") or os.environ.get("FORMSCULPT_GOF", "").strip() + return Path(given).expanduser() if given else Path.home() / "Formsculpt" / "GoF" + + +def _surface_health() -> str | None: + now = time.monotonic() + if now - _health["at"] < HEALTH_SECONDS: + return _health["data"] + port = os.environ.get("FORMSURFACE_PORT", "").strip() + base = os.environ.get("FORMSURFACE_SERVICE", "").strip() or f"http://127.0.0.1:{port if port.isdigit() else SURFACE_PORT}" + data = None + try: + with _opener.open(base.rstrip("/") + "/api/health", timeout=1.0) as reply: + found = json.loads(reply.read().decode("utf-8") or "{}") + data = str(found.get("data") or "") or None if isinstance(found, dict) else None + except (urllib.error.URLError, OSError, ValueError): + data = None + _health.update(at=now, data=data) + return data + + +def surface_exports() -> Path: + given = config.env("HANDOFF_SURFACE") or os.environ.get("FORMSURFACE_DATA", "").strip() + if given: + return Path(given).expanduser() / "exports" + reported = _surface_health() + if reported: + return Path(reported).expanduser() / "exports" + return Path.home() / "FormSurface" / "exports" + + +def sources() -> list[dict]: + gof, surface = gof_folder(), surface_exports() + return [ + {"id": "gof", "label": "GoF folder", "apps": ["formsculpt", "formfabric"], "folder": str(gof), "found": (gof / GOF_MANIFEST).is_file()}, + {"id": "formsurface", "label": "FormSurface exports", "apps": ["formsurface"], "folder": str(surface), "found": surface.is_dir()}, + ] + + +def _app_id(value) -> str | None: + text = str(value or "").strip().lower() + return text if text in APPS else None + + +def _mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def gof_items() -> list[dict]: + folder = gof_folder() + try: + manifest = json.loads((folder / GOF_MANIFEST).read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + if not isinstance(manifest, dict) or not isinstance(manifest.get("objects"), list): + return [] + top = manifest.get("app") + now = time.time() + out = [] + for entry in manifest["objects"]: + if not isinstance(entry, dict): + continue + file = str(entry.get("file") or "") + fmt = str(entry.get("format") or Path(file).suffix.lstrip(".")).lower() + path = folder / file + if not file or Path(file).name != file or fmt == "package" or not path.is_file(): + continue + changed = _mtime(path) + target = str(entry.get("target") or "").lower() + app = _app_id(entry.get("app")) or _app_id(top) + out.append({ + "key": f"gof:{file}", "source": "gof", "path": str(folder), "item": file, "file": str(path), + "app": app, "app_name": APPS.get(app or "", str(entry.get("app") or top or "")), "title": str(entry.get("name") or file), + "format": fmt, "target": target, "for_formshot": target in GOF_TARGETS, "triangles": entry.get("triangles"), + "units": entry.get("units"), "sent": entry.get("sent"), "changed": changed, + "mark": f"{entry.get('sent')}:{entry.get('revision')}:{changed}", "stable": now - changed >= STABLE_SECONDS, + }) + return out + + +def surface_items() -> list[dict]: + exports = surface_exports() + try: + folders = [p for p in exports.iterdir() if p.is_dir() and not p.name.startswith(".")] + except OSError: + return [] + now = time.time() + out = [] + for folder in folders: + stem = folder.name + try: + files = [p for p in folder.iterdir() if p.is_file()] + except OSError: + continue + maps = [p for p in files if p.name.startswith(f"{stem}_") and p.suffix.lower().lstrip(".") in MAP_EXTENSIONS] + mesh = folder / f"{stem}.obj" + if not maps and not mesh.is_file(): + continue + changed = max(_mtime(p) for p in maps + ([mesh] if mesh.is_file() else [])) + out.append({ + "key": f"formsurface:{stem}", "source": "formsurface", "path": str(folder), "item": None, "file": str(folder), + "app": "formsurface", "app_name": APPS["formsurface"], "title": stem, "format": "maps", "target": "any", + "for_formshot": True, "maps": len(maps), "mesh": mesh.is_file(), "changed": changed, + "mark": f"{len(maps)}:{changed}", "stable": now - changed >= STABLE_SECONDS, + }) + return out + + +def available() -> list[dict]: + return sorted(gof_items() + surface_items(), key=lambda i: i["changed"], reverse=True) + + +def run_engine(name: str, args: dict): + try: + return engine.dispatch(name, args) + except EngineUnavailable as error: + raise HTTPException(503, str(error)) from None + except EngineError as error: + raise HTTPException(error.status, str(error)) from None + + +def open_offer(offer: dict, mode: str, auto: bool = False) -> dict: + args = {"path": offer["path"], "as": mode} + if offer.get("item"): + args["item"] = offer["item"] + result = run_engine("handoff.open", args) + events.publish("document.changed", source="handoff") + events.publish("handoff.opened", id=offer.get("id"), app=offer.get("app"), app_name=offer.get("app_name"), title=offer.get("title"), mode=mode, auto=auto) + return result + + +def _public(offer: dict) -> dict: + return {k: v for k, v in offer.items() if k not in ("mark", "stable", "for_formshot")} + + +def pending() -> list[dict]: + return sorted((_public(o) for o in _offers.values()), key=lambda o: o["arrived"]) + + +def _arrive(item: dict) -> None: + choice = app_choices().get(item.get("app") or "", "ask") + if choice == "blocked": + events.publish("handoff.blocked", app=item.get("app"), title=item.get("title")) + return + for old in [k for k, o in _offers.items() if o["key"] == item["key"]]: + _offers.pop(old, None) + events.publish("handoff.withdrawn", id=old) + offer = {**item, "id": secrets.token_urlsafe(9), "arrived": int(time.time() * 1000)} + if choice == "allowed": + try: + open_offer(offer, "add", auto=True) + except HTTPException as error: + offer["error"] = str(error.detail) + else: + return + _offers[offer["id"]] = offer + events.publish("handoff.offered", offer=_public(offer)) + + +def scan() -> int: + fresh = [] + with _lock: + values = stored() + seen = values.get("seen") if isinstance(values.get("seen"), dict) else {} + started = values.get("started") if isinstance(values.get("started"), dict) else {} + for source, folder, items in (("gof", gof_folder(), gof_items()), ("formsurface", surface_exports(), surface_items())): + place = f"{source}:{folder}" + first = place not in started + for item in items: + if not item["for_formshot"] or not item["stable"]: + continue + key = f"{place}|{item['key']}" + if seen.get(key) == item["mark"]: + continue + seen[key] = item["mark"] + if not first: + fresh.append(item) + if folder.is_dir(): + started[place] = int(time.time()) + values["seen"], values["started"] = seen, started + _save(values) + for item in fresh: + _arrive(item) + return len(fresh) + + +def _window_live() -> bool: + return time.monotonic() - _watch["window"] <= LIVE_SECONDS or events.watching() > 0 + + +def _loop() -> None: + while True: + time.sleep(SCAN_SECONDS) + if not _window_live(): + continue + try: + scan() + except Exception: + continue + + +def ensure_watcher() -> None: + _watch["window"] = time.monotonic() + with _lock: + if _watch["thread"] is None: + _watch["thread"] = threading.Thread(target=_loop, name="formshot-handoff-watch", daemon=True) + _watch["thread"].start() + + +@router.get("/apps") +def get_apps(request: Request) -> dict: + window_key.require(request) + return {"apps": app_choices(), "names": APPS, "choices": list(CHOICES)} + + +async def _body(request: Request) -> dict: + try: + body = await request.json() + except ValueError: + body = {} + return body if isinstance(body, dict) else {} + + +@router.post("/apps") +async def post_apps(request: Request) -> dict: + body = await _body(request) + return {"apps": set_choice(str(body.get("app") or ""), str(body.get("choice") or "")), "names": APPS} + + +@router.get("/offers") +async def get_offers(request: Request) -> dict: + window_key.require(request) + ensure_watcher() + await run_in_threadpool(scan) + return {"offers": pending(), "apps": app_choices(), "names": APPS, "sources": await run_in_threadpool(sources)} + + +def answer(oid: str, reply: str, mode: str) -> dict: + if reply not in ANSWERS: + raise HTTPException(400, f"answer is one of {', '.join(ANSWERS)}") + if mode not in MODES: + raise HTTPException(400, f"as is one of {', '.join(MODES)}") + with _lock: + offer = _offers.pop(oid, None) + if offer is None: + raise HTTPException(404, "That hand-off is no longer waiting") + events.publish("handoff.withdrawn", id=oid) + if reply == "deny": + return {"ok": True, "id": oid, "answer": reply} + if reply == "always" and offer.get("app"): + set_choice(offer["app"], "allowed") + try: + result = open_offer(offer, mode) + except HTTPException: + with _lock: + _offers[oid] = offer + events.publish("handoff.offered", offer=_public(offer)) + raise + if reply == "always" and offer.get("app"): + _open_held(offer["app"]) + return {"ok": True, "id": oid, "answer": reply, "as": mode, "result": result, "apps": app_choices()} + + +def _open_held(app: str) -> None: + with _lock: + held = sorted((o for o in _offers.values() if o.get("app") == app), key=lambda o: o["arrived"]) + for o in held: + _offers.pop(o["id"], None) + for o in held: + events.publish("handoff.withdrawn", id=o["id"]) + try: + open_offer(o, "add", auto=True) + except HTTPException as error: + o["error"] = str(error.detail) + with _lock: + _offers[o["id"]] = o + events.publish("handoff.offered", offer=_public(o)) + + +@router.post("/offers/{oid}") +async def post_answer(oid: str, request: Request) -> dict: + body = await _body(request) + return await run_in_threadpool(answer, oid, str(body.get("answer") or ""), str(body.get("as") or "add")) + + +@router.get("/available") +async def get_available(request: Request) -> dict: + window_key.require(request) + return {"items": await run_in_threadpool(available), "sources": await run_in_threadpool(sources)} + + +def _target(body: dict) -> dict: + path = str(body.get("path") or "").strip() + if not path: + raise HTTPException(400, "Give path: the file or folder another Form app wrote") + args = {"path": path} + item = body.get("item") + if isinstance(item, (str, int)) and str(item).strip(): + args["item"] = item + return args + + +@router.post("/inspect") +async def post_inspect(request: Request) -> dict: + args = _target(await _body(request)) + return await run_in_threadpool(run_engine, "handoff.inspect", args) + + +@router.post("/open") +async def post_open(request: Request) -> dict: + body = await _body(request) + mode = str(body.get("as") or "add") + if mode not in MODES: + raise HTTPException(400, f"as is one of {', '.join(MODES)}") + args = _target(body) + return await run_in_threadpool(open_offer, {**args, "title": Path(args["path"]).name}, mode) diff --git a/backend/app/routers/imports.py b/backend/app/routers/imports.py new file mode 100644 index 00000000..cb08f77e --- /dev/null +++ b/backend/app/routers/imports.py @@ -0,0 +1,332 @@ +"""Model files sent by the window for import (0.5.0).""" + +import asyncio +import re +import secrets +import shutil +import time +import unicodedata +from contextlib import asynccontextmanager +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Request +from starlette.concurrency import run_in_threadpool + +from app import project_library as library +from app import window_key + +KEEP_SECONDS = 24 * 3600 +SWEEP_EVERY = 3600 + + +def newest(folder: Path) -> float: + stamp = folder.stat().st_mtime + try: + for child in folder.rglob("*"): + stamp = max(stamp, child.lstat().st_mtime) + except OSError: + pass + return stamp + + +def sweep(now: float | None = None) -> int: + base = library.PROJECTS / FOLDER + if base.is_symlink() or not base.is_dir(): + return 0 + cutoff = (time.time() if now is None else now) - KEEP_SECONDS + removed = 0 + for entry in base.iterdir(): + try: + if entry.is_symlink() or not entry.is_dir() or not ID.match(entry.name): + continue + if newest(entry) < cutoff: + shutil.rmtree(entry, ignore_errors=True) + removed += 1 + except OSError: + continue + return removed + + +async def sweep_forever() -> None: + while True: + try: + await run_in_threadpool(sweep) + except Exception: + pass + await asyncio.sleep(SWEEP_EVERY) + + +@asynccontextmanager +async def lifespan(_app): + task = asyncio.create_task(sweep_forever()) + try: + yield + finally: + task.cancel() + + +router = APIRouter(lifespan=lifespan) + +FOLDER = ".imports" +ID = re.compile(r"^[a-f0-9]{16}\Z") +BAD = re.compile(r'[\x00-\x1f\x7f<>:"|?*]') +WINDOWS_NAMES = {"con", "prn", "aux", "nul", *(f"com{i}" for i in range(1, 10)), *(f"lpt{i}" for i in range(1, 10))} +MODEL_SUFFIXES = library.MESH_SUFFIXES +SIBLING_SUFFIXES = {".bin", ".mtl", ".png", ".jpg", ".jpeg", ".webp", ".ktx2", ".tga", ".bmp", ".tif", ".tiff", ".exr", ".hdr", ".dds", ".gif"} +NAME_LIMIT = 120 +DEPTH_LIMIT = 4 +FILE_LIMIT = library.MESH_LIMIT +TOTAL_LIMIT = 2 * library.MESH_LIMIT +FILE_COUNT = 256 +HEADER_LIMIT = 16 * 1024 +FIELD_LIMIT = 4096 +SCAN_DEPTH = 6 +SCAN_LIMIT = 500 +TOO_BIG = "The upload is too large: one file may be at most 1 GB and one import at most 2 GB" +NOT_MULTIPART = "Send the model as multipart/form-data with a file part named main and any sibling files named files" + + +def root() -> Path: + return library.PROJECTS / FOLDER + + +def clean_segment(raw: str) -> str: + text = unicodedata.normalize("NFC", raw) + text = BAD.sub("_", text).strip().lstrip(".").rstrip(". ") + if not text: + raise HTTPException(400, "A file name is empty after removing characters that cannot be in a file name") + if len(text) > NAME_LIMIT: + stem, dot, ext = text.rpartition(".") + keep = f".{ext}" if dot and len(ext) <= 10 else "" + text = text[: NAME_LIMIT - len(keep)].rstrip(". ") + keep + if text.split(".")[0].lower() in WINDOWS_NAMES: + text = f"_{text}" + return text + + +def clean_name(raw: str, nested: bool) -> str: + parts = [p for p in re.split(r"[\\/]+", raw or "") if p not in ("", ".")] + if not parts: + raise HTTPException(400, "A file has no name") + if ".." in parts: + raise HTTPException(400, f"The file name {raw!r} climbs out of its folder") + if not nested: + parts = parts[-1:] + if len(parts) > DEPTH_LIMIT: + parts = parts[-DEPTH_LIMIT:] + return "/".join(clean_segment(p) for p in parts) + + +def suffix(name: str) -> str: + return Path(name).suffix.lower() + + +def folder_for(entry: str) -> Path: + if not isinstance(entry, str) or not ID.match(entry): + raise HTTPException(404, "No such upload") + path = root() / entry + if path.is_symlink() or not path.is_dir() or not library.inside(path): + raise HTTPException(404, "No such upload") + return path + + +def disposition(headers: bytes) -> tuple[str, str | None]: + text = headers.decode("utf-8", "replace") + line = next((l for l in text.split("\r\n") if l.lower().startswith("content-disposition:")), "") + name = re.search(r'\bname="((?:[^"\\]|\\.)*)"', line) + filename = re.search(r'\bfilename="((?:[^"\\]|\\.)*)"', line) + unquote = lambda s: s.replace('\\"', '"').replace("%22", '"') + return (unquote(name.group(1)) if name else ""), (unquote(filename.group(1)) if filename else None) + + +class Upload: + def __init__(self, folder: Path) -> None: + self.folder = folder + self.files: list[str] = [] + self.main: str | None = None + self.total = 0 + self.handle = None + self.size = 0 + self.field: str | None = None + self.value = b"" + self.fields: dict[str, str] = {} + + def begin(self, field: str, filename: str | None) -> None: + if filename is None: + self.field = field + self.value = b"" + return + if len(self.files) >= FILE_COUNT: + raise HTTPException(400, f"One import may hold at most {FILE_COUNT} files") + is_main = field == "main" or (self.main is None and field != "files" and not self.files) + name = clean_name(filename, nested=not is_main) + kind = suffix(name) + if is_main and kind not in MODEL_SUFFIXES: + raise HTTPException(400, f"FormShot does not import {kind or 'files without an extension'}; it reads {library.MESH_WORDS}") + if not is_main and kind not in MODEL_SUFFIXES | SIBLING_SUFFIXES: + raise HTTPException(400, f"The file {name} is not a model, buffer, material or texture file") + if is_main and self.main is not None: + raise HTTPException(400, "Send one main model per import") + if name in self.files: + raise HTTPException(400, f"The file {name} was sent twice") + target = self.folder / name + target.parent.mkdir(parents=True, exist_ok=True) + if not library.inside(target.parent): + raise HTTPException(400, library.OUTSIDE) + self.handle = target.open("wb") + self.size = 0 + self.files.append(name) + if is_main: + self.main = name + + def write(self, data: bytes) -> None: + if not data: + return + if self.handle is None: + if self.field is not None: + self.value += data + if len(self.value) > FIELD_LIMIT: + raise HTTPException(400, "A form field is too long") + return + self.size += len(data) + self.total += len(data) + if self.size > FILE_LIMIT or self.total > TOTAL_LIMIT: + raise HTTPException(413, TOO_BIG) + self.handle.write(data) + + def end(self) -> None: + if self.handle is not None: + self.handle.close() + self.handle = None + elif self.field is not None: + self.fields[self.field] = self.value.decode("utf-8", "replace") + self.field = None + + def close(self) -> None: + if self.handle is not None: + self.handle.close() + self.handle = None + + +async def receive(request: Request, upload: Upload, boundary: bytes) -> None: + delimiter = b"\r\n--" + boundary + buffer = b"\r\n" + state = "preamble" + async for chunk in request.stream(): + buffer += chunk + while True: + if state == "preamble": + at = buffer.find(delimiter) + if at < 0: + buffer = buffer[-len(delimiter):] + break + buffer = buffer[at + len(delimiter):] + state = "boundary" + if state == "boundary": + if len(buffer) < 2: + break + if buffer.startswith(b"--"): + return + if not buffer.startswith(b"\r\n"): + raise HTTPException(400, NOT_MULTIPART) + buffer = buffer[2:] + state = "headers" + if state == "headers": + at = buffer.find(b"\r\n\r\n") + if at < 0: + if len(buffer) > HEADER_LIMIT: + raise HTTPException(400, NOT_MULTIPART) + break + field, filename = disposition(buffer[:at]) + buffer = buffer[at + 4:] + upload.begin(field, filename) + state = "body" + if state == "body": + at = buffer.find(delimiter) + if at < 0: + keep = len(delimiter) - 1 + if len(buffer) > keep: + upload.write(buffer[:-keep]) + buffer = buffer[-keep:] + break + upload.write(buffer[:at]) + upload.end() + buffer = buffer[at + len(delimiter):] + state = "boundary" + raise HTTPException(400, "The upload ended before its last part") + + +@router.post("/api/imports") +async def create_upload(request: Request): + window_key.require(request) + kind = request.headers.get("content-type", "") + found = re.search(r'boundary="?([^";]+)"?', kind) + if not kind.lower().startswith("multipart/form-data") or not found: + raise HTTPException(400, NOT_MULTIPART) + declared = request.headers.get("content-length", "") + if declared.isdigit() and int(declared) > TOTAL_LIMIT + 1_000_000: + raise HTTPException(413, TOO_BIG) + base = root() + base.mkdir(parents=True, exist_ok=True) + if base.is_symlink() or not library.inside(base): + raise HTTPException(400, library.OUTSIDE) + entry = secrets.token_hex(8) + folder = base / entry + folder.mkdir() + upload = Upload(folder) + try: + await receive(request, upload, found.group(1).encode("latin-1")) + if upload.main is None: + raise HTTPException(400, "The upload holds no model file") + except BaseException: + upload.close() + shutil.rmtree(folder, ignore_errors=True) + raise + main = (folder / upload.main).resolve() + return {"id": entry, "path": str(main), "folder": str(folder.resolve()), "name": upload.main, "files": upload.files, "bytes": upload.total} + + +@router.delete("/api/imports/{entry}") +def delete_upload(entry: str, request: Request): + window_key.require(request) + shutil.rmtree(folder_for(entry)) + return {"ok": True} + + +def walk(path: Path, depth: int, out: list[Path]) -> None: + if len(out) >= SCAN_LIMIT: + return + if path.is_file(): + if suffix(path.name) in MODEL_SUFFIXES and not path.name.startswith("."): + out.append(path) + return + if depth <= 0 or not path.is_dir() or path.is_symlink(): + return + try: + children = sorted(path.iterdir(), key=lambda p: (p.is_dir(), p.name.lower())) + except OSError: + return + for child in children: + if not child.name.startswith("."): + walk(child, depth - 1, out) + + +@router.post("/api/imports/scan") +async def scan_paths(request: Request): + window_key.require(request) + try: + body = await request.json() + except ValueError as error: + raise HTTPException(400, "Send a JSON object with paths") from error + paths = body.get("paths") if isinstance(body, dict) else None + if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths): + raise HTTPException(400, "Send a JSON object with paths, a list of absolute paths") + found: list[Path] = [] + missing = 0 + for raw in paths[:SCAN_LIMIT]: + path = Path(raw).expanduser() + if not path.is_absolute() or not path.exists(): + missing += 1 + continue + walk(path, SCAN_DEPTH, found) + return {"files": [{"path": str(p), "name": p.name} for p in found], "missing": missing, "capped": len(found) >= SCAN_LIMIT} diff --git a/backend/app/routers/library.py b/backend/app/routers/library.py new file mode 100644 index 00000000..e10f1cbd --- /dev/null +++ b/backend/app/routers/library.py @@ -0,0 +1,127 @@ +"""The material library: preset thumbnails from the user cache (rendered by the engine when missing) and the index.""" + +import asyncio +import os +import re +import sys +import time +from pathlib import Path +from typing import Any + +from fastapi import APIRouter, HTTPException, Query, Request, Response +from fastapi.responses import FileResponse +from pydantic import BaseModel, Field +from starlette.concurrency import run_in_threadpool + +from app.engine import EngineError, EngineUnavailable, engine +from app.routers.cad import cache_dir + +router = APIRouter(prefix="/api/library", tags=["library"]) + +LIBRARY_ENV = "FORMSHOT_LIBRARY" +PRODUCT = "FormShot" +MIN_SIZE, MAX_SIZE, DEFAULT_SIZE = 64, 512, 128 +WAIT = 60.0 +POLL = 0.15 +HASH = re.compile(r"^[0-9a-f]{64}$") +IMMUTABLE = "public, max-age=31536000, immutable" +REVALIDATE = "no-cache" +BUSY = ("queued", "rendering") + + +def bundled_library() -> Path | None: + exe = Path(sys.executable).resolve().parent + places = [exe.parent / "Resources" / "library", exe / "library", exe / "resources" / "library", + exe.parent / "lib" / PRODUCT / "library", exe.parent / "lib" / PRODUCT.lower() / "library"] + appdir = os.environ.get("APPDIR", "").strip() + if appdir: + places.append(Path(appdir) / "usr" / "lib" / PRODUCT / "library") + places.append(Path("/usr/lib") / PRODUCT / "library") + return next((p for p in places if (p / "materials" / "index.json").is_file()), None) + + +def point_engine_at_bundle() -> None: + if os.environ.get(LIBRARY_ENV, "").strip() or not getattr(sys, "frozen", False): + return + found = bundled_library() + if found is not None: + os.environ[LIBRARY_ENV] = str(found) + + +point_engine_at_bundle() + + +def thumbs_dir() -> Path: + return cache_dir() / "formshot" / "library" / "thumbs" + + +class Batch(BaseModel): + ids: list[str] = Field(min_length=1, max_length=512) + size: int = Field(DEFAULT_SIZE, ge=MIN_SIZE, le=MAX_SIZE) + + +async def call(name: str, args: dict[str, Any]): + try: + return await run_in_threadpool(engine.dispatch, name, args) + except EngineUnavailable as error: + raise HTTPException(503, str(error)) from None + except EngineError as error: + status = 404 if error.status == 422 and str(error).startswith(("no preset", "no user preset")) else error.status + raise HTTPException(status, str(error)) from None + + +def etag(sha: str, size: int) -> str: + return f'"{sha}-{size}"' + + +def picture(path: Path, sha: str, size: int, request: Request, cache: str) -> Response: + tag = etag(sha, size) + headers = {"ETag": tag, "Cache-Control": cache} + if tag in [t.strip() for t in request.headers.get("if-none-match", "").split(",")]: + return Response(status_code=304, headers=headers) + return FileResponse(path, media_type="image/png", headers=headers) + + +@router.get("/thumbnail/{preset:path}") +async def thumbnail(preset: str, request: Request, size: int = Query(DEFAULT_SIZE, ge=MIN_SIZE, le=MAX_SIZE), + h: str = Query("", max_length=64)) -> Response: + wanted = h.lower() + if wanted and not HASH.match(wanted): + raise HTTPException(400, "h is the preset's SHA-256 in hex, as library.list gives it") + if wanted: + cached = thumbs_dir() / f"{wanted}-{size}.png" + if cached.is_file(): + return picture(cached, wanted, size, request, IMMUTABLE) + deadline = time.monotonic() + WAIT + reply = await call("library.thumbnail", {"id": preset, "size": size}) + while isinstance(reply, dict) and reply.get("state") in BUSY and time.monotonic() < deadline: + await asyncio.sleep(POLL) + reply = await call("library.thumbnail", {"id": preset, "size": size}) + if not isinstance(reply, dict): + raise HTTPException(502, "The engine answered library.thumbnail without a thumbnail") + state = reply.get("state") + if state in BUSY: + raise HTTPException(503, "The thumbnail is still being rendered", headers={"Retry-After": "2"}) + if state != "ready": + raise HTTPException(500, f"The thumbnail could not be rendered: {reply.get('error') or 'unknown reason'}") + sha = str(reply.get("sha256") or "") + path = Path(str(reply.get("path") or "")) + if not path.is_file(): + raise HTTPException(500, "The engine reported a thumbnail that is not in the cache") + return picture(path, sha, size, request, IMMUTABLE if wanted == sha else REVALIDATE) + + +@router.get("/index") +async def index(category: str = Query("", max_length=40), query: str = Query("", max_length=200), + shelf: str = Query("all", max_length=20)): + args: dict[str, Any] = {"shelf": shelf} + if category: + args["category"] = category + if query: + args["query"] = query + return await call("library.list", args) + + +@router.post("/thumbnails") +async def thumbnails(batch: Batch): + return await call("library.thumbnails", {"ids": batch.ids, "size": batch.size}) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 90972baa..7ef9f1d6 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -71,7 +71,7 @@ async def call_tool(name: str, args: dict, tab: bool, agent: str) -> dict: if refusal: return {"content": [{"type": "text", "text": refusal}], "isError": True} try: - reply = await run_in_threadpool(engine.dispatch, name, args) + reply = await run_in_threadpool(engine.dispatch_outside, name, args, "mcp") except (EngineUnavailable, EngineError) as error: return _text({"message": str(error)}, error=True) if isinstance(reply, dict) and reply.get("ok") is False: diff --git a/backend/app/routers/textures.py b/backend/app/routers/textures.py new file mode 100644 index 00000000..7c79679d --- /dev/null +++ b/backend/app/routers/textures.py @@ -0,0 +1,124 @@ +"""Texture images a material uses: uploads from the window, kept beside the project (0.6.0).""" + +import re +import secrets +import shutil +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Request + +from app import project_library as library +from app import window_key +from app.routers.imports import FIELD_LIMIT, clean_name, receive + +router = APIRouter() + +FOLDER = ".textures" +ID = re.compile(r"^[a-f0-9]{16}\Z") +IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".hdr", ".exr"} +IMAGE_WORDS = "PNG, JPEG, Radiance HDR and OpenEXR images" +FILE_LIMIT = 512 << 20 +TOO_BIG = "The image is too large: one texture may be at most 512 MB" +NOT_MULTIPART = "Send the image as multipart/form-data with one file part (named file or image)" + + +def root() -> Path: + return library.PROJECTS / FOLDER + + +def folder_for(entry: str) -> Path: + if not isinstance(entry, str) or not ID.match(entry): + raise HTTPException(404, "No such texture") + path = root() / entry + if path.is_symlink() or not path.is_dir() or not library.inside(path): + raise HTTPException(404, "No such texture") + return path + + +class Upload: + def __init__(self, folder: Path) -> None: + self.folder = folder + self.name: str | None = None + self.size = 0 + self.handle = None + self.field: str | None = None + self.value = b"" + + def begin(self, field: str, filename: str | None) -> None: + if filename is None: + self.field = field + self.value = b"" + return + if self.name is not None: + raise HTTPException(400, "Send one image per texture upload") + name = clean_name(filename, nested=False) + kind = Path(name).suffix.lower() + if kind not in IMAGE_SUFFIXES: + raise HTTPException(400, f"FormShot does not read {kind or 'files without an extension'} as a texture; it reads {IMAGE_WORDS}") + target = self.folder / name + if not library.inside(target.parent): + raise HTTPException(400, library.OUTSIDE) + self.handle = target.open("wb") + self.name = name + + def write(self, data: bytes) -> None: + if not data: + return + if self.handle is None: + if self.field is not None: + self.value += data + if len(self.value) > FIELD_LIMIT: + raise HTTPException(400, "A form field is too long") + return + self.size += len(data) + if self.size > FILE_LIMIT: + raise HTTPException(413, TOO_BIG) + self.handle.write(data) + + def end(self) -> None: + self.close() + self.field = None + + def close(self) -> None: + if self.handle is not None: + self.handle.close() + self.handle = None + + +@router.post("/api/textures") +async def create_texture(request: Request): + window_key.require(request) + kind = request.headers.get("content-type", "") + found = re.search(r'boundary="?([^";]+)"?', kind) + if not kind.lower().startswith("multipart/form-data") or not found: + raise HTTPException(400, NOT_MULTIPART) + declared = request.headers.get("content-length", "") + if declared.isdigit() and int(declared) > FILE_LIMIT + 1_000_000: + raise HTTPException(413, TOO_BIG) + base = root() + base.mkdir(parents=True, exist_ok=True) + if base.is_symlink() or not library.inside(base): + raise HTTPException(400, library.OUTSIDE) + entry = secrets.token_hex(8) + folder = base / entry + folder.mkdir() + upload = Upload(folder) + try: + await receive(request, upload, found.group(1).encode("latin-1")) + if upload.name is None: + raise HTTPException(400, "The upload holds no image") + if upload.size == 0: + raise HTTPException(400, "The image is empty") + except BaseException: + upload.close() + shutil.rmtree(folder, ignore_errors=True) + raise + path = (folder / upload.name).resolve() + return {"id": entry, "path": str(path), "name": upload.name, "bytes": upload.size} + + +@router.delete("/api/textures/{entry}") +def delete_texture(entry: str, request: Request): + window_key.require(request) + shutil.rmtree(folder_for(entry)) + return {"ok": True} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d064bfae..e0f35165 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -4,6 +4,8 @@ This describes FormShot 0.2.0 as it is in the repository. Parts that the plan sc Since 0.2.0 the repository has gained the GPU engine, the live viewport and a crash journal the engine actually writes; the sections [The GPU engine](#the-gpu-engine), [The live viewport](#the-live-viewport) and [The crash journal](#the-crash-journal) describe them, with the detail in [`GPU-ENGINE.md`](GPU-ENGINE.md) and [`VIEWPORT.md`](VIEWPORT.md). GPU rendering has run only on software Vulkan, software OpenGL and software WebGPU, never on a physical graphics card. +The import, CAD, materials and library work added a crate (`fsh-cad`), command groups in their own modules, background import jobs, a material program, and a library of presets; [Command groups](#command-groups), [Import](#import), [CAD and family hand-offs](#cad-and-family-hand-offs), [Materials from the document to the tracers](#materials-from-the-document-to-the-tracers) and [The material library](#the-material-library) describe them, with the detail in [`IMPORT.md`](IMPORT.md), [`MATERIALS.md`](MATERIALS.md) and [`LIBRARY.md`](LIBRARY.md). + ## The pieces ```text @@ -26,24 +28,25 @@ Conventions everywhere in the engine: right-handed, Y up, metres, radians, colou ## The engine crates -All crates live in `native/crates/`, edition 2021, Apache-2.0, version 0.4.0. `fsh-py` and `fsh-wasm` are outside the workspace's default members, so a plain `cargo build` does not need Python or the wasm target; `fsh-render-gpu` is a default member, so a plain build compiles wgpu. +All crates live in `native/crates/`, edition 2021, Apache-2.0, version 0.6.0. `fsh-py` and `fsh-wasm` are outside the workspace's default members, so a plain `cargo build` does not need Python or the wasm target; `fsh-render-gpu` is a default member, so a plain build compiles wgpu. | Crate | Holds | Depends on | | --- | --- | --- | | `fsh-core` | vectors, quaternions, `Mat4`, `Transform` with its inverse, `Ray`, `Aabb`, shading frames; `Rgb` in ACEScg with sRGB conversion and colour temperature; typed render ids and 64-bit document keys; length units; the deterministic sampler (Owen-scrambled Sobol for the first 64 dimensions, a hashed PCG beyond); sampling warps and MIS heuristics | std only | -| `fsh-scene` | the document: groups, parts, lights and cutaways over shared meshes and materials, cameras, environment, ground, image style, render settings; the command table; undo and redo with merge and groups; change levels; selection; `flatten()` to the immutable `RenderSnapshot` | fsh-core, serde, serde_json | +| `fsh-scene` | the document: groups, parts, lights and cutaways over shared meshes and materials, cameras, environment, ground, image style, render settings; the 18 material types, texture slots and material graphs, and the compiler that turns them into material programs; the command table; undo and redo with merge and groups; change levels; selection; `flatten()` to the immutable `RenderSnapshot` | fsh-core, fsh-materials, serde, serde_json | | `fsh-accel` | the two-level BVH (binned SAH per mesh, a top tree over instances), the watertight ray and triangle test, closest-hit and occlusion queries behind the `Intersector` trait | fsh-core, rayon | -| `fsh-materials` | the layered surface BSDF: EON diffuse, anisotropic GGX with visible-normal sampling, dielectric and F82-tint metal Fresnel, coat, rough transmission, fuzz, lobe selection and energy compensation tables built at first use | fsh-core | -| `fsh-io` | glTF/GLB, OBJ with MTL, STL and PLY readers into a neutral raw scene, the clean-up pass (validate, weld, normals, instances, units, up axis, floor and centre) and the conversion to one `scene.import` command; a GLB writer without textures; PNG (8 or 16 bit) and Radiance HDR readers and writers, an uncompressed float OpenEXR writer, and its own deflate, CRC-32 and Adler-32 | fsh-core, fsh-scene, serde_json | -| `fsh-format` | the `.fshot` project file: a stored ZIP of a manifest, the scene and material JSON and binary meshes, saved deterministically, loaded with validation, written atomically; the JSONL command journal with rotating snapshots and recovery | fsh-core, fsh-scene, serde, serde_json | -| `fsh-render-cpu` | the CPU path tracer, the specification engine: tiles on rayon, next-event estimation, MIS, Russian roulette, environment importance sampling, procedural sky and studio sweep, analytic lights, shadow-catcher ground, thin lens, a framebuffer of running sums with progressive passes and a cancel flag, the develop step (exposure; Neutral, AgX, ACES, sRGB and raw transforms) and the a-trous denoiser | fsh-core, fsh-scene, fsh-accel, fsh-materials, rayon | -| `fsh-render-gpu` | the GPU path tracer on wgpu 30 compute: adapters and refusals, the flat scene buffers, one WGSL megakernel with a software BVH traversal and a ray-query variant, the film in row bands, adaptive sampling, reduced-resolution passes and readback through the CPU's develop step (see [`GPU-ENGINE.md`](GPU-ENGINE.md)) | fsh-core, fsh-scene, fsh-accel, fsh-materials, fsh-render-cpu, wgpu, bytemuck, pollster (native), naga (validation feature only) | -| `fsh-commands` | the one command catalogue (88 entries: 39 document commands from `fsh-scene`, 38 engine commands for the app, selection, history, files, viewing and rendering, and 11 aliases from its one alias table) and `dispatch(session, name, args)` over an `Engine` session that owns the document, the history, the selected renderer (CPU or GPU behind one `PreviewRenderer` trait), its background render thread and the crash journal | every crate above; fsh-render-gpu and pollster natively only | -| `fsh-cli` | the `formshot-engine` program: `render` (with `--device`), `info`, `convert`, `devices`, `bench`, `catalogue`, `dispatch` over JSON lines on stdin (with `--journal`), `version` and `help`. Run so far: the sample scene rendered byte-identical on 1 and 2 threads, a GLB and `.fshot` round trip rendered byte-identical pictures from both files, and `bench` rendered the sample on the CPU, software Vulkan and software OpenGL within 0.00001 of each other | fsh-commands, fsh-io | +| `fsh-materials` | the layered surface BSDF: EON diffuse, anisotropic GGX with visible-normal sampling, dielectric and F82-tint metal Fresnel, coat, rough transmission, fuzz, lobe selection and energy compensation tables built at first use; the material program (25 opcodes), its interpreter, the texture pixel types, mips and sampler, the ten procedural patterns, and thin-film iridescence and the dispersion law (`Optics`) | fsh-core, serde | +| `fsh-io` | glTF/GLB, OBJ with MTL, STL, PLY, 3MF and FBX readers into a neutral raw scene with texture slots, the clean-up pass (validate, weld, normals, tangents, instances under rotation and mirroring, units with a confidence, up axis, floor and centre) and the conversion to one `scene.import` command; `probe`; readers for what the other Form apps hand over (`family/`); a GLB writer without textures; PNG (8 or 16 bit) and Radiance HDR readers and writers, an OpenEXR reader (scanline; NONE, RLE, ZIP, PIZ, PXR24) and uncompressed float writer, a JPEG reader, one `decode_image` for textures, and its own deflate, ZIP reader, CRC-32 and Adler-32 | fsh-core, fsh-scene, serde_json, roxmltree, bevy_mikktspace, zune-jpeg; ufbx natively only | +| `fsh-format` | the `.fshot` project file: a stored ZIP of a manifest, the scene and material JSON, binary meshes, embedded textures (named by SHA-256) and kept CAD sources, saved deterministically, loaded with validation, written atomically; the JSONL command journal with rotating snapshots and recovery | fsh-core, fsh-scene, serde, serde_json | +| `fsh-cad` | STEP and IGES through FormCAD's kernel worker, a child process speaking JSON lines: finding it, talking to it with cancel and timeouts, quality presets, reading its tessellation files, colours and shared shapes into a raw scene, and reading STEP and IGES headers and colours from the file itself | fsh-core, fsh-io, serde_json | +| `fsh-render-cpu` | the CPU path tracer, the specification engine: tiles on rayon, next-event estimation, MIS, Russian roulette, environment importance sampling, procedural sky and studio sweep, analytic lights, shadow-catcher ground, thin lens, material programs and textures at every hit with ray-cone footprints, thin film and dispersion, a framebuffer of running sums with progressive passes and a cancel flag, the develop step (exposure; Neutral, AgX, ACES, sRGB and raw transforms) and the a-trous denoiser | fsh-core, fsh-scene, fsh-accel, fsh-materials, rayon | +| `fsh-render-gpu` | the GPU path tracer on wgpu 30 compute: adapters and refusals, the flat scene buffers, one WGSL megakernel with a software BVH traversal and a ray-query variant, the material program interpreter and textures packed into its tables buffer, thin film and dispersion, the film in row bands, adaptive sampling, reduced-resolution passes and readback through the CPU's develop step (see [`GPU-ENGINE.md`](GPU-ENGINE.md)) | fsh-core, fsh-scene, fsh-accel, fsh-materials, fsh-render-cpu, wgpu, bytemuck, pollster (native), naga (validation feature only) | +| `fsh-commands` | the one command catalogue (121 entries: 47 document commands from `fsh-scene`, 38 engine commands for the app, selection, history, files, viewing and rendering, 25 commands of the import, cad, handoff, materials and library groups in `src/ext/`, and 11 aliases from its one alias table) and `dispatch(session, name, args)` over an `Engine` session that owns the document, the history, the selected renderer (CPU or GPU behind one `PreviewRenderer` trait), its background render thread, import jobs, the library's thumbnail worker and the crash journal | every crate above; fsh-render-gpu, fsh-cad and pollster natively only | +| `fsh-cli` | the `formshot-engine` program: `render` (with `--device`), `info`, `convert` (these three with import options), `probe`, `reimport`, `devices`, `bench`, `catalogue`, `dispatch` over JSON lines on stdin (with `--journal`), `version` and `help`. Run so far: the sample scene rendered byte-identical on 1 and 2 threads, a GLB and `.fshot` round trip rendered byte-identical pictures from both files, and `bench` rendered the sample on the CPU, software Vulkan and software OpenGL within 0.00001 of each other | fsh-commands, fsh-io | | `fsh-py` | the PyO3 module `fsh_py`: `catalogue()` and `Session(journal=None).dispatch(name, args_json)`, behind a feature so the workspace builds without Python | fsh-commands | | `fsh-wasm` | the wasm-bindgen package for the window: the document and commands in a `Session`, a mirror of the service's document, and `create_viewport`, which runs `fsh-render-gpu` on WebGPU and presents to a canvas | fsh-commands; on wasm32 also fsh-render-cpu, fsh-render-gpu, wgpu (WebGPU), js-sys, web-sys, wasm-bindgen-futures | -The planned crates and features arrive by phase. The GPU tracer with our own BVH in compute shaders and hardware ray queries (0.3.0) and the WebGPU viewport with a native streamed fallback (0.4.0) are in the tree, with the limits named below. Still to come: more importers and CAD through FormCAD's kernel worker, material presets and the node graph, and the library (0.5.0 to 0.6.0), lighting, cameras, output and the denoisers (0.7.0 to 0.8.0), shots, animation and advanced transport (0.9.0 to 0.10.0), editors and exchange (0.11.0 to 0.12.0), and agents, the render farm and the release (0.13.0 to 0.14.0). +The planned crates and features arrive by phase. The GPU tracer with our own BVH in compute shaders and hardware ray queries (0.3.0) and the WebGPU viewport with a native streamed fallback (0.4.0) are in the tree, with the limits named below. Import of 3MF and FBX, CAD through FormCAD's kernel worker, family hand-offs, material types, texture slots, the node graph and the library are in the tree too, with the limits their sections name, as are labels, thin film and dispersion, and textures and material programs in both path tracers. Still to come: lighting, cameras, output and the denoisers (0.7.0 to 0.8.0), shots, animation and advanced transport (0.9.0 to 0.10.0), editors and exchange (0.11.0 to 0.12.0), and agents, the render farm and the release (0.13.0 to 0.14.0). ## The document and the command registry @@ -63,14 +66,14 @@ How each surface gets to the catalogue: | --- | --- | | Window | `GET /api/engine/catalogue`; each entry is registered in the command registry as `engine.` and appears in the palette; edits go through `POST /api/engine/dispatch` | | MCP | `POST /mcp` `tools/list` returns the catalogue as tools with the same dotted names; `tools/call` dispatches through consent | -| Command line | `formshot-engine catalogue` (or `./formshot cli catalogue`) prints all 88 entries; `formshot-engine dispatch` reads `{"id","name","args"}` lines and answers each with `{id, result}` or `{id, error}` plus `meta: {revision, content_revision}` | +| Command line | `formshot-engine catalogue` (or `./formshot cli catalogue`) prints all 121 entries; `formshot-engine dispatch` reads `{"id","name","args"}` lines and answers each with `{id, result}` or `{id, error}` plus `meta: {revision, content_revision}` | | Agent skills | `./formshot agents sync` writes `.claude/skills/formshot-rendering/references/tools.md`, mirrors the skill into `.agents/skills` and writes `agents/manifest.json` | ## The project file -A `.fshot` file is a stored (uncompressed) ZIP holding a manifest, the scene as JSON, the materials as JSON and the meshes as binary entries. Entries are written in a fixed order with fixed metadata, so saving the same document twice gives the same bytes. Saves go to a temporary file that replaces the old one only when complete. Loading validates the whole tree (every child exists, parent links match, nothing is listed twice or unreachable, part references resolve, every block is in range) and refuses with a readable error. A session keeps an origin copy of the document, a journal of JSON lines recording each resolved command after it, and four rotating snapshots, so a crashed session can be recovered from the journal, a snapshot plus the journal, or the newest snapshot. See `docs/FILE-FORMAT.md` when it is present for the byte layout. +A `.fshot` file is a stored (uncompressed) ZIP holding a manifest, the scene as JSON, the materials as JSON and the meshes as binary entries. Entries are written in a fixed order with fixed metadata, so saving the same document twice gives the same bytes. Saves go to a temporary file that replaces the old one only when complete. Loading validates the whole tree (every child exists, parent links match, nothing is listed twice or unreachable, part references resolve, every block is in range) and refuses with a readable error. A session keeps an origin copy of the document, a journal of JSON lines recording each resolved command after it, and four rotating snapshots, so a crashed session can be recovered from the journal, a snapshot plus the journal, or the newest snapshot. Materials may carry texture slots and a graph, imported textures travel inside the file as members named by their SHA-256, and STEP or IGES sources are kept under `sources/` so CAD parts can be tessellated again. See [`FILE-FORMAT.md`](FILE-FORMAT.md) for the byte layout and what older engines do with newer files. -In the projects library each project is a folder `//` holding `project.fshot`, `info.json`, `thumb.webp` and, when a model was imported, `mesh.`. The service moves these bytes and never opens the ZIP. +In the projects library each project is a folder `//` holding `project.fshot`, `info.json`, `thumb.webp` and, for projects whose model was stored before the import module existed, `mesh.`. Models uploaded from a browser now live in `/.imports//` (kept for Reimport, swept after 24 hours), and images uploaded for slots in `/.textures//`. The service moves these bytes and never opens the ZIP. ## The service @@ -79,11 +82,12 @@ In the projects library each project is a folder `//` holding `p - **Guards.** A local guard refuses any Host or Origin that is not this computer. A window key is created at each start and claimed once by the window; every non-read route needs it in `x-formshot-window-key`, and streams and images take a one-time ticket instead. `/api/agent` and `/mcp` are open but go through consent. - **Engine bridge.** `backend/app/engine.py` tries the `fsh_py` binding first, then runs a `formshot-engine dispatch` child found by `FORMSHOT_ENGINE`, the frozen bundle or `native/target`. Calls are serialised. Errors keep their meaning: refused 422, crashed 502, not built 503, timed out 504, each with a sentence. Nothing is faked when the engine is missing. - **Render routes.** `/api/render/start`, `status`, `frame` and `stop` pass through to the engine's render commands; `frame` answers the latest PNG, or 204 before the first. -- **Byte routes for the viewport.** `GET /api/engine/mesh/{key}` answers one mesh as binary (`FSHM` version 1) for the raster modes, and `GET /api/engine/snapshot` answers the current document as `.fshot` bytes with its content revision in a header, for the engine in the window. Both need the window key or a one-use ticket. +- **Byte routes for the viewport.** `GET /api/engine/mesh/{key}` answers one mesh as binary (`FSHM` version 1, with flags in the high half of the version word for optional uv0 and tangent sections) for the raster modes, and `GET /api/engine/snapshot` answers the current document as `.fshot` bytes with its content revision in a header, for the engine in the window. Both need the window key or a one-use ticket. - **Engine sessions.** Each time an engine session starts, the stored Rendering preferences (device, viewport quality, adaptive sampling) are sent to it, and the engine keeps its crash journal in `/sessions`. - **Projects.** `/api/projects` and its Trash, templates and library settings serve Home. Every path goes through a check that refuses anything outside the projects folder. - **Consent.** Outside agents' changing calls raise a request in the window (deny, once or always). With no live window the request is refused at once. Read-only commands and the app's own dock tabs skip the prompt; Blocked refuses everyone. -- **Agent bus.** `/api/commands` and `/api/events` carry the dock's terminals, Claude Code, Codex, Cursor and Antigravity tabs, Chat and preferences. +- **Agent bus.** `/api/commands` and `/api/events` carry the dock's terminals, Claude Code, Codex, Cursor and Antigravity tabs, Chat and preferences. Engine commands that outside agents send through `/api/agent` or MCP are relayed on `/api/events` as `scene.changed`, `selection.changed`, `history.changed` or `document.changed` (`Engine.dispatch_outside`), so the window follows them at once. +- **Import, CAD, hand-off, texture and library routes.** `/api/imports` takes model uploads and expands dropped folders; `/api/cad/worker` reports and fetches the CAD worker with a pinned, hash-checked record; `/api/handoff/*` watches the family's hand-off folders and holds each arrival for the person's answer; `/api/textures` takes slot images; `/api/library/*` serves preset thumbnails from the engine's cache without holding the engine lock. All writes need the window key. - **Folders.** Data in `FORMSHOT_DATA` (else `~/FormShot` when frozen, else `/workspace`); projects in `FORMSHOT_PROJECTS` (else `~/Documents/FormShot`). ## The window @@ -92,7 +96,7 @@ In the projects library each project is a folder `//` holding `p - **Frame.** `index.html` holds every slot with a fixed id and a pre-paint script that applies the theme, accent and layout before the first frame. The app stays hidden until every module has mounted, then appears once. - **Registry.** `src/shell/registry.ts` holds commands, menus, panels, inspector pages, settings pages and top bar buttons. Menus, the palette, shortcuts and `data-cmd` buttons all run commands. Each slot has one owner. -- **Modules.** `src/modules.ts` lists the entry modules: the workspace (`src/ui/workspace.ts`), Preferences (`src/shell/settings.ts`), menus and the top bar (`src/shell/topbar.ts`), the dock (`src/shell/dock-adapter.ts`) and Home (`src/shell/home.ts`). +- **Modules.** `src/modules.ts` lists the entry modules: the workspace (`src/ui/workspace.ts`), Preferences (`src/shell/settings.ts`), menus and the top bar (`src/shell/topbar.ts`), the dock (`src/shell/dock-adapter.ts`), Home (`src/shell/home.ts`), import (`src/ui/import/`), hand-offs (`src/ui/handoff/`) and CAD (`src/ui/cad/`). The workspace mounts the Material inspector page (`src/ui/pages/material.ts` over `src/ui/material/`), the graph editor window (`src/ui/graph/`) and the library panel (`src/ui/library/`). - **Engine client.** `src/engine/client.ts` reads the catalogue, dispatches, tracks the engine's state (connecting, ready, unavailable, offline) and keeps the scene summary; `src/engine/render.ts` runs the streamed preview over the render routes; `src/engine/raster/` is the WebGL2 renderer and `src/engine/gpu/` the optional WebGPU engine. The engine folder draws only into canvases it is given and never builds UI. - **Viewport.** Rendered mode shows the path tracer; Solid, Wireframe and Material preview (the modes planned for 0.4.0) are drawn in the window with WebGL2; picking, the selection outline, the gizmo, navigation presets, framing and guides work in every mode. See [The live viewport](#the-live-viewport). - **Dock.** `src/dock/` is the family's shared agent dock 2.2.1, copied unchanged from FormVis; `src/shell/dock-adapter.ts` connects it to the service. @@ -121,12 +125,60 @@ In the projects library each project is a folder `//` holding `p - **The path tracer in the window.** When `./formshot engine wasm` has built the package and the browser has WebGPU, the window runs `fsh-render-gpu` itself through `fsh-wasm`, on a mirror of the service's document loaded from the snapshot route. A guard gives the first kernel compile and first pass 45 s; on timeout, error or device loss the window falls back to streamed frames and says why. It has not drawn a frame on any machine yet: software WebGPU runs out of memory compiling the kernel, and no browser with a real GPU was available. - **Streamed frames, the fallback.** The engine renders natively (CPU or GPU) and the window shows its frames from `/api/render/*`. This is the working path today. - **Interaction regimes.** `render.interaction` tells the engine the camera is moving: 1-sample passes at a reduced resolution sized to the frame budget (Viewport quality: 16, 33 or 66 ms), then a ladder of 0.25, 0.5 and full resolution 150 ms after the last move, then accumulation until settled. -- **Invalidation levels.** Commands report `none`, `display` (re-develop, keep samples), `region` (the CPU clears only the screen rectangle of the parts using an edited material) or `full`; camera moves write only the camera block. `scene.summary` carries a `content_revision` that camera moves do not change. +- **Invalidation levels.** Commands report `none`, `display` (re-develop, keep samples), `region` (both engines clear only the screen rectangle of the parts using an edited material, padded by 6 pixels, and keep every other pixel's samples; this holds also when the edit adds a material, as `library.apply` does: the CPU through `changed_instances`, the GPU through `GpuRenderer::update_region`) or `full`; camera moves write only the camera block. `scene.summary` carries a `content_revision` that camera moves do not change. ## The crash journal The engine now drives `fsh-format`'s journal. The service starts it with `/sessions` (`formshot-engine dispatch --journal`, or `fsh_py.Session(journal)`); every editor mutation is recorded after it applies, with snapshots every 100 entries. `file.recover_list` lists sessions left behind with their command counts and any journal error, and `file.recover {session}` restores the document and its undo history from the journal, a snapshot plus the journal, or the newest snapshot. Killing the engine mid-session and recovering through these commands has been run; the window has no recovery dialog yet, so recovery goes through the palette, MCP or the command line. The window's WebAssembly session keeps no journal. +## Command groups + +Commands added from the import work on live in `native/crates/fsh-commands/src/ext/`, one module per group, so that groups can be written side by side without touching the same lines: + +| Module | Commands | +| --- | --- | +| `ext/import.rs` and `ext/import/` | `import.probe`, `import.start`, `import.status`, `import.cancel`, `file.reimport`; the schemas of `file.import` and `file.open` | +| `ext/cad.rs` | `cad.status`, `cad.parts`, `scene.retessellate` | +| `ext/handoff.rs` | `handoff.inspect`, `handoff.open` | +| `ext/materials.rs` | `material.types`, `material.node_kinds`, `material.program`, `material.preview_maps`, `material.labels`, `material.get` | +| `ext/library.rs` and `ext/library/` | `library.list`, `library.get`, `library.favorite`, `library.recent`, `library.apply`, `library.save`, `library.remove`, `library.thumbnail`, `library.thumbnails` | + +Each module fills `COMMANDS` (name, description, change level, mutates, read only, a schema function) and answers its names in `dispatch`, returning `None` for any other; `ext::commands()` chains the groups into the catalogue after the engine commands, and `Engine::dispatch_value` routes their names to `ext::dispatch`. A group reaches the session through a few `pub(crate)` helpers of `engine.rs`: `changed` (apply an outcome's change level), `refresh_render`, `import`, `install_editor`, the `State` fields and the journal notes. Commands that change the document as data (`material.set_slot`, `material.set_graph`, `scene.set_part_mesh` and the rest) stay in `fsh-scene`'s table, so they are undoable and journalled like every other edit. Each module was reserved as an empty file before its owner started, so ownership was decided by path. + +## Import + +[`IMPORT.md`](IMPORT.md) has the detail. The flow: + +1. **Read.** `fsh_io::read_any` picks a reader by content, then extension (glTF/GLB, OBJ, STL, PLY, 3MF, FBX natively); STEP and IGES go to `fsh-cad` instead. Readers give a `RawScene`: nodes, meshes, materials with texture slots, images inside the file. +2. **Clean.** The shared pass validates, welds, makes normals and MikkTSpace tangents, finds repeated parts (also rotated or mirrored), resolves units (option, declared, else a guess with a confidence) and the up axis, and stands the model on the floor. +3. **Prepare.** `ext/import/run.rs::prepare` converts to one `scene.import` payload, wraps or merges the top nodes, records `source.path`, `source.node` and `source.options` in node metadata, and embeds the textures it can read as `fshot:textures/...` members. It never touches the document. +4. **Apply.** `apply` runs the payload, the root rename and framing in one history group, so an import is one undo step and one journal command, then reports the change. + +`file.import` runs all four at once. `import.start` runs steps 1 to 3 on a worker thread against an empty document (CAD reads included, with cancel killing the worker) and answers `{job}`; the next engine call applies a finished job unless a history group is open; `import.status` reports stage and fraction; `import.cancel` and a document change (new, open, close, recover) leave the document untouched. `file.reimport` reads the sources again and matches parts by `source.node`, a unique name, then a unique shape, swapping meshes with `scene.set_part_mesh` so part ids stay. In the window the import module probes, shows the sheet, uploads in a browser (`/api/imports`) or passes the real path on the desktop, and polls the job. + +## CAD and family hand-offs + +STEP and IGES are read by FormCAD's kernel worker (OpenCascade), started as a child process by `fsh-cad` and spoken to in JSON lines; the engine never downloads it. It is found through `FORMSHOT_CAD_WORKER`, beside the program, or in `/formshot/workers//`, where the service's `POST /api/cad/worker/fetch` or `./formshot cad fetch` puts it after checking every file against a pinned record. CAD imports keep their source in the project, tag parts with `cad.*` metadata, and `scene.retessellate` rebuilds their meshes at another quality without changing part ids. + +FormSculpt and FormFabric hand over through GoF folders, FormSurface through map folders, and FormCAD through its GLB and 3MF exports; `fsh_io::family` recognises each. The service watches the GoF folder and FormSurface's exports while the window is open, holds each arrival, and the window asks the person (decline, open once, always allow that app); `handoff.open` then brings it in as one undo step, with FormSurface's maps as document textures. Outside agents reach the same commands through MCP and its consent. + +## Materials from the document to the tracers + +[`MATERIALS.md`](MATERIALS.md) has the detail. The pipeline: + +1. **Document.** A `Material` holds a type id (one of 18 presets of one OpenPBR-style surface model), `params`, optional texture `slots` keyed by material input, and an optional `graph` of nodes (textures, mapping, maths, ramps, normal map, bump and ten procedural patterns), and an ordered list of `labels` (images projected onto the part). +2. **Compile.** `fsh_scene::compile_material` turns slots and graph into a `fsh_materials::Program`: graph outputs win over slots, slots over constants; pure operations are folded, dead code dropped, at most 32 vec4 registers allocated. A material with nothing that varies compiles to a constant program whose `base` is exactly the old per-material inputs. +3. **Snapshot.** `flatten()` gives each `RenderMaterial` its `Arc` and lists the textures programs sample as `RenderTexture`s, deduplicated by path and colour space. +4. **Textures.** `fsh_commands::textures` decodes each `RenderTexture` once (fsh-io's `decode_image`: PNG, JPEG, HDR, EXR), builds mips, and hands the resulting `TextureSet` to the running renderer through `PreviewRenderer::set_textures` when the list or a file changes, restarting the picture; missing images sample their slot's fallback with a warning in `render.status`. +5. **Tracers.** The CPU tracer builds a `HitContext` per hit (with a ray-cone footprint) and calls `Program::evaluate` with the `TextureSet`; constant materials take `program.base` and never run the interpreter. The GPU tracer packs the same set and every program's `encode_f32()` blob into its existing `tables` buffer (no new binding), runs the same opcodes in `program.wgsl` (with `procedural.wgsl` and `texture.wgsl`), and leaves the interpreter out of the kernel when no material needs it; a program it cannot run, or textures that do not fit, send the job to the CPU. Thin film and dispersion are per-material constants applied after the program in both. +6. **Preview.** `material.preview_maps` bakes a program on a 1 m square into base colour, roughness, metalness and normal maps, which the window's Material preview mode samples by mesh uv0, sampling the engine's loaded textures through the same cache. + +The window edits materials through the Material page (types, parameters, slots) and the graph editor, both by document commands, so every edit is undoable. + +## The material library + +[`LIBRARY.md`](LIBRARY.md) has the detail. 249 presets live as JSON files in `assets/library/materials//` with a generated `index.json` that lists each file's SHA-256; every number is traced to measured data (refractiveindex.info, CC0), a published table, or an authored choice named in the file. The engine's `library.*` commands find the library (`FORMSHOT_LIBRARY`, the app's bundled resources, or `assets/library` above the program), check the index against every file, search and rank, keep favourites, recent presets and the user's own presets in the user data folder, and apply a preset as one undo step (type defaults, then the preset's values, then the type's graph tuned to it). Thumbnails are rendered by the CPU tracer on FormShot's own material ball on a background thread and cached by preset hash; the service serves them, and the window's virtual grid asks only for tiles in view. + ## Ports and processes | Port or name | What | diff --git a/docs/FILE-FORMAT.md b/docs/FILE-FORMAT.md index 53af9694..aace0ce3 100644 --- a/docs/FILE-FORMAT.md +++ b/docs/FILE-FORMAT.md @@ -31,9 +31,10 @@ Members are always written in this order: | 2 | `scene.json` | the document without meshes and materials | | 3 | `materials/.json` | one material per member, ascending key | | 4 | `meshes/.fshmesh` | one binary mesh per member, ascending key | -| 5 | `textures/-.` | embedded texture files the scene references, ascending name | -| 6 | `preview.png` | optional preview picture | -| 7 | anything else | members from a newer writer, kept unchanged, ascending name | +| 5 | `textures/.` (or the older `textures/-.`) | embedded texture files the scene references, ascending name | +| 6 | `sources/.` | kept STEP and IGES files some node still refers to, ascending name; only when there are any | +| 7 | `preview.png` | optional preview picture | +| 8 | anything else | members from a newer writer, kept unchanged, ascending name | When a kept member has the same name as one the writer produces, the writer's own member wins. @@ -52,6 +53,7 @@ Every JSON member is canonical: UTF-8, two-space indentation, object keys sorted | `meshes` | mesh keys, ascending, as decimal strings | | `materials` | material keys, ascending, as decimal strings | | `textures` | embedded texture member paths, ascending | +| `sources` | kept CAD source member paths, ascending; the field is left out when there are none | | `preview` | `"preview.png"`, or null when there is none | | other fields | kept verbatim from a newer writer | @@ -61,11 +63,22 @@ The scene member is the document's stored form without its meshes and materials, Each node carries its name, kind (group, part, light or cutaway), parent, children, local transform, visibility, lock, ray visibility, optional part colour, metadata and optional pivot. Transforms are translation, rotation as a quaternion in x, y, z, w order, and scale, applied as translation times rotation times scale. -The environment source is one of `sky` (procedural sky parameters), `hdri` (a path to an equirectangular image), `uniform` (one colour) or `studio` (the renderer's built-in studio sweep). Files from before the studio source existed simply never contain it. +The environment source is one of `sky` (procedural sky parameters), `hdri` (an equirectangular Radiance HDR or OpenEXR image: a `fshot:textures/...` member when the engine embedded it, else a path), `uniform` (one colour) or `studio` (the renderer's built-in studio sweep). Files from before the studio source existed simply never contain it. ### materials/<key>.json -One material: `name`, `type_id` (generic, plastic, metal, glass, paint and so on), `params` with every surface parameter written out explicitly, and `textures` (texture keys). The surface parameters follow the layered model of OpenPBR Surface: base, specular, transmission, subsurface, coat, fuzz, thin film, emission and geometry groups. Unknown fields are kept per material. +One material: `name`, `type_id` (one of the 18 material types: generic, plastic, plastic_clear, metal, metal_brushed, paint, paint_metallic, glass, glass_thin, liquid, gem, rubber, fabric, ceramic, diffuse, emissive, wood, stone), `params` with every surface parameter written out explicitly, `textures` (texture keys), and three optional fields, `slots`, `graph` and `labels`. The surface parameters follow the layered model of OpenPBR Surface: base, specular, transmission, subsurface, coat, fuzz, thin film, emission and geometry groups. Unknown fields are kept per material. The fields a reader treats as known are listed in fsh-scene's `MATERIAL_FIELDS`. + +`slots` and `graph` are left out entirely when empty, so a material without them encodes to the same bytes as before they existed. [`MATERIALS.md`](MATERIALS.md) describes what they mean; their stored form: + +| Field | Form | +| --- | --- | +| `slots` | an object keyed by material input name (`base_color`, `specular_roughness`, `base_metalness`, `specular_weight`, `coat_weight`, `coat_roughness`, `emission_color`, `geometry_opacity`, `normal`, `bump`, `displacement`), each value a texture slot: `texture` (a texture key), `projection` (`{"kind": "uv", "set": 0}`, `{"kind": "box", "blend": 0.5}`, `{"kind": "planar"}`, `{"kind": "cylindrical"}` or `{"kind": "spherical"}`), `transform` (`offset` [u, v], `scale` [u, v], `rotation` in radians, `space` object or world), `wrap` (repeat, clamp, mirror), `filter` (nearest, bilinear, trilinear), `colour_space` (srgb, linear, acescg, data, or null for the input's default), `channel` (rgb, r, g, b, a, luminance), `range` [low, high], `invert`, `multiply`, `strength`, `flip_y` and `fallback` (an RGBA texel or null) | +| `graph` | `nodes`, an object keyed by node id as a decimal string, each node holding `kind`, its settings, `inputs` (unlinked values: a number or [r, g, b]), `position` [x, y] and `label`; `links`, a list of `{"from": [node, "socket"], "to": [node, "socket"]}` sorted by target then source; `outputs`, an object keyed by material input name whose values are `[node, "socket"]` | + +Both are written in a stable order (sorted keys, sorted links), so a graph saves to the same bytes every time. + +`labels`, also left out when empty, is a list in print order (later labels print over earlier ones). Each label: `id` (unique non-zero within the material), `name`, `texture` (a texture key or null), `colour_space` (or null), `origin`, `normal` and `up` ([x, y, z] in the object space of the part wearing the material, metres), `size` ([width, height], metres), `rotation` (radians about the normal), `depth` (metres), `opacity` (0 to 1), `two_sided`, `visible`, `roughness` and `metalness` (0 to 1, or null to leave the surface's). A load refuses zero or negative sizes and depth, a normal parallel to up, values out of range and duplicate ids; unknown label fields in a file do not make the load fail (commands, by contrast, refuse them). A label's image is listed in the material's `textures` like a slot's. ## Mesh members (mesh layout 1.0) @@ -102,7 +115,41 @@ For layout 1.0 the member length must be exactly 64 + N rounded up to 4 + 4 byte ## Embedded textures -A texture file can travel inside the project. It is stored as `textures/<16 lowercase hexadecimal digits of its FNV-1a 64 hash>-.`, where the extension is one to eight lowercase letters or digits, and the texture reference's path becomes `fshot:textures/...`. A save writes only the textures the scene references and fails if a referenced texture has no bytes. A load checks every listed texture's hash and length against its name and refuses an `fshot:` reference whose member is missing. Any other path is an external reference and is left untouched. Engine 0.2.0 does not produce embedded textures yet. +A texture file can travel inside the project. It is stored as `textures/.`, where the extension is one to eight lowercase letters or digits, and the texture reference's path becomes `fshot:textures/...`. Members written by earlier engines are named `textures/<16 lowercase hexadecimal digits of the FNV-1a 64 hash>-.`; a load accepts both and checks each against its name (SHA-256 for the new form, hash and length for the old). An embedded texture may hold at most 256 MiB. A save writes only the textures the scene references and fails if a referenced texture has no bytes. A load refuses an `fshot:` reference whose member is missing. Any other path is an external reference and is left untouched. + +Model imports embed the textures they find: PNG, JPEG, Radiance HDR and OpenEXR files beside the model or inside it (GLB buffers, data URIs, 3MF package parts, FBX embedded content), deduplicated by content. Other image formats are skipped; files above the cap stay referenced by their absolute path; missing files keep their reference, made absolute inside the model's folder, and their slots sample the fallback. Images named by path in a command are embedded when the command runs, not at save time: `material.set_slot {path}`, `material.label_add` and `material.label_set {path}`, `texture.add {texture: {path}}`, and `environment.set` with an HDRI source rewrite the path to `fshot:textures/.` and keep the bytes, so the resolved command in the journal and the saved file both name the member. The same rules apply: PNG, JPEG, Radiance HDR or OpenEXR content of at most 256 MiB; a missing file, another format or a larger file keeps its path as given (relative paths start at the document's folder). A save writes every member a texture reference names, plus the member an embedded environment names, which is not a material texture. + +## Kept CAD sources + +A STEP or IGES file imported through the CAD worker is kept inside the project, so its parts can be tessellated again at another quality after the original file is moved or deleted. It is stored as `sources/<16 lowercase hexadecimal digits of its FNV-1a 64 hash>.` and listed in the manifest's `sources` field; the part nodes name it in their metadata as `source.cad: "fshot:sources/..."`. A load checks the name, that the member holds at most 64 MiB, and that its hash matches the name. A source above 64 MiB is not kept; its parts name the absolute path instead. A save writes only the sources that some node's metadata names; the running session keeps every source it has seen, so undoing the removal of a CAD part and saving again writes its source back. + +## Metadata written by imports + +Imports, re-imports and hand-offs record where nodes came from in each node's `metadata` map (string keys and string values), which older readers keep like any other metadata: + +| Key | On | Meaning | +| --- | --- | --- | +| `source.path` | every imported node | absolute path of the model file (or of the folder for maps only) | +| `source.node` | every imported node | the node's path inside the file, names joined by `/`; empty for a group holding the whole file | +| `source.options` | the import's top nodes | the geometry options with the resolved units and up axis, as JSON | +| `source.missing` | parts a re-import hid | `"true"` until the part returns | +| `source.cad`, `cad.mesh`, `cad.quality`, `cad.unit`, `cad.up` | CAD parts | the kept source (or path), the body and slot, the tessellation quality (a preset name or `chord,angle`), unit and up axis | +| `source.app`, `source.handoff`, `source.title`, `source.writer`, `source.folder`, `source.design_unit`, `source.gof.*`, `source.template`, `source.maps` | hand-offs | which Form app wrote it, how it arrived, and every FormSurface map with its role | +| `material.vertex_colours` | parts | `multiply`: the mesh's vertex colours multiply the base colour | +| `material.alpha_cutoff` | parts | the glTF mask cutoff, kept for a later hard cutoff | + +## Newer files in older engines + +The format version stays 1.0.0: every addition is optional and older files load unchanged and resave to the same bytes. What an engine from before each addition does with a file that uses it: + +| Addition | Older engine | +| --- | --- | +| `slots`, `graph` and `labels` on a material | keeps them as unknown material fields and writes them back unchanged; renders the material from its constant parameters | +| `sources/` members and the manifest's `sources` | keeps them as unknown members and fields and writes them back; cannot tessellate again | +| texture members named by SHA-256 | refuses the file: its loader reports that the member "is not named -". Files without embedded textures are not affected | +| import metadata keys | keeps them; they are plain node metadata | +| an environment naming a `fshot:textures/...` member | refuses the file for the SHA-256 member name above; an engine that accepts the name but predates embedded environments treats the member name as a path on disk and cannot load the image | + ## What a load checks @@ -136,6 +183,7 @@ While a document is open, a session can keep enough on disk to rebuild it after | `origin-.fshot` | the document the journal continues from (generation g) | | `journal.jsonl` | append-only, one compact canonical JSON object per line | | `snapshot-<0..3>.fshot` | four rotating background snapshots | +| `sources/.` | kept CAD sources, each written once, named and checked as project members; recovery puts them back into the document's project | ### Journal lines diff --git a/docs/GPU-ENGINE.md b/docs/GPU-ENGINE.md index ec532ec5..e5aa1fa3 100644 --- a/docs/GPU-ENGINE.md +++ b/docs/GPU-ENGINE.md @@ -8,7 +8,7 @@ The engine has run only on software implementations: Vulkan on lavapipe (Mesa's ## Shape -- **One megakernel.** One invocation is one pixel taking its samples in order (`@workgroup_size(8, 8)`). The host dispatches once per band of rows. Materials are data, parameter records in a buffer, so changing a material never compiles a shader. +- **One megakernel.** One invocation is one pixel taking its samples in order (`@workgroup_size(8, 8)`). The host dispatches once per band of rows. Materials are data, parameter records in a buffer, and texture slots, graphs and labels are a material program the kernel interprets from the `tables` buffer, so changing a material never compiles a shader (a scene that starts using programs compiles the interpreter variant once). - **Two traversal paths behind one interface.** Every module calls `trace_closest(ray, mask) -> TraceHit` and `trace_occluded(ray, mask) -> bool`. The software path walks FormShot's own two-level BVH, flattened from `fsh-accel` into storage buffers; it runs wherever compute runs (Vulkan, Metal, Direct3D 12, OpenGL with compute, WebGPU). The hardware path uses ray queries over acceleration structures built by the driver, where the adapter offers them. - **Bands.** The film is split into row bands that each fit one storage binding (2048 by 1536 needs two at 128 MiB). Natively a pass is split further into dispatches of about 0.1 s over interleaved rows, checking the cancel flag between them, so no dispatch runs long enough to trip an operating system's GPU watchdog. - **Readback.** The film holds the same running sums as the CPU's `PixelSums`. Develop (exposure, tone map, denoise) runs through `fsh-render-cpu`'s own develop step after a readback; in the window the WebAssembly build resolves and tone maps on the GPU instead. @@ -26,6 +26,8 @@ Measured at 320 by 240, 16 samples per pixel, against the CPU on 2 threads: | glass (rough, tinted and thin-walled spheres) | 0.00001 | 0.00001 | 0.000011 | | sky and sun with a thin lens | 0.00000 | 0.00000 | 0.000001 | +Material programs, textures and optics, against the CPU on lavapipe at 320 by 240 and 16 samples: a scene with a uv checker, a normal map with roughness from alpha, box-projected colour and bump and a spherical checker (128 px textures with mips) 0.000083, the same with ray queries and with software traversal; soap bubbles 0.00001; anodised titanium and pearl paints 0.00001; a flint prism and a diamond 0.00000; a rough prism 0.00007. On llvmpipe GL: bubbles 0.00001, the prism 0.00000. Program evaluation alone, compared value by value with the CPU interpreter over 77 programs, agrees within 1.4e-5 except bump through cylindrical and spherical projections, where finite-difference heights make the CPU itself move by more for a one-ulp change of the hit. + The residual sits on the horizon rows: last-bit rounding of near-horizontal camera rays, and with ray queries the shadow catcher's grazing occlusion probes. A change to sampling, lights or materials lands on the CPU first and is then ported. ## Bind groups @@ -34,15 +36,15 @@ Twelve bindings in at most three groups. The scene and film groups use exactly 8 | Group | Binding | WGSL | Element | Holds | | --- | --- | --- | --- | --- | -| 0 | 0 | `var frame: Frame` | 288 B | camera, film, settings, counts, offsets and the render region | +| 0 | 0 | `var frame: Frame` | 304 B | camera, film, settings, counts, offsets, the render region and the texture directory offset | | 0 | 1 | `var sobol: Sobol` | 8192 B | Sobol direction numbers, 64 dimensions by 32 bits | | 0 | 2 | `var nodes: array` | 32 B | top level, then every mesh's nodes | | 0 | 3 | `var tris: array` | 48 B | object-space corners in leaf order | -| 0 | 4 | `var verts: array` | 16 B | authored vertex normals | +| 0 | 4 | `var verts: array` | 16 B | per-vertex attribute slots: authored normals, and uv sets and tangents of meshes that run a material program | | 0 | 5 | `var instances: array` | 128 B | placed instances | -| 0 | 6 | `var materials: array` | 144 B | surface parameter records | +| 0 | 6 | `var materials: array` | 160 B | surface parameter records with program offsets, thin film and dispersion | | 0 | 7 | `var lights: array` | 96 B | lamps, sun and the emissive group | -| 0 | 8 | `var tables: array` | 4 B | environment, BSDF energy and emissive tables | +| 0 | 8 | `var tables: array` | 4 B | environment, BSDF energy, textures, material programs and emissive tables | | 1 | 0 | `var band: Band` | 48 B in a 256 B slot | the band and the adaptive settings | | 1 | 1 | `var accum: array` | 64 B | the band's running sums | | 2 | 0 | `var tlas: acceleration_structure` | | ray-query variant only | @@ -53,7 +55,7 @@ Every buffer holds at least one zeroed element. Counts come from the Frame, neve Offsets are in bytes; `vec3` fields take 12 bytes and share their 16-byte row with the scalar after them. -**Frame (288).** +**Frame (304).** | Offset | Fields | | --- | --- | @@ -75,6 +77,7 @@ Offsets are in bytes; `vec3` fields take 12 bytes and share their 16-byte row wi | 240 | bsdf_cond, bsdf_cond_avg, bsdf_diel, bsdf_sheen (float offsets into `tables`) | | 256 | flags (bit 0 BSDF tables present, bit 1 acceleration structure bound, bit 2 adaptive sampling on, bit 3 render region on), revision, samples, pass_index | | 272 | region_x0, region_y0, region_x1, region_y1 (film pixels; with flag bit 3, pixels outside return at once) | +| 288 | textures (float offset of the texture directory in `tables`, NONE when the scene samples no texture), pad0, pad1, pad2 | The first 76 bytes are the camera block: a camera move writes only those. Camera values are derived exactly as the CPU's `CameraModel` derives them. @@ -82,7 +85,16 @@ The first 76 bytes are the camera block: a camera move writes only those. Camera **Triangle (48).** c0, i0, c1, i1, c2, i2: object-space corners with each corner's vertex index within its mesh (for normals, `verts[instance.vertex_base + i]`). With a 16-byte stride, `tris` doubles as the vertex buffer of the ray-query structures. -**Vertex (16).** normal (vec3), pad. Meshes without authored normals have `vertex_base` NONE and use the geometric normal, as on the CPU. +**Vertex (16).** One attribute slot, `v: vec4`. A mesh owns `stride * vertex_count` slots from its instance's `vertex_base`, vertex i at `vertex_base + i * stride`, and the instance flags say which slots exist, in this order: + +| Slot | Present when | Holds | +| --- | --- | --- | +| normal | flag bit 3 (`INST_NORMALS`) | authored normal xyz, 0 | +| uv sets 0 and 1 | uv set count (flags bits 4 to 6) at least 1 | (u0, v0, u1, v1) | +| uv sets 2 and 3 | uv set count at least 3 | (u2, v2, u3, v3) | +| tangent | flag bit 7 (`INST_TANGENTS`) | tangent xyz, handedness sign | + +Uvs are packed as the mesh stores them (v up). Uv sets and tangents are packed only for meshes worn by an instance whose material program is not constant, so a scene without programs keeps one slot per vertex with authored normals and none without; a mesh with normals, one uv set and tangents takes three. Meshes with no slots have `vertex_base` NONE and use the geometric normal, as on the CPU. **Instance (128).** @@ -91,9 +103,9 @@ The first 76 bytes are the camera block: a camera move writes only those. Camera | 0 | world: three vec4 rows of local to world (w is the translation) | | 48 | inv: three vec4 rows of world to local | | 96 | tint (vec3, valid with flag bit 2), material | -| 112 | root (absolute mesh root node, NONE for an empty mesh), vertex_base, mask (camera 1, shadow 2, diffuse 4, glossy 8, transmission 16), flags (bit 0 flips handedness, bit 1 in the top tree, bit 2 has tint) | +| 112 | root (absolute mesh root node, NONE for an empty mesh), vertex_base, mask (camera 1, shadow 2, diffuse 4, glossy 8, transmission 16), flags (bit 0 flips handedness, bit 1 in the top tree, bit 2 has tint, bit 3 authored normals, bits 4 to 6 uv set count 0 to 4, bit 7 tangents) | -**Material (144).** The sanitized surface inputs of `fsh-materials`: base colour and weight, specular colour, metalness, transmission colour, diffuse roughness, coat colour, specular weight, fuzz colour, specular roughness, emission (already in scene units), specular ior, anisotropy, transmission weight, coat weight and roughness, coat ior, fuzz weight and roughness, opacity, then thin_walled, eta, program (reserved for bytecode materials) and flags. The records are the snapshot's materials, then the default material, then the ground. +**Material (160).** The constant block of the material's compiled program (`program.base`, which for a material without slots, graph or labels equals the sanitized parameters), as the sanitized surface inputs of `fsh-materials`: base colour and weight, specular colour, metalness, transmission colour, diffuse roughness, coat colour, specular weight, fuzz colour, specular roughness, emission (already in scene units), specular ior, anisotropy, transmission weight, coat weight and roughness, coat ior, fuzz weight and roughness, opacity, then thin_walled, eta, program (the float offset in `tables` of the material's encoded program, NONE for a constant or refused program) and flags (bit 0 `MAT_PROGRAM`: run the program), then at 144 to 160 film_weight, film_thickness (micrometres), film_ior and dispersion (the Cauchy slope; 0 for none), written from the material's parameters, never by a program. Materials that share one program share one blob. The records are the snapshot's materials, then the default material, then the ground. **Light (96).** kind (0 rectangle, 1 disc, 2 point, 3 sphere, 4 spot, 5 directional, 6 sun, 7 the emissive group), flags (camera, specular, lights surfaces, shadows, two-sided), prob and cdf (the CPU's selection table), then emission and area, position and radius, u and cos_inner, v and cos_outer, normal and importance. @@ -103,24 +115,28 @@ The first 76 bytes are the camera block: a camera move writes only those. Camera ## The tables buffer -One `array` holds three blocks, each found through Frame offsets: +One `array` holds five blocks in this order, each found through Frame or material offsets. All integers stored in it are exact floats below 2^24. | Block | Contents | | --- | --- | | Environment | pixels (width by height by 3, row 0 at the zenith, before the scale), the luminance function, the row CDFs (width + 1 per row) and the marginal (height + 1) | | BSDF energy | a 16-word header (magic "FSBT", version 1, dimensions, offsets), then conductor `[32 roughness][32 mu]`, its average `[32]`, dielectric `[2 sides][16 eta][32 roughness][32 mu][reflect, transmit]` and sheen `[16 roughness][32 mu]`: 67,120 floats | +| Textures | at `Frame.textures` = D, offsets inside relative to D: `[N, lut, 0, 0]`; N records `[levels, colour space (0 srgb, 1 linear, 2 acescg, 3 data), storage (0 rgba8, 1 rgbaf32, 2 opaque rgb8), first level record]`; level records `[width, height, texel offset >> 16, texel offset & 0xffff]`; the 256 floats of the sRGB decode table; texels, rgba8 as two floats `r + 256 g` and `b + 256 a`, rgbaf32 as four, and storage 2 (an 8-bit image whose alpha is 255 in every level) as one float `r + 256 g + 65536 b`, which halves the memory of opaque images (three Khronos samples that the 128 MiB binding of lavapipe refused now fit). A missing image, or one whose first level is malformed, has 0 levels and samples the fallback; levels after a malformed one are left out, as on the CPU. The block is the engine's `TextureSet`, in the snapshot's texture order, packed by `texpack.rs` | +| Programs | each non-constant material's `Program::encode_f32()` blob (see [`MATERIALS.md`](MATERIALS.md)), pointed at by its record's `program` | | Emissive | a header (count and offsets), the triangle CDF, 20-float records (three corners, normal, area, emission, probability, instance, slot, two-sided) and per-instance slot maps | +`GpuRenderer::set_textures(Option)` repacks the texture block and resets the film; a material edit rewrites the program blobs; an environment change moves every later offset and so rewrites the material records; a change in which meshes need uv sets rebuilds geometry. + ## Shader modules -Twenty-one WGSL files live in `src/shaders/`, embedded into the binary and assembled by an `#include "file"` preprocessor (include once, `enable` lines hoisted to the top). During development `RendererOptions::shader_dir` loads them from a folder without rebuilding. +Twenty-four WGSL files live in `src/shaders/`, embedded into the binary and assembled by an `#include "file"` preprocessor (include once, `enable` lines hoisted to the top). During development `RendererOptions::shader_dir` loads them from a folder without rebuilding. | Module | Holds | | --- | --- | | `bindings.wgsl` | constants, every struct, groups 0 and 1, run-time infinity, mask and instance helpers | | `bindings_hw.wgsl` | `enable wgpu_ray_query;` and group 2 | | `math.wgsl` | pure helpers with no bindings: NaN-safe min, max and clamp, an accurate `sin_cos`, frames, warps, MIS heuristics, ray offset | -| `features.wgsl` | the override constants `USE_LAMPS`, `USE_CATCHER`, `USE_NORMALS` | +| `features.wgsl` | the override constants `USE_LAMPS`, `USE_CATCHER`, `USE_NORMALS`, `USE_PROGRAMS` | | `sampler.wgsl` | the sampler, bit-identical to `fsh-core` | | `traverse_common.wgsl` | slab test, watertight triangle test, ray validity, world normal | | `traverse_sw.wgsl` | the software two-level BVH traversal with an ordered 64-entry stack | @@ -128,12 +144,15 @@ Twenty-one WGSL files live in `src/shaders/`, embedded into the binary and assem | `trace.wgsl`, `trace_hw.wgsl` | one-line indirections; the assembler swaps one for the other to make the hardware kernel | | `camera.wgsl` | pixel filters, pinhole, thin lens and orthographic rays | | `env.wgsl` | environment evaluation, pdf and sampling | -| `surface.wgsl` | ray spawning, hit points, shading normals, tinted inputs, counted traces | +| `surface.wgsl` | ray spawning, hit points, shading normals from the strided vertex slots, `hit_ctx` and `shade_inputs` (the program, then the tint), counted traces | +| `texture.wgsl` | `tex_sample`: the texture directory, nearest, bilinear and trilinear filtering, repeat, clamp and mirror, the sRGB table, primaries to ACEScg | +| `procedural.wgsl` | the ten procedural patterns, with the CPU's integer hashing | +| `program.wgsl` | `HitCtx`, `run_program` over opcodes 0 to 24 (24 is the label projection), polynomial `atan2` and `acos` so projections do not depend on driver precision, `sanitize_inputs` | | `lights.wgsl` | every lamp kind, emissive triangles, light choice | | `catcher.wgsl` | the shadow catcher's sampler dimensions | -| `bsdf_tables.wgsl`, `bsdf.wgsl` | the energy-table lookups and the layered surface BSDF | -| `integrator.wgsl` | `path_sample`, the port of the CPU's path loop | -| `kernel.wgsl` | the megakernel entry (about 3,400 lines once assembled) | +| `bsdf_tables.wgsl`, `bsdf.wgsl` | the energy-table lookups and the layered surface BSDF, with the thin-film Fresnel (`bsdf_add_film`) | +| `integrator.wgsl` | `path_sample`, the port of the CPU's path loop, with ray-cone footprints and the dispersion hero channel | +| `kernel.wgsl` | the megakernel entry (about 4,350 lines once assembled for software traversal, 4,268 for ray queries) | | `adaptive.wgsl` | the adaptive-sampling pass that retires and revives pixels | | `plumbing.wgsl` | the first placeholder kernel, kept as a minimal smoke test | @@ -143,12 +162,16 @@ Rules for kernel authors: never write an infinity, a NaN or the largest float as ## Specialisation and kernel cache -The three override constants switch off the code for lamps, the shadow catcher and authored normals when a scene does not need it. Adaptive sampling is not a constant: the kernel skips retired pixels when the Frame's adaptive flag is set, so switching adaptive sampling on or off never compiles a kernel. The renderer keeps up to four compiled variants. `RendererOptions::features` asks for at least a set of features (`Features::NONE` means exactly the scene's own variant); by default the native renderer builds the scene's variant and the window uses the variant with everything on. A scene change uses the renderer's own variant or a kept one that covers the scene. Natively a missing variant is compiled when the scene changes; on WebAssembly, when no kept kernel covers the scene, the pass returns a shader error before any dispatch instead of drawing a wrong picture, `needs_specialise()` says so, and `specialise_async()` compiles the missing variant (it works on any target). The window does not call it yet. Where the driver offers a pipeline cache (Vulkan yes, OpenGL no) compiled kernels are kept on disk, keyed by adapter, driver, WGSL hash and constants. +The four override constants switch off the code for lamps, the shadow catcher, authored normals and the material program interpreter (`USE_PROGRAMS`, on when some material record has `MAT_PROGRAM`) when a scene does not need it; the thin-film code has no constant and is in every kernel. Adaptive sampling is not a constant: the kernel skips retired pixels when the Frame's adaptive flag is set, so switching adaptive sampling on or off never compiles a kernel. The renderer keeps up to four compiled variants. `RendererOptions::features` asks for at least a set of features (`Features::NONE` means exactly the scene's own variant); by default the native renderer builds the scene's variant and the window uses the variant with everything on. A scene change uses the renderer's own variant or a kept one that covers the scene. Natively a missing variant is compiled when the scene changes; on WebAssembly, when no kept kernel covers the scene, the pass returns a shader error before any dispatch instead of drawing a wrong picture, `needs_specialise()` says so, and `specialise_async()` compiles the missing variant (it works on any target). The window does not call it yet. Where the driver offers a pipeline cache (Vulkan yes, OpenGL no) compiled kernels are kept on disk, keyed by adapter, driver, WGSL hash and constants. ## Render region `GpuRenderer::set_region` takes a rectangle in output pixels (or none) and maps it through the resolution scale onto the film; with the Frame's region flag set, kernel invocations outside it return at once. Samples are kept when a region is set or cleared, the whole picture is still developed, and the statistics (samples, fewest, most, converged fraction) count only the region's pixels, so clearing a region lets adaptive sampling carry on over the rest of the film. The engine's `render.region` takes fractions of the image and keeps the region across device and preview-size changes; the CPU engine has no region pass yet and answers so in `region_note`. On lavapipe at 320x240 a region pass over a sixth of the image took 0.116 s against 1.137 s for the full film, and the pixels inside were bit-identical to a full-film render at the same samples. +**Region resets after an edit.** A different thing from the render region: when a material edit changes only some parts, `GpuRenderer::update_region(snapshot, instances, pad)` applies the new snapshot without a reset and clears only the first-hit rectangle of those instances (padded by 6 pixels), keeping the samples everywhere else, as the CPU engine does; it answers none when only a full reset will do. The engine uses it for every Region-level change, `library.apply` and assigning a new material included. On the product template at 320 by 240, applying a gold preset to one band cleared 5,600 of 76,800 pixels on both engines, the same rectangle, and every changed pixel lay inside it. + +**Bent normals.** Like the CPU, the integrator bends a normal that a material program changed just enough that the mirror reflection stays 0.01 above the geometric horizon (`clamp_bent_normal`), so steep normal maps no longer leave black rims on polished metal. + ## Traversal choice `RendererOptions::traversal` is automatic, software or hardware, and the environment variable `FORMSHOT_GPU_TRAVERSAL` (software, hardware or auto) overrides it. Automatic picks ray queries when the device was opened with them, binds a third group with an acceleration structure, and the structures build. Hardware structures are one bottom-level structure per unique mesh, built straight from `tris`, and one top-level instance per placed instance with its world rows, its index as the custom index and its ray mask. After a closest hit the software path's watertight test is re-run on the committed triangle, so hit distances and barycentrics come out bit-identical to the software path. A transform or material change rebuilds only the top level; a changed mesh builds only its own bottom level. A missing feature, a failed build or a kernel that does not compile drops to the software traversal with a one-line reason; traversal never sends a job to the CPU. WebAssembly always uses the software traversal, since WebGPU offers no ray queries. @@ -159,8 +182,8 @@ Before anything is uploaded, `Refusals::check` compares the scene with the adapt | Kind | Codes | Effect | | --- | --- | --- | -| Limit | resolution, nodes, triangles, vertices, instances, materials, lights, frame_width, frame_size, bvh_depth, environment_size | the GPU cannot hold the job; it renders on the CPU | -| Feature | adaptive_bands (adaptive sampling on a film larger than one binding) | the GPU picture would differ from the CPU's; the job renders on the CPU | +| Limit | resolution, nodes, triangles, vertices, instances, materials, lights, frame_width, frame_size, bvh_depth, environment_size, texture_memory (the tables block with the textures would pass the largest storage binding; raised at upload or by `set_textures`, which keeps the old pixels) | the GPU cannot hold the job; it renders on the CPU | +| Feature | adaptive_bands (adaptive sampling on a film larger than one binding); material_program (a material in use whose program fails its checks, needs more than 32 registers, uses an opcode outside `GPU_OPCODES` or a procedural outside `GPU_PROCEDURALS`, or reads a uv set past 4; such programs are not uploaded) | the GPU picture would differ from the CPU's; the job renders on the CPU | The engine session in `fsh-commands` then applies a ladder, and every rung leaves a plain note in `render.status`, in the reply to `render.set_device` and in the command line's output: diff --git a/docs/IMPORT.md b/docs/IMPORT.md new file mode 100644 index 00000000..88ba0f2f --- /dev/null +++ b/docs/IMPORT.md @@ -0,0 +1,106 @@ +# Import, CAD and family hand-offs + +This page describes how a model gets into a FormShot document: the formats read, the options, units and axes, background jobs, re-import, textures, STEP and IGES through FormCAD's kernel worker, and what the other Form apps hand over. The code is in `native/crates/fsh-io` (readers, clean-up, `family/`), `native/crates/fsh-cad`, `native/crates/fsh-commands/src/ext/` (`import.rs`, `import/`, `cad.rs`, `handoff.rs`), `backend/app/routers/` (`imports.py`, `cad.py`, `handoff.py`) and `frontend/src/ui/` (`import/`, `cad/`, `handoff/`). The rationale and what ran are in the HASHOUT logs beside that code. + +## Formats + +| Format | Extensions | Reader | Notes | +| --- | --- | --- | --- | +| glTF, GLB | .gltf, .glb | fsh-io | materials with texture slots, KHR_texture_transform and the material extensions listed below; tangents kept | +| OBJ with MTL | .obj | fsh-io | `o` and `g` groups become nodes, one part per `usemtl`; polygons ear-clipped; MTL maps become slots | +| STL | .stl | fsh-io | binary facet colours (VisCAM/SolidView and Materialise conventions) become vertex colours | +| PLY | .ply | fsh-io | polygons ear-clipped; vertex colours | +| 3MF | .3mf | fsh-io (roxmltree, own ZIP reader) | unit from the file, Z up, build items and components, base materials, colour groups, composites, texture groups, multiproperties (first layer) | +| FBX | .fbx | fsh-io on ufbx, desktop engine only | the file's unit, Y up after conversion, Lambert, Phong and PBR materials, texture slots, embedded images; not in the browser engine | +| STEP | .step, .stp | fsh-cad through FormCAD's kernel worker | assemblies, body colours, face colours read from the file, shared shapes | +| IGES | .iges, .igs | fsh-cad through the worker | solid colours and names read from the file | + +Detection looks at content first (3MF a ZIP holding a `.model` part, FBX its binary magic or `FBXHeaderExtension`, STEP `ISO-10303-21;`, IGES an `S` in column 73), then the extension. Not read: 3MF slice, beam lattice, volumetric and boolean extensions; FBX NURBS, skins, blend shapes, cameras, lights and animation (reported as warnings); STEP PMI and layers. + +## Options + +`file.import {path, ...}` (and `import.start`, and `file.open` of a model) takes: + +| Option | Values | Default | +| --- | --- | --- | +| `name` | the name of the imported top node | the file's stem | +| `units` | auto, mm, cm, m, in, ft | auto: declared by the file, else guessed | +| `up_axis` | auto, y, z | auto: declared by the format | +| `stand_on_floor` | stand the model on the ground | true | +| `center` | move the footprint's centre to the origin | false | +| `frame` | frame the camera on the result | when the scene had no parts | +| `merge` | put everything under one group | false (several roots get a wrap group) | +| `cad_quality` | draft, medium, high, ultra, or `{chord, angle}` | medium | +| `options` | the older clean-up object (`unit`, `up_axis`, `centre`, `stand_on_floor`, ...) | read first; top-level names win | + +Calls written for earlier engines keep working and give the same documents, apart from the new source metadata. The window's import sheet remembers up axis, the switches and the CAD quality in the browser, and defaults units to the probed unit with a warning when it was guessed. + +## Units and axes + +Every reader's result goes through one clean-up pass: validate, weld, normals (area weighted, 30 degrees), MikkTSpace tangents where a mesh has uvs and normals but no tangents, repeated parts found (also rotated or mirrored copies, matched through the shared triangle list), units, up axis (one linear map, local transforms conjugated), then floor and centre on the root transforms only. + +A unit comes from the option, else the file (3MF always declares one; FBX gives its scale; glTF is metres; STEP and IGES read through the worker in millimetres), else a guess from the bounding-box diagonal: under 0.5 the file is taken as metres, under 50 as centimetres, else millimetres. The guess carries a confidence (0.5 at a threshold, rising to 0.95 one decade away) and candidate units that give a 5 mm to 20 m object. A guessed unit is reported (`unit_guessed`), and the sheet says so, because a 1.2 m model is guessed as centimetres. + +`import.probe {path}` answers what a file holds without changing the document: format, declared and guessed units, up axis, bounds in file units and in metres at the guessed unit, triangles, meshes, nodes, materials, textures, images in the file, texture slots and warnings. For STEP and IGES it reads the header (schema, writing system, declared unit, entity counts) and, when the worker is installed, opens the file without tessellating (bodies, groups, faces, colours); triangles and meshes are then null. + +## Where nodes came from + +Every imported node records its origin in its metadata: `source.path` (the absolute file) and `source.node` (its path inside the file, names joined by `/`). The import's top nodes also hold `source.options` (the geometry options with the resolved unit and up axis), so a re-read cannot flip a unit guess. Parts whose mesh keeps vertex colours carry `material.vertex_colours = multiply`; masked glTF materials put their cutoff in `material.alpha_cutoff`. [`FILE-FORMAT.md`](FILE-FORMAT.md) lists every key. + +## Jobs + +`file.import` imports at once. `import.start` runs the read and the clean-up on a worker thread and answers `{job}` at once; the document changes on the first engine call after the worker finishes, as one undo step and one journal command, and never while a history group is open (stage `waiting`). `import.status {job}` answers `{job, state, stage, fraction, path, seconds, result?, error?}` with state running, done, failed, cancelled or stale; without `job` it lists this engine's jobs. `import.cancel {job}` stops it (a CAD job kills the worker) and the document stays exactly as it was. Opening, creating, closing or recovering a document while a job runs cancels it and marks it stale. Jobs belong to their engine session and end with it. + +## Re-import + +`file.reimport {nodes?}` reads the source files of the given imported nodes again (every imported node when none is given), with the options stored on their top nodes. Parts match by `source.node`, then by a name unique on both sides, then by a shape unique on both sides, so a part renamed in the file keeps its material. Matched parts keep their transform and material (and every slot edit), take the file's name only if the person had not renamed them, and get the new mesh in place (their ids stay); parts new in the file arrive; parts gone from the file are hidden and marked `source.missing`, and come back when they return. CAD files are re-read at the quality their parts carry now. One undo step. A texture whose image changed in the source is not refreshed on matched parts. A missing source file is an error for that file only. A model uploaded from a browser is kept in `/.imports//` for this, and the service removes upload folders after 24 hours without changes; re-import of those parts then reports the source as missing. + +## Textures + +Readers turn each material's maps into texture slots ([`MATERIALS.md`](MATERIALS.md)), with uvs stored v up: + +- **glTF.** baseColorTexture to base_color (multiplied by the factor), metallicRoughness to specular_roughness (g) and base_metalness (b), normal (with its scale), emissive (times emissive_strength), alpha in BLEND mode to geometry_opacity (soft coverage), and in MASK mode a hard cutoff: a MASK material with an alpha texture gets a small graph driving geometry_opacity with `clamp((alpha * factor - cutoff + 1e-4) * 1e4, 0, 1)`, so coverage is 0 or 1 at the cutoff in both tracers (an untextured MASK material is simply 0 or 1), texCoord sets, KHR_texture_transform, sampler wrap and filters. Extensions read: clearcoat, transmission, ior, specular, sheen, volume, iridescence, dispersion, anisotropy (strength), emissive_strength. Occlusion and inputs without a slot (transmission, specular colour, sheen, clearcoat normal, thickness, iridescence) are recorded on the material only. +- **MTL.** map_Kd, map_Ks, map_Ns (inverted), map_Pr, map_Pm, bump, norm, map_d, map_Ke and disp, with -o, -s, -clamp, -bm and -imfchan. +- **3MF.** texture2d parts with their tile style and filter, as a base_color slot. +- **FBX.** base colour, roughness or glossiness, metalness, normal, emission, specular, bump, displacement and opacity maps, UV sets by name, the texture transform and embedded content. + +The import then reads each image it can find (beside the model or inside it: GLB buffers, data URIs, 3MF parts, FBX content) and embeds PNG, JPEG, Radiance HDR and OpenEXR files in the project as `fshot:textures/.`, once per distinct content. Other formats (WebP, KTX2, DDS, GIF, BMP, TIFF) are skipped and their slots dropped; files above 256 MiB stay referenced by path; missing files and files outside the model's folder keep their reference and sample the slot's fallback. The reply's `textures` block lists what was embedded, referenced, missing and skipped. Both path tracers sample these textures; how they are loaded and filtered is in [`MATERIALS.md`](MATERIALS.md). + +## CAD: STEP and IGES + +STEP and IGES are opened by FormCAD's kernel worker (OpenCascade), a separate program FormShot starts and talks to in JSON lines; the engine never downloads anything. + +**Getting the worker.** `./formshot cad fetch` (or Download in Preferences > CAD Import, or the line under the import sheet's CAD row) downloads release `occt-8.0.1` from FormCAD's published binaries, checks a record pinned by SHA-256, the archive against `SHA256SUMS` and every unpacked file against the record, and installs it in `/formshot/workers/occt-8.0.1/` (`FORMSHOT_CACHE`, else `~/.cache`, `~/Library/Caches` or `%LOCALAPPDATA%`). `./formshot cad status` and `cad.status` say whether it is there. The engine looks in `FORMSHOT_CAD_WORKER` first, then beside the program, then in the cache. `FORMSHOT_CAD_RELEASE_URL` points the download at a mirror; `FORMSHOT_CAD_TIMEOUT` sets the per-request timeout (600 s by default) and `FORMSHOT_CAD_HELLO_TIMEOUT` how long a starting worker may take to answer (120 s by default). + +**Quality.** Chord is the largest distance between a triangle and the surface, as a fraction of the model's bounding-box diagonal; angle is in degrees. + +| Preset | Chord | Angle | +| --- | --- | --- | +| draft | 0.002 | 30 | +| medium | 0.0005 | 20 | +| high | 0.00015 | 12 | +| ultra | 0.00005 | 6 | +| custom `{chord, angle}` | above 0, at most 0.1 | 1 to 90 | + +**What arrives.** Assembly groups and one part per body, in metres, Z up converted like any other file; one material per colour; bodies that are the same shape share one mesh. The worker reports body colours for STEP; FormShot reads STEP face colours and IGES solid colours and names from the file itself and applies them when they can be matched to the bodies, with a warning otherwise. Parts carry `source.cad`, `cad.mesh`, `cad.quality`, `cad.unit` and `cad.up`. The file is kept in the project under `sources/` (up to 64 MiB) and in the crash journal; a save writes only the sources some part still names. `cad.parts {nodes?}` lists the CAD parts with their source, quality, unit and up axis. + +**Tessellating again.** `scene.retessellate {nodes?, quality}` (Scene > Re-tessellate CAD Parts) rebuilds the meshes of CAD parts from the kept source at another quality, as one undo step; each part keeps its id, name, placement, material, visibility and selection, and shared meshes stay shared. Locked parts are skipped. It runs while you wait (no progress, no cancel). + +**Limits.** The worker sends no progress inside the open or one body's tessellation, no face colours, no IGES colours and no instance matrices; FormShot works around the colours and derives sharing by matching tessellations. Only tested on Linux x86_64. + +## Hand-offs from the other Form apps + +| App | What it writes | How FormShot takes it | +| --- | --- | --- | +| FormSculpt | GoF: `.glb`, `.obj` or `.fbx` in its watched folder with a `gof.json` manifest | the GoF folder is watched; entries for `any` (or a future `formshot` target) are offered | +| FormFabric | GoF entries from `formfabric.gof.send`; glTF, GLB and OBJ exports | as FormSculpt; models through the usual readers | +| FormSurface | `/exports//_.` map folders, in its own names or one of twelve templates, texture sets and UDIM tiles, and a `# FormSurface` OBJ | its export folder is watched; maps become document textures with roles and colour spaces on the matching materials | +| FormCAD | GLB with its title and design unit, 3MF, STEP | as models (the title and design unit are recorded); STEP through the CAD worker | + +The service scans the GoF folder (`FORMSHOT_HANDOFF_GOF`, `FORMSCULPT_GOF` or `~/Formsculpt/GoF`) and FormSurface's exports (found from `FORMSHOT_HANDOFF_SURFACE`, `FORMSURFACE_DATA`, FormSurface's running service, or `~/FormSurface`) every 2 s while the window is open. Nothing that was there before the first scan is offered. Each arrival is held: the window asks Decline, Open once or Always allow , and whether to add it to this document or open it as a new one; per-app choices (ask, always, block) are in Preferences > Hand-offs. File > Open a Hand-off lists everything in both places. `handoff.inspect {path, item?}` says what a file or folder is and holds; `handoff.open {path, item?, as}` brings it in as one undo step, recording `source.app` and the other hand-off keys. Outside agents use the same commands through MCP, under the same consent as every other change. + +Files given to FormShot when it starts (by the system or by FormPortal) arrive as `formshot://open-paths`: a `.fshot` opens, models go to the import sheet. Folders given that way are not routed yet. + +## In the window + +File > Import Model (Mod+I), a drop on the viewport or on Home, or Open a Hand-off. In a browser, files are uploaded to `/api/imports` with their sibling files (glTF buffers and images, OBJ's MTL and maps); on the desktop the real path is used. The sheet shows the probe, the options and the progress of the job; Import All applies the options to the rest of a multi-file drop. File > Reimport reads the selection's sources again; File > Recent Imports reopens one of the last eight. diff --git a/docs/LIBRARY.md b/docs/LIBRARY.md new file mode 100644 index 00000000..3123d32c --- /dev/null +++ b/docs/LIBRARY.md @@ -0,0 +1,91 @@ +# The material library + +FormShot ships a library of 249 material presets made from measured and published physical data, with commands to list, search, apply and save them, CPU-rendered thumbnails, and a panel in the window. The presets are in `assets/library/`, the commands in `native/crates/fsh-commands/src/ext/library.rs` and `ext/library/`, the thumbnail route in `backend/app/routers/library.py` and the panel in `frontend/src/ui/library/`. [`assets/library/README.md`](../assets/library/README.md) is the presets' own description; the rationale is in the HASHOUT logs. + +## Format + +``` +assets/library/ + README.md sources, licences, how presets were made + materials/ + index.json every preset, generated + /.json one preset per file +``` + +The twelve categories, in the window's order, with their counts: Metal 73, Plastic 37, Glass 17, Paint 22, Rubber 9, Fabric 13, Wood 10, Stone 10, Ceramic 10, Liquid 17, Gem 22, Emissive 9. The folder is the category in lower case. The whole tree is about 408 KB and must stay under 2 MB. + +A preset file is UTF-8 JSON with two-space indentation, keys in this order: + +| Field | Meaning | +| --- | --- | +| `format` | always `formshot-material-preset`; any other value is refused | +| `version` | 1; a reader refuses versions it does not know | +| `id` | `/`, equal to the file's path below `materials/` without `.json`; slugs are `[a-z0-9]+(-[a-z0-9]+)*`, at most 48 characters. Never reused or renamed: favourites, thumbnails and documents refer to it | +| `name` | plain English, unique within its category, sentence case with the finish after a comma ("Steel, brushed"); data, not a translated string | +| `category` | one of the twelve, matching the folder | +| `type` | a material type id ([`MATERIALS.md`](MATERIALS.md)); it becomes the material's type | +| `params` | surface parameters by `SurfaceParams` field name; an unknown key is an error | +| `tags` | at most 8 from a fixed vocabulary (finish, optics, colour family, substance, use, and the flags `needs-graph` and `synthetic`) | +| `source` | `kind` (measured, published or authored), `reference`, `urls`, `notes`, and `authored` (the parameters chosen by us rather than measured) | +| `licence` | the SPDX id of the file: `Apache-2.0` for every preset in the repository; `NOASSERTION` for the user's own | + +Colours are scene-linear ACEScg (converted with fsh-core's linear-sRGB matrix, 8-bit sRGB decoded first). Ranges are those of `SurfaceParams::validate`. `emission_color` is normalised to ACEScg luminance 1, so `emission_luminance` is the surface's real luminance in nits (a channel may exceed 1). Numbers are rounded to 4 decimal places. Format 1 presets store the full value of every field that defines their look, so they do not depend on later changes to type defaults; they carry no graph and no slots. + +`index.json` (`format: formshot-material-index`, `version`, `count`, `categories` with counts, `presets` with id, name, category, type, tags, file and the SHA-256 of the file's bytes) is generated, sorted by category then name. The generator and the validator are kept outside the repository; a preset added by hand needs its index entry with the file's SHA-256 in the right place. + +## Sources and licences + +Every preset is our own work under Apache-2.0, written from public data; no preset, name or description comes from another renderer's library. Only numbers are taken from these sources: + +| Source | Used for | Licence | +| --- | --- | --- | +| refractiveindex.info database (M. N. Polyanskiy, Sci. Data 11, 94, 2024), commit e6d15e364f70de1cad8a96a20f75689f2fba8b21 | n and k of metals and alloys; n and dispersion of glasses, polymers, liquids and crystals; absorption of water and window glasses. Each preset cites the original paper and the file URL at that commit | CC0 1.0 | +| CIE 1931 2 degree colour matching functions and illuminant D65, as tabulated in colour-science | turning spectra into colours (not stored) | CIE standard data; package BSD-3-Clause | +| USDA AMS Sucrose Conversion Table (Appendix XV) | refractive index of sugar solutions | US government work | +| MFA Boston CAMEO gemstone table; GIA Gem Encyclopedia (emerald); LibreTexts Gemology (beryl); orders of magnitude of luminance | refractive indices, dispersion and lamp and display luminance | facts cited | + +**Metals.** n and k are interpolated from 380 to 780 nm in 5 nm steps; the unpolarised Fresnel reflectance is integrated against the CIE 1931 functions under D65 at normal incidence (the base colour, F0) and at 82 degrees (cosine 1/7); `specular_color` is the F82 tint of the OpenPBR metal model, the ratio of the true 82-degree reflectance to the Schlick curve through F0. The fit error of the model against the exact reflectance is 0.0016 (silver) to 0.042 (red brass) over 50 angles. Data sets that give normal reflectances far above handbook values or do not cover the visible range were rejected. + +**Dielectrics.** `specular_ior` is n at 587.6 nm and the Abbe number `(nd - 1) / (nF - nC)`; for gems quoted with a B-G dispersion, `nF - nC = 0.5845 (nG - nB)` from Cauchy's two-term law. Water and window glasses get a Beer-Lambert transmission colour at their stated depth. Anodised titanium uses the Airy reflectance of a TiO2 film on titanium at six thicknesses. + +**Authored.** Finish roughness, dye and pigment colours (given as 8-bit sRGB in the notes), coat settings, subsurface parameters, some polymer and liquid IORs and a few luminances are our choices, listed in each preset's `source.authored`. + +**Thin film and graphs.** Six anodised titanium and two pearl paint presets use thin film, which both path tracers now render (the film colours match the preset names: bronze, violet, blue, light blue, gold, magenta). Wood, stone and metallic paint presets are tagged `needs-graph`: their look comes from their type's procedural graph, which applying gives them and both tracers run. Graph thumbnails were rendered and looked at for all 28 `needs-graph` presets: metallic paints read as their own colours (red, silver, pearl white, champagne, black, gunmetal, blue, pearl blue), marbles show veins and the other stones mottling; wood presets read as flat tones at 128 px, because their rings (250 per metre) are finer than a pixel on the 1 m ball and the anti-aliasing shows their mean. + +## Finding the library + +The engine looks in order at `FORMSHOT_LIBRARY` (which must hold `materials/index.json`), then the app's bundled resources (`../Resources/library` on macOS; `library` or `resources/library` beside the program on Windows; `../lib/FormShot/library`, `$APPDIR/usr/lib/FormShot/library` or `/usr/lib/FormShot/library` on Linux), then `assets/library` in any folder above the program (development). The desktop bundle carries `assets/library/materials` as the resource `library/materials`; the desktop shell sets `FORMSHOT_LIBRARY` to `/library` for the service when the person has not set it and the bundled index exists, and when the service runs frozen with the variable still unset it finds that folder from its own executable and sets it for the engine. + +The index is checked against every file: a missing file, a file whose hash, fields or JSON disagree with the index, or a file the index does not list is one warning in `library.list` and the preset is left out (a hash mismatch alone keeps the preset). Reading is strict: unknown keys and unknown params are refused with the preset named, and the built parameters must pass `validate()`. Nothing in a bad library crashes or touches the document. + +## Commands + +All are engine commands, listed in the catalogue with schemas, so the window, the command line, MCP and Python get the same behaviour. Ids are `/` for built-in presets and `user/` for the user's own. + +| Command | Answer | +| --- | --- | +| `library.list {category?, query?, shelf?, limit?, offset?}` | `{root, origin, shelf, total, count, offset, categories, presets, warnings}`. Shelf all, favorites, recent or user. A query matches every word against name, tags, category or type, ignoring case and accents, word prefixes counting; results are ranked (whole name starts with the word 100, a name word equals it 80, starts with it 60, a tag equals it 45, category or type 40, name contains it 30, tag prefix 25, category or type prefix 20, summed; then shorter names) | +| `library.get {id}` | the entry, the preset file, its source, the material applying it would make, the file path, and `graph`: none, type or flat | +| `library.apply {id, nodes, scope?}` | applies to parts as one undo step labelled "Apply " (see below); answers the change plus `{id, material, reused, parts, scope}` | +| `library.favorite {id, on = true}` | `{id, favorite, favorites}` | +| `library.recent {}` | the presets applied most recently (24 kept), newest first, with `used_at` | +| `library.save {material, name?, category}` | saves a document material as `user/` | +| `library.remove {id}` | deletes a user preset; built-in presets cannot be removed | +| `library.thumbnail {id, size = 128, wait?, timeout?, inline?, retry?}` | `{id, size, sha256, path, state, error?, png_base64?}`; a missing picture is queued and answered at once | +| `library.thumbnails {ids, size}` | queues several in the order given | + +Each entry in a list is `{id, name, category, type, tags, sha256, user, favorite, needs_graph}`. + +**Applying.** The material is built as `SurfaceParams::default()`, then the type's defaults, then the preset's `params`, with the type's graph when it has one, tuned to the preset (the wood node's colours at 1.3 and 0.55 times the base colour, the marble node's at 1.08 and 0.45, the paint flakes' roughness and metalness lerps around the preset's values and their colour mix around 1.5 times its base colour, and for stones other than marble (concrete, limestone, sandstone, slate, travertine, granite) a fractal mottling graph instead of the marble veins, granite with 4 mm grains). An identical material already in the document (same name, type, params, graph, slots and textures) is reused instead of duplicated. Scope `part` (default) reaches every part in the given nodes' subtrees; `group` every part under each node's parent group; `same_material` every part wearing a material that the reached parts wear. The preset goes to the front of the recent list. + +**Saving.** `library.save` writes `/formshot/library/materials//.json` in format 1 with every parameter that differs from the type's defaults, `source.kind` authored and licence `NOASSERTION`; slots, textures and the material's own graph are not stored (the reply's `notes` says so). The slug comes from the name (accents folded, at most 40 characters); a taken slug becomes `-2`, `-3`. Favourites and recent presets are kept in `/formshot/library/state.json`, re-read on every call and written atomically, so the command line and the service agree. The user data folder is `FORMSHOT_USER_DATA`, else `%APPDATA%`, `~/Library/Application Support`, `$XDG_DATA_HOME` or `~/.local/share`. + +## Thumbnails + +A thumbnail is FormShot's own material ball (a sphere with an inset band, on a dark pedestal) wearing the preset, rendered by the CPU path tracer under the built-in studio with one soft key light, a shadow-catcher ground, 48 samples and the denoiser; an emitting preset lowers the exposure so its colour reads. Renders run on one background thread per engine with its own document, so commands are never blocked. Pictures are cached at `/formshot/library/thumbs/-.png`, so a changed preset gets a new picture; a `.look` marker in that folder names the scene version (`ball-4` since the preset graphs were corrected), and when it changes the old pictures are dropped once. About 10 s per 128 px picture on a busy two-core machine. + +The service serves `GET /api/library/thumbnail/?size=128&h=`: with a matching `h` and a cached file it answers at once with an immutable cache header, without asking the engine; otherwise it queues the render and polls, answering 503 with `Retry-After` while it runs. `GET /api/library/index` passes through `library.list`; `POST /api/library/thumbnails` queues a batch. + +## The panel + +The Library panel on the left of the workspace has a search field (180 ms debounce; Enter searches now, Escape clears), shelves (All, Favorites, Recent, In project, User), the twelve categories with live counts of the current shelf and search, a grid of tiles in three sizes, and a save button. The grid is virtual: a fixed pool of tile nodes is rebound as you scroll, and thumbnails are asked for only when a tile is in view, so a long list scrolls without building nodes. Double-click or Enter applies a preset to the selected parts; the tile menu also applies to whole groups or to every part sharing the material, toggles favourite, shows details (the preset's source and references) and removes user presets. Dragging a tile onto the viewport outlines the part under the pointer and applies on drop (Alt: the whole group; Shift: every part with the same material). In project lists the document's own materials. The panel keeps its shelf, category, search, tile size, scroll and active tile across reloads. diff --git a/docs/MATERIALS.md b/docs/MATERIALS.md new file mode 100644 index 00000000..1b17955e --- /dev/null +++ b/docs/MATERIALS.md @@ -0,0 +1,240 @@ +# Materials: types, slots, graphs and the material program + +This page describes how a FormShot material is stored, how texture slots and node graphs become a small program, and how that program is meant to run in both path tracers. It is the reference for anyone changing a material type, adding a node kind or an opcode, or porting the interpreter. Everything is in scene-linear ACEScg, metres and radians unless a field says otherwise. The code is in `native/crates/fsh-scene` (types, slots, graphs, the compiler, the preview bake) and `native/crates/fsh-materials` (the program, the interpreter, texture pixels, procedurals); the rationale is in [`native/HASHOUT_LOG.md`](../native/HASHOUT_LOG.md) under fsh-materials and fsh-scene. + +**State in this tree.** Types, slots, graphs, labels, the compiler, the interpreter, the ten procedurals, thin film and dispersion, the texture loader and every command below exist and ran. Both path tracers run material programs at every hit: the CPU through `Program::evaluate` with the engine's loaded textures, the GPU through `program.wgsl` with the same textures packed into its `tables` buffer, agreeing with the CPU within the parity tolerance on software drivers ([`GPU-ENGINE.md`](GPU-ENGINE.md)). The window's own WebGPU engine receives the same textures but has not drawn a picture anywhere yet. `material.preview_maps` bakes with the engine's loaded images too, so the window's Material preview mode shows image slots and labels. + +## One surface model, eighteen types + +Every material is the same layered surface model, `SurfaceParams`, whose fields follow OpenPBR Surface: base, specular, transmission, subsurface, coat, fuzz, thin film, emission and geometry. A material type is only a preset of that model: its default parameters, the parameters its page shows (with ranges and units, and whether a texture may drive each), and optionally a preset graph. `fsh_scene::material_types()` lists them; `material.types` returns them to the window and agents. + +| id | category | key defaults (everything else is the model's default) | graph | +| --- | --- | --- | --- | +| generic | Generic | the plain defaults | no | +| plastic | Plastic | base 0.6 grey, specular_roughness 0.3, specular_ior 1.49 (PMMA) | no | +| plastic_clear | Plastic | transmission 1, base white, specular_roughness 0.02, specular_ior 1.49 | no | +| metal | Metal | base_metalness 1, aluminium colour, specular_roughness 0.2 | no | +| metal_brushed | Metal | metal with specular_roughness 0.3 and anisotropy 0.7 | an optional brushed bump | +| paint | Paint | red base, specular_roughness 0.4, coat 1, coat_roughness 0.03, coat_ior 1.5 | no | +| paint_metallic | Paint | base_metalness 0.6, specular_roughness 0.35, coat 1, coat_roughness 0.02, coat_ior 1.5 | flakes | +| glass | Glass | transmission 1, base white, specular_roughness 0, specular_ior 1.52 (soda-lime) | no | +| glass_thin | Glass | glass, thin walled | no | +| liquid | Liquid | glass with specular_ior 1.333 (water, 20 C, 589 nm) | no | +| gem | Gem | glass with specular_ior 2.417 (diamond), dispersion scale 1, Abbe number 55 | no | +| rubber | Rubber | base 0.04 grey, specular_roughness 0.6, specular_ior 1.52, diffuse roughness 0.5 | no | +| fabric | Fabric | specular_weight 0.25, specular_roughness 0.8, diffuse roughness 1, fuzz 1, fuzz_roughness 0.5 | no | +| ceramic | Ceramic | base 0.8 white, specular_roughness 0.4, coat 1, coat_roughness 0.05, coat_ior 1.5 (glaze) | no | +| diffuse | Generic | specular_weight 0, diffuse roughness 0.5 | no | +| emissive | Emissive | base black, emission_luminance 500 nits, emission white | no | +| wood | Wood | specular_roughness 0.45, diffuse roughness 0.3 | wood rings | +| stone | Stone | specular_roughness 0.5, diffuse roughness 0.5 | marble veins | + +Colours are given in linear sRGB and converted with `Rgb::from_linear_srgb`. `fsh_scene::METALS` lists ten measured normal-incidence colours (iron, silver, aluminium, gold, copper, chromium, nickel, titanium, cobalt, platinum; Real-Time Rendering 4th ed. table 9.2) with a white edge tint; the library's metal presets carry more exact F0 and F82 tints computed from measured n and k (see [`LIBRARY.md`](LIBRARY.md)). + +The preset graphs: wood uses a wood node (250 rings per metre, light (0.48, 0.30, 0.15) and dark (0.20, 0.10, 0.04)) into base_color; stone a marble node (8 veins per metre, base (0.80, 0.79, 0.76), vein (0.22, 0.22, 0.24)); paint_metallic uses flakes (2000 per metre, density 0.5, spread 0.25) whose mask lerps roughness from 0.35 to 0.12 and metalness from 0.5 to 0.9 and mixes two blues into base_color, and whose colour output goes through a normal_map node into normal. Because paint_metallic's base colour comes from its graph, its page's base colour field changes nothing until the mix node is edited. metal_brushed's `optional_graph` (brushed lines at 1000 per metre and 2 cm streaks into a 3e-5 m bump) is offered, not applied to new materials. + +`material.create {type, name?}` starts a material from a type's preset; `material.set_type {key, type_id, keep}` changes the type, keeping the values (`keep: true`, the default) or resetting params and graph to the preset (`keep: false`; slots stay). + +## Texture slots + +A slot makes a texture drive one material input. Slots are allowed on `base_color`, `specular_roughness`, `base_metalness`, `specular_weight`, `coat_weight`, `coat_roughness`, `emission_color`, `geometry_opacity`, `normal`, `bump` and `displacement`. A slot holds: + +| Field | Meaning (default) | +| --- | --- | +| `texture` | a document texture key | +| `projection` | `uv {set}` (set 0), `box {blend}` (0.5), `planar`, `cylindrical`, `spherical` | +| `transform` | `offset` [u, v], `scale` [u, v] (repeats per uv unit, or per metre for projections), `rotation` (radians), `space` (object, or world for projections) | +| `wrap` | repeat, clamp, mirror (repeat) | +| `filter` | nearest, bilinear, trilinear (trilinear) | +| `colour_space` | srgb, linear, acescg, data; unset means srgb for colour inputs and data for the rest | +| `channel` | rgb, r, g, b, a, luminance (rgb). A number input reads rgb as ACEScg luminance, which equals the value on grey maps; a colour input given one channel splats it | +| `range`, `invert` | number inputs: `t = 1 - t` when inverted, then `value = range[0] + t (range[1] - range[0])` ([0, 1]) | +| `multiply` | multiply by the input's constant, as glTF factors do (false) | +| `strength` | normal: tangent xy scale (1); bump: metres of height per texel value 1 (0.001); displacement: metres per unit (0.01) | +| `flip_y` | normal: the green channel points down (DirectX convention) | +| `fallback` | the texel used when the image is missing; unset means the texel that reproduces the input's constant | + +`material.set_slot {key, input, slot, path?}` deep-merges a partial slot (merging while a value is dragged); with `path` it adds the texture reference in the same undo step. `material.clear_slot {key, input}` removes one. `texture.remove` clears slots that name the removed texture. + +### Mapping maths + +The uv transform is `uv' = R(rotation) (uv * scale) + offset` with `R = [[c, -s], [s, c]]`. Projections use the object-space position (world when `space` is world) in metres: + +| Projection | uv | +| --- | --- | +| planar | `(x, y)` | +| cylindrical, about object Y | `(atan2(x, z) / 2pi + 0.5, y)` | +| spherical | `(atan2(x, z) / 2pi + 0.5, acos(clamp(y / abs(p))) / pi)` | +| box | three planes, `(z, y)` for X, `(x, z)` for Y, `(x, y)` for Z, each through the same transform, weighted by `w_i = max(abs(n_i) - blend / 2, 0)^4` normalised (n the object normal) | + +Uvs are stored with v pointing up (origin at the image's bottom left, the image's first row at v = 1); every importer follows this. A uv input asking for a set the mesh lacks reads set 0. + +## The material graph + +A graph is a set of nodes, links between their sockets, and outputs that connect node sockets to material inputs. Graph outputs drive every input except `bump` (a graph bumps through a Bump node into `normal`), and a graph output wins over a slot on the same input, which wins over the constant. Sockets are Float, Colour, Vector or Normal; float and colour convert by splat and ACEScg luminance, vector and colour componentwise, float to vector by splat; a normal goes only into normal or vector inputs. A graph is refused when it names missing nodes, sockets or textures, links one input twice, has a cycle, holds more than 256 nodes, or would need more than 32 registers. + +| Kind | Settings | Inputs (default) | Outputs | +| --- | --- | --- | --- | +| constant | value (number or colour) | none | value | +| texture | texture, projection, transform, wrap, filter, colour_space, fallback | vector (from the projection) | colour, alpha | +| mapping | projection, transform | none | vector (u, v, footprint) | +| mix | none | a (0), b (1), factor (0.5) | result | +| math | op: add, subtract, multiply, divide, minimum, maximum, lerp, clamp, power, invert | a, b, c (0) | value | +| colour_ramp | 1 to 16 sorted stops, interpolation linear, constant or smooth | factor (0.5) | colour, alpha | +| normal_map | flip_y | colour (0.5, 0.5, 1), strength (1) | normal | +| bump | none | height (0), strength (0.001 m), normal (the shading normal) | normal | +| noise | seed | vector, scale 5, detail 2, roughness 0.5, distortion 0 | value, colour | +| fbm | seed | vector, scale 5, octaves 6, lacunarity 2, gain 0.5 | value, colour | +| voronoi | seed, metric (euclidean, manhattan, chebyshev), feature (f1, f2, edge) | vector, scale 5, randomness 1 | distance, colour, position | +| checker | none | vector, scale 5, colour1 (0.8), colour2 (0.2) | colour, value | +| gradient | linear, quadratic, radial, spherical | vector | value, colour | +| wave | seed, bands or rings, sine, saw or triangle | vector, scale 5, distortion 0, detail 2, phase 0 | value, colour | +| brushed | seed | vector, scale 200 (lines per metre), length 0.05 m, strength 1 | value | +| flakes | seed | vector, scale 2000 (per metre), density 0.5, spread 0.3 | normal, mask, colour | +| wood | seed | vector, scale 1, rings 20 (per metre), distortion 0.5, colour1, colour2 | colour, value | +| marble | seed | vector, scale 1, veins 4, distortion 1, colour1, colour2 | colour, value | + +An unlinked `vector` input of a procedural is the object-space position in metres; of a texture node, its projection. `material.node_kinds` returns this table with every socket and setting; `material.set_graph {key, graph, merge?}` replaces a material's graph (or removes it with null) as one undo step; with `merge: true`, consecutive merging calls on one material stay one undo step until `history.barrier` or another command, which is how a value drag in the graph editor stays one step. + +The flakes `normal` output is in tangent space (a procedural sees no frame). The compiler therefore encodes any procedural output typed Normal as a normal-map colour (`0.5 n + 0.5`) and passes it through a NormalMap step at strength 1, so linking `normal` straight into the material's normal gives the same result as routing the `colour` output through a normal_map node, as the paint_metallic preset does. + +## The program + +`compile_material` turns a material into a `Program`: a constant block `base` (the sanitised parameters, emission in scene units: colour times nits times 0.01), a list of instructions over 32 vec4 registers, a constant pool, an output table, the registers used, `needs` bits (uv sets 0 to 3, tangent, textures, procedural, normal, bump) and the snapshot textures it samples. It emits per input (graph over slot over constant), folds pure operations, drops dead code and allocates registers by liveness. A program with no code and no outputs is constant: the renderer uses `base` and never runs the interpreter, and `base` is bit-identical to the inputs untextured materials always had. Float values are splatted across all four components. A material that fails to compile falls back to its constant program. `material.program {key}` shows a material's program with a disassembly. + +Evaluation: registers start at zero; each instruction writes `dst`; then each output writes its field (floats take x, colours xyz, the normal xyz normalised with the incoming shading normal when not finite, displacement x); then the inputs are sanitised; a part colour, when set, then replaces `base_color`. + +| Op | Name | Meaning (operands are registers unless noted; k is a constant-pool index) | +| --- | --- | --- | +| 0 | Nop | nothing | +| 1 | Const | dst = consts[a..a+4] | +| 2 | Input | shading-point input `flags & 15`: 0 world position (w footprint), 1 object position (w footprint), 2 shading normal, 3 geometric normal, 4 object normal, 5 uv set `a` as (u, v, uv footprint, 0), 6 tangent (xyz, w sign), 7 footprint; evaluated at bump offset `flags >> 4` (0 none, 1 along u, 2 along v) | +| 3 | Swizzle | dst.i = a[(flags >> 2i) & 3] | +| 4 | Combine | dst = (a.x, b.x, c.x, 0) | +| 5 to 11 | Add, Sub, Mul, Div, Min, Max, Pow | componentwise; Div gives 0 where b is 0; Pow is max(a, 0)^b, 0 when not finite | +| 12 | Lerp | a + (b - a) c.x | +| 13 | Clamp | min(max(a, b), c) | +| 14 | Invert | 1 - a | +| 15 | Luminance | splat(dot(a.xyz, ACEScg luminance)) | +| 16 | Ramp | colour ramp at a.x; consts[b] = n, then n stops (position, r, g, b, a); flags 0 linear, 1 constant, 2 smooth | +| 17 | Xform2 | uv transform of a with consts[b..b+6] = (sx, sy, cos, sin, ox, oy); the footprint z is multiplied by max(abs sx, abs sy) | +| 18 | Project | a = position; flags 0 planar, 1 cylindrical, 2 spherical; dst = (u, v, footprint', 0), the footprint grown near the axis or pole | +| 19 | Tex | sample texture b at uv a.xy with footprint a.z; fallback consts[c..c+4]; wrap in flags bits 0 to 1, filter in bits 2 to 3 | +| 20 | TexBox | box projection of texture b at position a with the object normal (world when flags bit 4); fallback consts[c..c+4], then (sx, sy, cos, sin, ox, oy, blend) | +| 21 | NormalMap | world normal from the tangent-space colour a.xyz: n = 2c - 1, xy times b.x, y negated when flags bit 0, in the frame (T, B, N) | +| 22 | Bump | normal a bent by the heights b = (h, h_u, h_v) in metres (Mikkelsen 2010 surface gradient) | +| 23 | Proc | dst = procedural(kind = flags, output = b, args); consts[a] = n, then n argument register numbers | +| 24 | Label | a = object position (w footprint), consts[b..b+12] = origin, right / width, up / height, normal / half depth, c = object normal; d = a.xyz - origin, `u = dot(d, right) + 0.5`, `v = dot(d, up) + 0.5`, `w = dot(d, normal)`, footprint `a.w max(abs(right), abs(up))`; mask 1 when u and v are in 0..1, w in -1..1 and (flags bit 0 clear, or the object normal faces the label's normal), else 0; dst = (u, v, footprint, mask) | + +Fields: 0 base_weight, 1 base_color, 2 base_metalness, 3 base_diffuse_roughness, 4 specular_weight, 5 specular_color, 6 specular_roughness, 7 specular_ior, 8 specular_anisotropy, 9 transmission_weight, 10 transmission_color, 11 coat_weight, 12 coat_color, 13 coat_roughness, 14 coat_ior, 15 fuzz_weight, 16 fuzz_color, 17 fuzz_roughness, 18 emission (scene units), 19 opacity, 20 normal, 21 displacement (metres along the normal, stored, not applied per hit). + +**The tangent frame and bump.** At a hit, N is the shading normal, T the mesh tangent (Gram-Schmidt against N) or dP/du when the mesh has none, and B = sign cross(N, T). Bump evaluates the height three times (at the hit, offset along u and along v) with `eps = clamp(0.5 footprint, 1e-6, 1e-2)` metres, then `dhdu = (h_u - h) / du`, `dhdv = (h_v - h) / dv`, `R1 = cross(dP/dv, N)`, `R2 = cross(N, dP/du)`, `det = dot(dP/du, R1)` and `n' = normalize(abs(det) N - sign(det) (dhdu R1 + dhdv R2))`, falling back to N when not finite. The uv footprint passed to Tex is the world footprint over `sqrt(abs(dP/du x dP/dv))`, times the transform's scale. + +### The encoded program + +`Program::encode()` gives 32-bit words; `encode_f32()` the same with every integer stored as an exact float, for the GPU's existing `tables` buffer (the GPU engine is at its limit of 8 storage buffers, so programs and texels need no new binding; every integer stays below 2^24): + +``` +word 0 magic 0x4d50 ("PM") word 1 version 1 +word 2 instruction count I word 3 constant count K +word 4 output count O word 5 registers used +word 6 needs bits word 7 reserved 0 +then I instructions x 4 words: [op | dst << 8 | flags << 16, a, b, c] +then K constants +then O outputs x 1 word: [field | reg << 8] +``` + +The constant block is not in the blob: on the GPU it is the existing material record, whose `program` word holds the blob's offset and whose flags bit 0 says a program runs. + +## Textures and filtering + +The snapshot lists the textures programs sample as `RenderTexture {key, path, colour_space, mipmaps}`, deduplicated by path and colour space (one image used for a colour and for a number appears twice, as srgb and as data). The pixels arrive as a `TextureSet` in the same order (`None` samples the fallback); a `TextureImage` is a colour space and mip levels of `Rgba8` or `RgbaF32` texels, row 0 at v = 1. One definition serves both engines: + +- **Mips.** Level n + 1 is `max(1, w/2)` by `max(1, h/2)`, each texel the mean of the 2 by 2 block of level n in linear values (sRGB bytes decoded first, re-encoded with round-to-nearest), indices clamped to the level. +- **Decoding.** `Rgba8` in srgb decodes rgb with the exact 256-entry table `srgb8_table()` and alpha as i / 255; other spaces i / 255. +- **Nearest.** `floor(u w)`, wrapped. +- **Bilinear.** `x = u w - 0.5`, `i0 = floor(x)`, `f = x - i0`, the same for y with `v' = 1 - v`; texels i0 and i0 + 1 wrapped (repeat: euclidean modulo; clamp: to 0..w-1; mirror: period 2w reflected), weights (1 - f, f), decoded values filtered. +- **Trilinear.** `lod = log2(max(footprint_uv w0, footprint_uv h0, 1e-8))` clamped to the levels, a linear blend of the two bilinear lookups. +- **Colour spaces.** After filtering, srgb and linear multiply rgb by the linear-sRGB-to-ACEScg matrix; acescg and data stay as they are. + +Details the definition fixes: mips of 8-bit sRGB rgb are `round(srgb_encode(mean of the decoded values) 255)`; other 8-bit channels take the exact integer mean `(a + b + c + d + 2) / 4`; float levels the plain mean; trilinear blends only when the fraction is above 0; a non-finite uv returns the fallback. Float storage is always linear: 16-bit PNGs become floats, decoded through the sRGB curve when the colour space is srgb; HDR and EXR values are stored as read with NaN and infinities set to 0. + +**Decoding.** Every image goes through fsh-io's `decode_image`: PNG (8 and 16 bit, every colour type), JPEG (baseline and progressive, through zune-jpeg; greyscale, YCbCr, RGB, CMYK and YCCK; at most 16384 pixels a side; EXIF orientation ignored), Radiance HDR, and OpenEXR (single-part scanline files with NONE, RLE, ZIPS, ZIP, PIZ or PXR24 compression and HALF, FLOAT or UINT channels; tiled, deep, multi-part, B44 and DWA files are refused). The engine, the window's engine and the checks share this one decoder. + +**Loading.** The engine (`fsh_commands::textures`) loads each `RenderTexture` once per path, colour space, file length and modification time; `fshot:` members come from the project, other paths from disk (relative to the document's folder). A missing or undecodable image becomes `None` and its slots sample their fallbacks; the reason is in the command reply's warnings and in `render.status.textures {count, loaded, missing, warnings}`, and the render goes on. The set is handed to the renderer when the list, the folder or a file's size or time changed, at the next refresh or `render.start`; that restarts the picture. Imports embed their images in the project (see [`FILE-FORMAT.md`](FILE-FORMAT.md)); the window uploads chosen images through `POST /api/textures`. Whatever names an image by path (`material.set_slot`, `material.label_add`, `material.label_set`, `texture.add`, and `environment.set` for an HDRI) has it embedded in the project as `fshot:textures/.` when the command runs, if it is a PNG, JPEG, HDR or EXR of at most 256 MiB; otherwise the path stays as given. Relative paths start at the document's folder. + +**Bent normals.** A normal changed by a program (a normal map, a bump, flakes) can be so steep that the mirror direction falls below the geometric surface, which the BSDF rejects; both tracers bend such a normal just enough that the reflection stays 0.01 above the horizon (after Keller et al. 2017). Normals no program changed are left alone. + +**Footprints.** Both tracers carry a ray cone (Ray Tracing Gems, chapter 20) from the camera: the footprint at a hit is the cone's width over `max(abs(cos), 0.05)`, and after a bounce the spread grows by 2 for a diffuse lobe, `2 r^2` for a glossy one of roughness r, and nothing for a delta lobe. Light samples on textured emitters use footprint 0. + +**The hit context.** Object position and normal through the instance's inverse; uv sets with one entry per vertex, as stored, up to four; dP/du and dP/dv from uv set 0 (an orthonormal frame around the shading normal when the mapping is missing or degenerate); the mesh tangent made orthogonal to the shading normal, its sign flipped on mirrored instances. The GPU builds the same context; its `atan2` and `acos` are polynomials so projections do not depend on the driver. + +## Procedural patterns + +`fsh_materials::procedural(kind, output, args)` and its WGSL port `procedural.wgsl` compute the ten patterns. `args[0]` is the coordinate (xyz in metres, footprint in w), then the kind's inputs in the table's order (numbers in x, colours in xyz), then a settings vector (seed, mode 1, mode 2, 0). Hashing is integer pcg3d (Jarzynski and Olano, "Hash Functions for GPU Rendering", JCGT 9(3), 2020) on u32 in both languages, so the integer parts agree bit for bit and floats within 1e-4 (measured at most 5.4e-7 on software Vulkan). + +| Kind | Formula | +| --- | --- | +| noise 0 | Perlin's improved noise (SIGGRAPH 2002), fractal with detail + 1 octaves, lacunarity 2, gain = roughness; value `0.5 + 0.5 n`; optional distortion of the position by three noise channels | +| fbm 1 | the same fractal sum with octaves 1 to 16, lacunarity and gain (Musgrave's fBm) | +| voronoi 2 | Worley's cellular basis (SIGGRAPH 1996): one feature point per cell jittered by randomness, the 27 cells around the point, euclidean, manhattan or chebyshev distance, F1, F2 or F2 - F1; colour from the F1 cell's hash; position the F1 point | +| checker 3 | parity of `floor(p scale + 1e-4)` per axis | +| gradient 4 | linear `clamp(x)`, quadratic its square, radial `atan2(y, x) / 2pi + 0.5`, spherical `max(1 - abs(p), 0)`, on raw coordinates | +| wave 5 | bands along x or rings in abs(p), plus fractal distortion and phase, through a sine, saw or triangle profile; period 1 / scale metres | +| brushed 6 | two noise layers stretched along object X (streak length) and squeezed across it (lines per metre) | +| flakes 7 | voronoi cells as flakes, on with probability density, tilted uniformly in solid angle within a cone set by spread; outputs a tangent-space normal, a mask and a normal-map colour | +| wood 8 | rings about object Y at the given rings per metre with a noise-distorted radius, ring profile f^3, grain noise stretched along Y | +| marble 9 | Perlin's 1985 turbulence (five octaves) distorting a vein phase along x, vein `(1 - sin(pi f))^4` | + +**Anti-aliasing.** Each kind fades detail finer than the pixel footprint to its mean, by `aa(r) = 1 - smoothstep(0.5, 1, r)` with r the footprint over the feature length: noise octaves fade to 0 (value 0.5), checker and wave to 0.5, voronoi distances to their measured means (euclidean F1 0.4801 at randomness 0 and 0.5205 at 1, for example), flakes to density and an unbent normal, wood rings to 1/4, marble veins to 0.1309. Averaged over a plane, the preset colours are the same near and far (wood 0.400 near, 0.399 at 4 m). + +## Labels + +A label is an image projected onto the part wearing the material, like a printed decal: `material.labels` lists them, in order, in the part's object space. + +| Field | Meaning | +| --- | --- | +| `id`, `name` | an id unique in the material (ids are max + 1), a display name | +| `texture`, `colour_space` | the image (a document texture) and its colour space (else the texture's hint, else srgb) | +| `origin`, `normal`, `up` | the label's centre, the direction it faces and its up direction, in metres in object space | +| `size` | width and height in metres | +| `rotation` | radians about the normal, counter-clockwise seen from the front | +| `depth` | how far through the part the projection reaches, in metres | +| `opacity` | 0 to 1 | +| `two_sided` | also print where the surface faces away from the label (a one-sided label prints only on faces turned towards it) | +| `visible` | hidden labels cost nothing | +| `roughness`, `metalness` | optional: what the printed area's roughness and metalness become | + +The frame is right = up x normal (so the image reads unmirrored from the front), rotated about the normal. Labels compile after slots and graph, in list order: each visible label with an image is a `Label` op on the object position and object normal, a `Tex` with clamp wrap, trilinear filter and a transparent fallback (a missing image prints nothing), then `a = alpha * mask * opacity`, `base_color = lerp(base_color, label colour, a)` and, when set, `specular_roughness` and `base_metalness` lerped the same way. Later labels print over earlier ones. A material whose labels are all hidden or without images stays a constant program. + +Commands (undoable, merged while a value is dragged): `material.label_add {key, label, index?, path?, colour_space?}` (with `path` the texture is added in the same step; answers the new id), `material.label_set {key, id, label, path?}`, `material.label_remove {key, id}`, `material.label_move {key, id, index}`. Partial labels with unknown fields are refused. `texture.remove` leaves a label without its image. In the window the Labels section of the Material page lists them, edits sizes in millimetres and rotation in degrees, and places a label with Place on Surface (click a point on the part). + +## Thin film and dispersion + +These two OpenPBR features are per material and constant (programs, textures and labels never change them); both tracers apply them identically. + +**Thin film** (`thin_film_weight`, `thin_film_thickness` in micrometres 0 to 10, `thin_film_ior`): a film on the base, below the coat, following Belcour and Barla's Airy reflectance (ACM TOG 36(4), 2017) with three interference orders and their spectral sensitivity fits, unpolarised, converted to ACEScg so that a flat reflectance stays grey, clamped to 0..1. Below 0.03 um the film fades out. Over a dielectric base the reflectance is `lerp(F, Airy, weight)` per channel and transmission is 1 - F, so a thin wall with specular_ior 1 and a film is a soap bubble; over a metal F82 blends with the conductor Airy, the metal's n and k approximated from base and specular colour (Gulbrandsen, JCGT 3(4), 2014). The anodised titanium and pearl paint presets of the library use it. + +**Dispersion** (`transmission_dispersion_scale`, `transmission_dispersion_abbe_number`): Abbe number V_d = abbe / scale and a Cauchy law through `specular_ior` at the d line. The tracers are RGB, so each path picks one hero channel c from sampler dimension 5 at its first dispersive, transmissive, not thin-walled hit, uses that channel's ior (`n_c = n_d + (n_d - 1) k D_c` with D = (-0.0062823046, 0.5049531, 1.9850688) um^-2 for ACEScg R, G, B, whose representative wavelengths are 588.2, 542.2 and 452.6 nm), and weights its first transmission by 3 on that channel and 0 on the others. A program-driven ior is shifted the same way. A prism therefore shows three images, blue far from red and green. Not done: dispersion within a channel, on thin walls, in shadows (shadows through glass stay opaque). + +## Preview maps for the window + +`material.preview_maps {key, size}` (16 to 512, default 128) evaluates a material's program over a 1 m square in the object XY plane facing +Z (pixel (x, y) at uv `((x + 0.5) / size, 1 - (y + 0.5) / size)`, footprint 1 / size) and returns four base64 PNGs: base colour (sRGB-encoded from ACEScg), roughness and metalness (linear grey) and the normal (tangent space, `0.5 + 0.5 n`, OpenGL convention), plus flat `values` and a `constant` flag. The window's Material preview mode samples these by mesh uv0 (see [`VIEWPORT.md`](VIEWPORT.md)), so uv-mapped materials agree in placement with the tracers; projected and procedural materials are approximated by the square. + +## Commands + +| Command | Kind | What it does | +| --- | --- | --- | +| `material.create {key?, material?, type?, name?}` | document, undoable | a new material, from a type's preset when `type` is given | +| `material.set_type {key, type_id, keep = true}` | document | change the type, keeping or resetting the values | +| `material.set_params {key, values}` | document | change parameters (merges while dragging) | +| `material.set_slot {key, input, slot, path?}` | document | add or change a texture slot (merges while dragging without `path`) | +| `material.clear_slot {key, input}` | document | remove a slot | +| `material.set_graph {key, graph, merge?}` | document | replace or remove the graph; refused with the reason when invalid; `merge` folds consecutive calls into one step | +| `material.get {key}` | read-only | the material as stored, its used texture keys, every document texture reference, and a summary of its program | +| `material.types {}` | read-only | the types and the measured metals | +| `material.node_kinds {}` | read-only | the graph node kinds | +| `material.program {key}` | read-only | the compiled program with a disassembly | +| `material.preview_maps {key, size}` | read-only | the baked preview maps | + +Labels add `material.label_add`, `material.label_set`, `material.label_remove`, `material.label_move` (document, undoable) and `material.labels {key}` (read-only: each label with its image path and size in pixels). The window's Material page and graph editor read materials through `material.get`. diff --git a/docs/VIEWPORT.md b/docs/VIEWPORT.md index b07fcd20..4e0a4b87 100644 --- a/docs/VIEWPORT.md +++ b/docs/VIEWPORT.md @@ -11,7 +11,9 @@ The viewport is the picture in the middle of the workspace. It shows the scene i | Solid | WebGL2: a camera-relative studio matte with a contact shadow on the ground | same | | Wireframe | WebGL2: triangle edges | same | -`view.mode {mode}` (or `view.mode.render`, `material`, `solid`, `wireframe`) switches. The raster modes read the scene from `scene.meshes`, which lists meshes and placed instances (row-major world matrices, display colours, metalness and roughness, visibility, selection) with a revision, and fetch each mesh once from `GET /api/engine/mesh/{key}` as binary (`FSHM` version 1: a 16-byte header, then float positions, float normals and 32-bit indices, little endian), falling back to `scene.mesh_data` when the route is missing. Meshes are cached by key and revision. The raster picture is drawn into a 4x multisampled target and redrawn only when something it shows changes: the camera, instances, selection, size, style or guide lines. While a raster mode shows, the path tracer is stopped. Returning to Rendered keeps the raster picture until a fresh path-traced frame arrives (at most 5 s), so an old position never flashes. +`view.mode {mode}` (or `view.mode.render`, `material`, `solid`, `wireframe`) switches. The raster modes read the scene from `scene.meshes`, which lists meshes and placed instances (row-major world matrices, display colours, metalness and roughness, visibility, selection) with a revision, and fetch each mesh once from `GET /api/engine/mesh/{key}` as binary (`FSHM` version 1: a 16-byte header, then float positions, float normals and 32-bit indices, little endian), falling back to `scene.mesh_data` when the route is missing. The second header word holds the version in its low 16 bits and flags in its high 16 bits: bit 16 appends uv set 0 (2 floats per vertex), bit 17 tangents (4 floats per vertex, the last a sign of 1 or -1), in that order, present only when the mesh has them; readers that ignore trailing bytes keep working. + +**Material preview.** `scene.meshes` also lists `materials: [{key, revision}]` (the revision moves when the material's JSON or a texture file it names changes) and per instance `tinted` (a part colour replaces the base colour). In Material preview the window asks `material.preview_maps {key, size}` for the materials visible parts wear (size 64, 128 or 256 by viewport quality), and samples the baked base colour, roughness, metalness and tangent-space normal maps by mesh uv0, at `(u, 1 - v)` since the bake's first row is v = 1, with the mesh tangent frame or the screen-derivative frame when the mesh has no tangents. New maps replace the old ones only when all four have arrived. Constant materials and parts without uvs use the flat values. Projected and procedural materials are only as right as a bake on a 1 m square can make them, while image slots and labels show their real images, because the bake samples the engine's loaded textures. Meshes are cached by key and revision. The raster picture is drawn into a 4x multisampled target and redrawn only when something it shows changes: the camera, instances, selection, size, style or guide lines. While a raster mode shows, the path tracer is stopped. Returning to Rendered keeps the raster picture until a fresh path-traced frame arrives (at most 5 s), so an old position never flashes. ## The path tracer in the viewport @@ -31,6 +33,10 @@ How the window chooses, in order: The state chip's tooltip always names the reason the window is not drawing itself. +**Textures in the window.** The window's session compiles the same material programs as the engine and needs the pixels of every texture they sample. Images embedded in the project come out of the snapshot it already loads; images outside it come from `GET /api/engine/texture?path=` (window key; it answers only paths the current document's materials sample, 404 for anything else, 413 above 512 MiB, and revalidates with an ETag of size and modification time, so an unchanged file is fetched once). A module worker running the same WebAssembly module decodes them with the engine's decoder (PNG, JPEG, HDR, EXR, mips built there) and hands the decoded images back; the window keeps no texel copy in JavaScript, and images the document stops using are released. Textures load before the viewport takes its first scene and after each document change (outside files are checked every 5 s), and the viewport keeps refining the old picture until they are ready, then restarts once. A texture that cannot be used samples its material's fallback and the device menu says which and why. An environment image embedded in the project is decoded the same way and handed to the window's tracer; an environment still referenced by an outside path shows the studio there. This has run with a stand-in viewport only: no textured picture has been drawn by the WebGPU viewport, for the reason below. + +**Edits from outside the window.** Commands an agent sends through `/api/agent` or MCP are relayed by the service as `scene.changed`, `selection.changed`, `history.changed` or `document.changed` events on `/api/events`, so the window refreshes at once; a command that changes the document but answers `change: none` (an undo of an edit to an unused material, for example) still refreshes the summary. + **What has run.** In headless Chromium with SwiftShader (software WebGPU), the earlier placeholder kernel drew, orbited at half size, picked up a service edit through the poll and handed over to streamed frames when its device was destroyed. The real path-tracing kernel has never finished compiling there: SwiftShader's compiler grows past 4 GB and is killed, so the guard fires and streamed frames draw. No browser with a real graphics card was available, so the path tracer in the window has not drawn a frame anywhere yet. ## Interaction regimes @@ -53,7 +59,7 @@ Every engine command reports the change it actually caused, and the renderers ac | --- | --- | --- | | none | nothing restarts (a new sample target is picked up) | redraw only if the listing revision moved | | display | re-develop only (exposure, tone map): samples kept | no change | -| region | material edits on the CPU engine clear the screen rectangle of the parts that use the material, padded by 6 pixels, and keep every other pixel's samples; the reply carries `region {rect, cleared, total}`. The GPU engine resets fully | the listing revision moves and colours are redrawn | +| region | material edits on the CPU engine clear the screen rectangle of the parts that use the material, padded by 6 pixels, and keep every other pixel's samples; the reply carries `region {rect, cleared, total}`. The GPU engine does the same through `update_region`, also when the edit adds a material (`library.apply`, assigning a new material) | the listing revision moves and colours are redrawn | | full | restart accumulation; uploads are partial (a camera move writes 76 bytes on the GPU, a transform rewrites the top-level tree and instances, a material its records) | refetch only meshes whose revision changed | A camera move restarts the picture through the camera path, not a full rebuild. Content changes move `content_revision` in `scene.summary`; camera changes do not, which lets the window's engine ignore them in its poll. Every reply of `formshot-engine dispatch` also carries `meta: {revision, content_revision}`. @@ -79,7 +85,6 @@ The state chip names the regime (Moving at a percentage of the resolution, Refin - The path tracer in the window has not drawn a frame: software WebGPU runs out of memory compiling the kernel, and no real GPU browser has been tried. Streamed frames are the working path. - Region render works on the GPU engine only. On the processor `render.region` replies `applied: false` with the `region_note` "render regions are not supported on this device yet (cpu)" and the whole image renders; the window does not show that note yet. The region drag in the window has not been run against an engine that has the command. -- The GPU engine resets fully on a material edit; only the CPU engine keeps samples outside the edited region. -- The window learns of edits made outside it (by agents or the command line) only at its own next dispatch, or through the WebGPU engine's poll; the service publishes no scene-changed event yet. -- An HDRI environment cannot reach the window's engine: the project carries a file path on the service's machine. +- Edits made by `formshot cli dispatch` run in a separate engine process and never reach the window; edits through the service's agent route and MCP are relayed as events. +- An HDRI environment referenced by an outside path cannot reach the window's engine; one set with `environment.set` is embedded in the project and does. - Not run: Tauri, Safari and Firefox WebGPU, trackpad, touch and Safari gestures (code paths only), WebGL context loss. diff --git a/formshot b/formshot index 95a0ccde..b3664a70 100755 --- a/formshot +++ b/formshot @@ -22,6 +22,7 @@ usage: ./formshot [command] [options] freeze freeze the backend into the Tauri sidecar (src-tauri/binaries/formshot-engine-backend-*) desktop dev|build run or bundle the desktop app; extra arguments such as --config FILE go to tauri app [flags] build the installable desktop app start to finish (same as ./build_app) + cad [fetch|status] download and verify the STEP and IGES reader (OpenCASCADE worker), or show whether it is installed mcp formshot over MCP's stdio transport, bridged to the running service's /mcp i18n extract|check collect the English interface strings, or check each language table against strings.json agents sync|check|install [--dry-run] write agents/manifest.json and the skill's tool reference (sync), validate @@ -54,6 +55,7 @@ case "$cmd" in build) exec setup/build_frontend "$@" ;; serve) exec setup/serve "$@" ;; freeze) exec setup/freeze_backend "$@" ;; + cad) exec setup/cad_worker "$@" ;; desktop) sub="${1:-dev}" [ $# -gt 0 ] && shift diff --git a/formshot.bat b/formshot.bat index 75c80b05..b18db75a 100644 --- a/formshot.bat +++ b/formshot.bat @@ -21,6 +21,7 @@ if /i "%CMD%"=="desktop" goto desktop if /i "%CMD%"=="app" goto app if /i "%CMD%"=="doctor" goto doctor if /i "%CMD%"=="mcp" goto mcp +if /i "%CMD%"=="cad" goto cad if /i "%CMD%"=="i18n" goto i18n if /i "%CMD%"=="agents" goto agents if /i "%CMD%"=="notices" goto notices @@ -248,6 +249,14 @@ exit /b %FAIL% :mcp python -I mcp\server.py %2 %3 %4 %5 %6 %7 %8 %9 exit /b %errorlevel% +:cad +set "PY=python" +if exist backend\venv\Scripts\python.exe set "PY=backend\venv\Scripts\python.exe" +pushd backend +"%PY%" -m app.routers.cad %2 %3 %4 %5 %6 %7 %8 %9 +set "CADRC=%errorlevel%" +popd +exit /b %CADRC% :i18n python -I setup\i18n.py %2 %3 %4 %5 %6 %7 %8 %9 exit /b %errorlevel% @@ -270,6 +279,6 @@ exit /b 0 echo usage: formshot [command] echo boot ^| install ^| install-desktop ^| backend ^| frontend ^| build ^| serve ^| freeze echo engine [build^|check^|wasm] ^| render IN OUT [flags] ^| cli [args] ^| desktop dev^|build ^| app [flags] -echo mcp ^| i18n extract^|check ^| agents sync^|check^|install ^| notices [--check] ^| doctor ^| clean [--all] ^| help +echo cad [fetch^|status] ^| mcp ^| i18n extract^|check ^| agents sync^|check^|install ^| notices [--check] ^| doctor ^| clean [--all] ^| help :end endlocal diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index e426b513..1af361c9 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # frontend HASHOUT_LOG -Living log for the window side, _v0.4.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. +Living log for the window side, _v0.6.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. ## Org-navi-map @@ -9,7 +9,7 @@ frontend/ index.html the frame: every slot with a fixed id, pre-paint theme, accent, layout, dock and motion script public/splash.html the desktop splash window's page, copied into dist/ by vite build vite.config.ts host false, dev 5300 and preview 5301 strictPort, /api proxied to 127.0.0.1:8300 with ws - package.json, package-lock.json version 0.4.0, the family's pinned set, no icon libraries, no three.js + package.json, package-lock.json version 0.6.0, the family's pinned set, no icon libraries, no three.js public/formshot-logo.svg hand-drawn mark (hexagon with lens), the favicon src/main.ts boot order: window key, language, shell, modules, translator, reveal, events src/version.ts VERSION, a version site @@ -62,6 +62,25 @@ frontend/ src/ui/island-menu.ts, device-menu.ts, stacked.ts island menus, the device and quality menu, stacked labels src/shell/commands.ts, command-palette.ts app-level commands and the palette src/styles/workspace.css + src/ui/import/ index.ts (file.import, import.files, reimport, recent, opens given at launch), engine.ts (probe and jobs), + sheet.ts (the import sheet), upload.ts, desktop.ts (Tauri panel, native drops, open-paths), drop.ts, + recent.ts, formats.ts, import.css + src/ui/cad/ index.ts, quality.ts, service.ts, picker.ts, settings.ts (CAD Import page), offer.ts (sheet hook), + parts.ts (which parts are CAD), retess.ts (the re-tessellate dialog), cad.css + src/ui/handoff/ index.ts, service.ts, describe.ts, prompt.ts (the consent dialog), browse.ts, settings.ts, handoff.css + src/ui/pages/material.ts the Material inspector page: Materials, Parameters, Textures, Graph, Labels, Library sections + src/ui/material/ model.ts, store.ts, edits.ts, swatch.ts, list.ts, popover.ts, glyphs.ts, rows.ts, + params.ts, slots.ts, image.ts, graph.ts, library.ts + src/styles/material.css the Material page's styles + src/ui/graph/ the node editor window: index.ts, editor.ts, model.ts, source.ts, window.ts, canvas.ts, + views.ts, fields.ts, ramp.ts, colour.ts, links.ts, interact.ts, commit.ts, menu.ts, help.ts, + keys.ts, status.ts, labels.ts, graph.css + src/ui/labels/ the Labels section: index.ts (mountLabels), model.ts, image.ts, place.ts (Place on Surface), labels.css + src/engine/gpu/textures.ts, texture-worker.ts TextureFeed and its module worker: texture bytes and decoding for the window's engine + src/ui/library/ the library panel: panel.ts, grid.ts (virtual grid), thumbs.ts, data.ts, state.ts, actions.ts, + details.ts, drag.ts, drop.ts (viewport drop target), save.ts, library.css + src/engine/raster/materials.ts MaterialSource: material.preview_maps for the raster material mode + src/i18n/modules/ import, cad, handoff, material, graph, library and labels namespaces added ``` ## Contents @@ -77,6 +96,12 @@ frontend/ - [Translations](#translations) - [Seams pass](#seams-pass) - [The live viewport](#the-live-viewport) +- [Import and opening files](#import-and-opening-files) +- [CAD and hand-offs](#cad-and-hand-offs) +- [Materials](#materials) +- [The material library](#the-material-library) +- [Labels, window textures and translations](#labels-window-textures-and-translations) +- [The polish pass](#the-polish-pass) ## The frame and the shell @@ -350,3 +375,311 @@ A viewport engine has `start(canvas)`, `stop()`, `setCamera`, `status()`, option - kind: verification - logged: v0.3.0 · 2026-12-02 `npx tsc --noEmit` clean; `vite build` passes with the package (it emits `fsh_wasm_bg-*.wasm`) and without it; `setup/i18n.py check` 100%. Headless Chromium 1243 with SwiftShader WebGPU, the real built app and a service with the release engine, each browser in a memory cgroup: WebGPU was chosen by default (chip "Starting · google swiftshader · WebGPU in the window") and the mirror loaded the exact snapshot (549,663 bytes, no notes); the megakernel never finished compiling and was OOM-killed at the 4,000 MB limit at about 107 s. With the 45 s guard it fell back with the sentence above and CPU frames drew; with a 20 s guard it fell back at 18 to 20 s, and the next visit in the same tab went straight to streamed frames with no GPU engine made. Preference streamed: "WebGPU viewport not used: WebGPU in the window is turned off". Package absent: "The browser engine package is not built (run ./formshot engine wasm)". Destroying the GPUDevice mid-run (with the earlier placeholder kernel, which did draw): the chip's nodes switched to "cpu · Streamed frames (WebGPU off)" with the loss in the tooltip. A WebGPU canvas is never composited by these headless builds, so the drawn pictures were read back with `read_picture()`. Not run: a real GPU browser, so the path tracer in the window has drawn no frame; the content-revision reload, a run-time loss after a real start and the moving regime with the real kernel (the poll starts after the first pass); Safari, Firefox, Tauri; HDRI environments (the snapshot carries a path on the service machine). + +## Import and opening files + +### src/ui/import/index.ts · taking over file.import +- refers-to: src/ui/import/index.ts :: mount, openGiven; src/shell/commands.ts :: file.import; src/shell/registry.ts :: getCommand +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The workspace (src/shell/commands.ts) still registers `file.import` before this module mounts, and the registry throws on duplicates, so `mount` takes the registered spec from `getCommand('file.import')` and replaces its label, description, icon, enabled and run in place (Mod+I stays); when the id is free it registers it itself. Args: none opens the picker, `{path}` or `{paths}` open the sheet for those paths, `{files}` (File objects) upload first. Also registered: `import.files {files?, paths?, path?}`, `file.reimport` (the `scene.summary` selection as `nodes`, else every part), `import.recent {path}`, `import.clearRecent`, File menu entries Reimport and Recent Imports (localStorage `formshot.import.recent`, 8 at most). After `done` the module emits `scene.changed` and `document.changed` locally (the workspace refreshes and kicks the render) and `ui.import.done {name, path}`; framing is the engine's `frame` option so the import stays one undo step. Closing the sheet while an import runs leaves the job running and its toast still arrives; queued files are dropped with a toast. + +### src/ui/import/engine.ts, sheet.ts · probe, jobs and the sheet +- refers-to: src/ui/import/engine.ts :: probe, ImportJob, parseProbe, resultCounts; src/ui/import/sheet.ts :: ImportSheet +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The module keeps its own catalogue view (reloaded on `hello` and `resync`) and falls back when commands are missing: no `import.start` means a direct `file.import`, no `file.reimport` disables Reimport. `ImportJob` runs `import.start`, polls `import.status` every 200 ms and sends `import.cancel`. Reply parsing is tolerant (counts as numbers or arrays, warnings as strings or `{message}`). The sheet (a wide `Dialog`) sends `path, units, up_axis, stand_on_floor, center, frame, merge` and `cad_quality` only for .step, .stp, .iges and .igs. Units default to the probed unit (declared, else guessed) while untouched, and a guess shows a plain warning under the field; up axis, the four switches and CAD quality persist in localStorage `formshot.import.options` (defaults auto, floor on, centre on, frame on, merge off, medium). Import All applies the options to the remaining files with units staying automatic unless changed. Every row has a fixed height, the CAD and progress rows are reserved with `visibility`, the bar moves by `transform: scaleX(var(--fsh-imp-fraction))`: a PerformanceObserver saw zero layout shifts during imports. cad-ui added one region at the end of `open()` (`runCommand('cad.sheet', {select, row})`, plus the registry import line) and reads the selected option's `data-quality` JSON in `options()`. + +### src/ui/import/upload.ts, desktop.ts, drop.ts, src/shell/home.ts · browser uploads, desktop paths and drops +- refers-to: src/ui/import/upload.ts :: groupFiles, droppedFiles, Sending, removeUpload; src/ui/import/desktop.ts :: listenOpens, expandPaths; src/ui/import/drop.ts; src/shell/home.ts :: Home.openFiles +- kind: decision +- logged: v0.6.0 · 2026-12-02 +In a browser the model goes to `POST /api/imports` (part `main` plus sibling parts `files` with relative names, only for glTF and OBJ, which read files beside them) with progress and abort through XMLHttpRequest; a cancelled, failed or aborted upload, or a sheet closed before import, deletes its folder, while a finished import keeps it for Reimport (the service sweeps it after 24 hours). On the desktop the real path from the open panel (`plugin:dialog|open`) or the native drop (`onDragDropEvent`) is used, never an upload, and folders go through `/api/imports/scan`. The drop overlay lives in `#overlay-root` at `var(--z-modal)`. Home's `openFiles` gained one hunk: with `import.files` registered, a model dropped or picked on Home starts a new project from the default template named after the file and imports into it; the model then lives in `.imports//` instead of `mesh.` in the project folder. A native drop on Home creates the project with `file.new {title}` unless a DOM drop happened within 600 ms. + +### src/ui/import/desktop.ts, index.ts · files given at launch +- refers-to: src/ui/import/desktop.ts :: listenOpens; src/ui/import/index.ts :: openGiven +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Inside Tauri, `listenOpens` listens to `formshot://open-paths` first and then drains `take_pending_opens` (which also tells Rust the window is ready), so nothing is lost or doubled; outside Tauri it does nothing. `openGiven(paths)` serialises batches and waits up to 60 s for the import catalogue, because files given at launch arrive before the engine is up. The first `.fshot` opens through `workspace.load {path, title, saved: true}` after a confirm when the open document has unsaved changes; extra `.fshot` files get a toast. Models go to the sheet (several with Import All) when a document is open, else `file.new {title: stem}` first; when Home covers an open document, `ui.workspace.loaded` closes it. Rust's `OPENABLE_EXTS` in src-tauri/src/main.rs lists every import format and `.fshot`, but only files: folders given by the system never reach the window. + +### src/i18n/modules/import/ · strings +- refers-to: src/i18n/modules/import/strings.json and the language tables +- kind: decision +- logged: v0.6.0 · 2026-12-02 +88 strings (83 for the sheet, drops and menus, 5 for opening given files). es.json was written by hand and the 22 other placeholder tables are byte copies of it, the repository's precedent for placeholder tables; es-MX and fr-CA are `{}`. The translators' pass has since filled the 23 non-regional tables (see the translations entry under The material library). + +### (import window) · verification +- refers-to: src/ui/import/ :: (module) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +`npx tsc --noEmit` and `vite build` clean; `./formshot i18n check` exits 0. Headless Chrome against a stand-in engine (the 0.4.0 engine wrapped to answer `import.*`), screenshots looked at: Mod+I picker, a GLB uploaded and probed (10,240 triangles, Millimetres preselected with the guess warning), progress, done toast and the framed render; Cancel mid-import deleting the upload; three files with Import All; a three-file drop on the viewport; Recent Imports; Reimport reaching `file.reimport`; a degraded catalogue; a damaged GLB's reason in the sheet; a drop on Home making a new project; a throttled 11 MB upload with its percentage and Cancel removing the partial folder. Launch opens ran with a stubbed `__TAURI_INTERNALS__` and a stand-in engine: a pending model at launch on Home, a `.fshot` event, two models in a workspace (sheet "1 of 2"), a dirty document asking first. Not run: anything inside real Tauri (the open panel, native drag and drop, real open-paths payloads), browser folder drops through `webkitGetAsEntry`, the real `import.*` commands from the window. + +## CAD and hand-offs + +### src/ui/cad/index.ts, quality.ts, picker.ts, settings.ts · the CAD Import page and the default quality +- refers-to: src/ui/cad/index.ts :: mount; src/ui/cad/quality.ts; src/ui/cad/picker.ts :: QualityPicker; src/ui/cad/settings.ts; src/ui/cad/service.ts :: worker +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The module `cad` registers the Preferences page "CAD Import" (id `cad`, order 62, group Files), `cad.settings` (File menu), `cad.fetchWorker`, `cad.sheet` (palette false), `scene.retessellate` (Scene menu and `context.part`) and `file.importCad`, which the File menu had listed as not built and which now opens the import picker. Presets mirror the engine's (draft 0.002 and 30, medium 0.0005 and 20, high 0.00015 and 12, ultra 0.00005 and 6); custom chord and angle are checked against 0 < chord <= 0.1 and angle 1..90, and chord is shown as a percentage of the model size. The default lives in localStorage `formshot.cad.quality` (a preset name or the object) and `ui.cad.quality` announces a change. The page shows status, version, program path (truncated from the left in a `bdi`), where it was found, this computer's triple and what is published, a reserved two-line reason, Download, Cancel (enabled only when the service says `cancellable`, which it never does today), Check the worker (`cad.status {probe: true}`), and a reserved progress row moved by `scaleX`. `service.ts` is one store for the page and the sheet over `GET /api/cad/worker`, `POST /api/cad/worker/fetch` and the `cad.worker` events. + +### src/ui/cad/offer.ts, parts.ts, retess.ts · the sheet hook, CAD parts and re-tessellation +- refers-to: src/ui/cad/offer.ts :: attachSheet; src/ui/cad/parts.ts :: cadIndex, zipMember; src/ui/cad/retess.ts :: openRetessellate +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`cad.sheet` sets the sheet's CAD quality to the stored default (a custom default adds an option "Custom (0.03%, 15°)" carrying `data-quality`) and inserts one reserved 36 px line under the CAD row, shown only while the file is STEP or IGES and the worker is missing, downloading or just installed, with a Download button and progress; it is inserted in the same task as `dialog.open()` so the sheet opens at its final height. `scene.summary` carries no node metadata, so `cadIndex` reads `scene.json` from the project snapshot (a 40-line stored-zip reader) and keeps parts with `source.cad`; it re-reads the cheap summary on events and fetches the snapshot again only when the part ids, triangle counts or document path change. The re-tessellate dialog offers Selected CAD parts or All CAD parts with counts, shows the source files, the quality now and triangles now, takes a new quality, and asks `cad.estimate` only if the engine lists it (no engine does). Apply runs `scene.retessellate {quality, nodes?}`; the engine sends no progress, so the reserved row is indeterminate with elapsed seconds, and success closes with a toast naming the triangle change and an Undo action. The command is disabled with the reason when the engine lacks it, when nothing came from STEP or IGES, or when the selection holds no CAD part. The Scene inspector page has no hook for extra rows, so no CAD source line was added there. + +### src/ui/handoff/ · the consent prompt and Open a Hand-off +- refers-to: src/ui/handoff/index.ts; service.ts; describe.ts; prompt.ts; browse.ts; settings.ts; handoff.css +- kind: decision +- logged: v0.6.0 · 2026-12-02 +One `fsh-scrim`/`fsh-dialog` built once in `#overlay-root` and patched per offer: title, "1 of n", " is handing over : <what>.", Sent as, Contents, Maps and From (from `POST /api/handoff/inspect`), Add to this document or As a new document, then Decline, Open once, Always allow <App> (hidden when the app is unknown); Escape declines; its size is reserved so it keeps one box between offers. `handoff.browse` ("Open a Hand-off...", File menu) lists `GET /api/handoff/available` or takes a path; `handoff.settings` opens the Preferences page `handoff` with ask, always or block per app and the watched folders. 60 strings in the `handoff` namespace; the tables were first written by a script as new files with English placeholders and later translated. + +### (CAD and hand-off window) · verification +- refers-to: src/ui/cad/, src/ui/handoff/ +- kind: verification +- logged: v0.6.0 · 2026-12-02 +CAD: headless Chrome over CDP against a release engine and a real cache: the page showed Not installed with the published record (7,061 files, 955 MB); Download fetched occt-8.0.1 for real (download about 20 s, unpack and verify about 60 s) and the facts switched to Installed; Check the worker gave "occt-8.0.1, OpenCascade 8.0.1, protocol 2"; the sheet with an empty cache offered and ran the download; an import at Custom 0.03 % and 15 degrees gave 4,882 triangles; re-tessellation Draft (2,276), High (7,438) and Undo back with the old part id; the disabled reason with only a plain sphere selected; a worker hello timeout shown in the dialog. The import itself ran through a stand-in hiding `import.start`, since the engine of that base did not route STEP to jobs. Hand-offs: real FormSculpt sends and FormSurface exports during a session gave "1 of 4" prompts; Open once, Always allow, Decline and a blocked app behaved; the dialog kept the same top and height across offers; Open a Hand-off listed seven and opened FormFabric's dress as a new document, path-traced. Not run: Tauri, a download cancel, byte counts, `cad.estimate`, `context.part` (nothing opens it yet). + +## Materials + +### src/ui/pages/material.ts, src/ui/inspector.ts · the Material page +- refers-to: src/ui/pages/material.ts :: mountMaterialPage; src/ui/inspector.ts +- kind: decision +- logged: v0.6.0 · 2026-12-02 +inspector.ts's material page line now mounts `mountMaterialPage` (two lines changed). Sections in order, each mounted once: Materials, Parameters, Textures, Graph, Labels, Library. The page follows the viewport selection (active part, else the first selected part, groups walked down to parts) only when the selection changes, and keeps a just-created key for 4 s until the summary lists it. Labels: `mountLabels` once into a 120 px reserved host, `show(key)` only when the material changes; the labels module is still the reserved stub. + +### src/ui/material/store.ts, edits.ts, swatch.ts · reading materials and editing them in one undo step +- refers-to: src/ui/material/store.ts :: MaterialStore; src/ui/material/edits.ts :: Edits; src/ui/material/swatch.ts :: Swatches; src/ui/material/zip.ts; src/ui/material/model.ts +- kind: decision +- logged: v0.6.0 · 2026-12-02 +No engine command returns one material's params, slots and graph, so `MaterialStore` uses `material.get {key}` when the catalogue lists it and otherwise reads `GET /api/engine/snapshot` as a stored ZIP (`scene.json` textures, `materials/<key>.json`), skipped when `X-Formshot-Content-Revision` is unchanged. Reads happen only while the page is visible, debounced 90 ms, never during a gesture, and a read that started before a local patch is dropped. It marks itself stale on every mutating dispatch (and asks for a summary refresh when the change level is none, since `material.create` and `material.rename` otherwise never refresh). `Edits.live` coalesces to one command per frame per target and `commit` sends `history.barrier`, so a drag is one undo step. Swatches are 56 px balls drawn into each row's existing canvas: constant materials shaded locally from their params (live while dragging), others from `material.preview_maps`, cached by key and an FNV-1a signature (256 entries), two requests at a time. + +### src/ui/material/list.ts, params.ts, slots.ts, image.ts, graph.ts, library.ts · the sections +- refers-to: src/ui/material/list.ts; params.ts; slots.ts; image.ts; graph.ts; library.ts; rows.ts; popover.ts; glyphs.ts; src/styles/material.css +- kind: decision +- logged: v0.6.0 · 2026-12-02 +List: fixed 40 px rows patched in place, inline rename on F2 or double click; New (a type picker grouped by category, measured metals under Metal), Assign to selection, Duplicate, Rename, Delete (kept clickable while in use so a toast can say why; a disabled button shows no tooltip in most webviews). Parameters: the Type select with a keep values or reset to type popover (`material.set_type keep`), rows keyed by field from the type's `shown` specs and reused across materials and types, and a collapsed All parameters block (33 fields) built on first open; graph-driven fields are disabled with a Graph tag, slotted fields carry a Texture tag. Textures: one editor per slot with every `TextureSlot` field (rotation in degrees) through `material.set_slot` partials and `material.clear_slot`; Add a map for any free slottable input. Images: the Tauri dialog path on the desktop, a file input and `POST /api/textures` in a browser, the upload deleted when `set_slot` fails. Graph: node count, inputs driven, and Edit graph (`openGraphEditor`). Library: Save to library (`library.save {material, name, category}`), disabled with the reason until the catalogue lists it. Hand-drawn icons (copy, pencil, assign, graph, texture, unlink, bookmark) are in material/glyphs.ts. 152 strings in the `material` namespace. + +### src/ui/graph/ · the node editor window +- refers-to: src/ui/graph/index.ts :: openGraphEditor; editor.ts :: GraphEditor; model.ts; commit.ts :: Committer; canvas.ts :: GraphCanvas; views.ts :: NodeView, OutputView; window.ts :: EditorWindow; links.ts :: LinkLayer; interact.ts; ramp.ts; menu.ts :: PickMenu +- kind: decision +- logged: v0.6.0 · 2026-12-02 +One editor window per workspace (an overlay panel at `--z-popover`, moved by its header, resized from eight edges, its box in `sessionStorage['formshot.graph.window']`). The editor keeps a local graph and sends it whole with `material.set_graph` after each finished gesture, skipping sends that would not change the last accepted graph; value drags run inside `history.begin_group` (at most one send per frame) so a drag is one undo step. Refusals the window can see (type mismatches using the same conversion table as fsh-scene, loops, self links, output to output) are refused before sending with the reason; a graph the engine still refuses stays on screen with the offending link dashed red, both nodes badged and Revert offered. Outside changes (undo, agents, other views) mark the editor stale and it re-reads 120 ms later and patches only nodes whose shape changed. The output node and the view are kept per material for the session only (the graph has no field for them). The output node shows the `material.preview_maps` base colour; per-node swatches are not built. Keys: Tab or Shift+A add, L connect or disconnect, Delete, Mod+D, copy, cut and paste between materials, F frame, arrows move focus, ? help. A node drag writes one style per node and one `d` per touching link per frame (MutationObserver). 189 strings in the `graph` namespace, 14 others left to the namespaces that already translate them. Like the page, it reads materials through the snapshot when `material.get` is missing. + +### src/engine/raster/scene-data.ts, materials.ts, renderer.ts, shaders.ts, src/ui/raster-view.ts · preview maps in the raster material mode +- refers-to: src/engine/raster/scene-data.ts :: MeshData.uv0, MeshData.tangents, FLAG_UV0, FLAG_TANGENTS, SceneMeshes.materials, RasterInstance.tinted; src/engine/raster/materials.ts :: MaterialSource, PREVIEW_SIZES; src/engine/raster/renderer.ts :: setMaterial, hasMaterial, keepMaterials, setEnvironmentTint; src/engine/raster/shaders.ts :: MESH_VS, SURFACE_FS; src/ui/raster-view.ts +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The Material preview mode now samples the engine's baked `material.preview_maps` by mesh uv0, so it agrees with where the tracers put a material's colour, roughness, metalness and normal detail on uv-mapped parts. Meshes upload uv0 at attribute 2 and tangents at 3; maps are mipmapped REPEAT textures with trilinear filtering and up to 4x anisotropy (base colour `SRGB8_ALPHA8`, the others `RGBA8`, units 1 to 4), sampled at `(u, 1 - v)` because the bake's row 0 is v = 1. A new upload replaces the old textures only after all four exist, so an edit never flashes the constant look. Constant materials and parts without uv0 use the answer's `values` (or the part colour when tinted). The normal map is tangent space in T = mesh tangent (Gram-Schmidt) and B = sign * cross(N, T), or the screen-derivative frame without tangents (the CPU's dpdu/dpdv fallback). The four Gaussian light lobes became GGX lights (height-correlated Smith, Schlick Fresnel) with roughness widened by each light's size, `a = sqrt(r^4 + 0.5 w0)`; environment terms are scaled by an environment tint (the summary environment's average relative to 0.55). Solid mode is byte for byte the old path. Preview sizes follow the viewport quality (64, 128, 256). Maps are fetched only for materials visible parts wear, one request per material at a time, freed when unused. `?raster-debug` exposes the view at `window.__formshotRaster`. + +### (materials window) · verification +- refers-to: src/ui/pages/material.ts, src/ui/material/, src/ui/graph/, src/engine/raster/ +- kind: verification +- logged: v0.6.0 · 2026-12-02 +Material page, headless Chrome with the CPU throttled 4x against a debug engine: swatches; rubber, copper, ceramic, glass, emissive, fabric, gem, wood and metallic paint created; duplicate, rename, delete refused with the reason; the list followed viewport clicks; roughness drags gave history depth 0, 1, 2 and one undo restored the first; plastic to rubber reset and rubber to metal kept; 33 All parameters rows; an uploaded PNG on base colour with box projection, scale and rotation drags one step each, mirror, linear, multiply, a normal map added and a slot cleared; 22 marked nodes unchanged across edits and switches; zero layout shift during drags. Graph editor: a wood-like graph built by pointer and keys compiled with base_color, specular_roughness and normal outputs; refusals shown before and after the engine; undo and redo without rebuilding nodes; copy and paste into a second material; window box restored from sessionStorage; Add image as one undo step through a stand-in upload route. Raster view: maps matched the baked base colour in orientation on a plane; a material edit fetched only that material with no constant-look frame; a transform edit fetched nothing; texture memory dropped on `material.remove` and came back on undo; quality changes refetched at 64, 128 and 256; the WebGPU mirror read flagged mesh blocks. Not run: Tauri, `library.save` from the page, `material.get` (it does not exist), real touch or trackpad, the WebGPU path tracer (SwiftShader timed out compiling). Swatches and maps of procedural materials were grey on that base; image slots show their fallbacks because the preview bake passes `NoTextures`. + +## The material library + +### src/ui/library.ts, src/ui/library/panel.ts, grid.ts, thumbs.ts · the panel and its virtual grid +- refers-to: src/ui/library.ts; src/ui/library/panel.ts :: mountLibraryPanel; grid.ts :: VirtualGrid; thumbs.ts :: ThumbLoader; data.ts; state.ts +- kind: decision +- logged: v0.6.0 · 2026-12-02 +library.ts now hands its host to `mountLibraryPanel` and keeps only the splitter; the static shelves, categories and empty state of 0.4.0 are gone, and the new state file reads the old `formshot.library.shelf` key once. The grid is virtual: a scroll container with `contain: strict` holds a spacer sized by a CSS variable, tiles are absolutely positioned by `translate3d`, the pool is `(visible rows + 1 + 2 overscan rows) * columns` nodes and item i lives in slot `i % pool`, so scrolling and new results rebind the same nodes in place; tile sizes are fixed per step (72, 96, 128 px plus a 22 px name line). Thumbnails are `<img>` without `src` over a placeholder of the same size, requested only when an IntersectionObserver sees the tile (newest first, three at a time, cancelled when the tile leaves, aborted when nobody waits), at `/api/library/thumbnail/<id>?size=128|256&h=<sha256>` so cached pictures are immutable. One `library.list {shelf?, query?}` per shelf or search change; categories and their twelve counts are computed locally from that reply. Shelves: All, Favorites, Recent, In project (the summary's materials), User. State (shelf, category, query, size, scroll, active tile) is in `localStorage['formshot.library.panel']` and scroll and the active tile are restored only after the first real list arrives. The removed 0.4.0 panel body, quoted in full (the `t` import and the splitter code around it stayed): + +```ts +import { el, q, setAttr, setClass } from '../shell/dom'; +import { icon } from '../shell/icons'; + +const SHELF_KEY = 'formshot.library.shelf'; +const SHELVES: ReadonlyArray<readonly [string, string]> = [ + ['all', 'All'], + ['favorites', 'Favorites'], + ['recent', 'Recent'], + ['project', 'In project'], +]; +const CATEGORIES: readonly string[] = ['Metal', 'Plastic', 'Glass', 'Paint', 'Rubber', 'Fabric', 'Wood', 'Stone', 'Ceramic', 'Liquid', 'Gem', 'Emissive']; + +function storedShelf(): string { + try { + const v = localStorage.getItem(SHELF_KEY); + return SHELVES.some(([id]) => id === v) ? v as string : 'all'; + } catch { + return 'all'; + } +} + +function saveShelf(id: string): void { + try { localStorage.setItem(SHELF_KEY, id); } catch { return; } +} + const shelves = SHELVES.map(([id, label]) => `<button class="fsh-ws-shelf" type="button" role="tab" data-shelf="${id}" aria-selected="false">${t(label)}</button>`).join(''); + const cats = CATEGORIES.map((c) => `<li><button class="fsh-ws-cat" type="button" data-cat="${c}" aria-pressed="false"><span class="fsh-ws-cat-name">${t(c)}</span><span class="fsh-ws-cat-count fsh-tabular" data-no-i18n>0</span></button></li>`).join(''); + const root = el(`<div class="fsh-ws-lib"> +<div class="fsh-ws-lib-head"><span class="fsh-ws-lib-title">${icon('library', 14)}<span>${t('Library')}</span></span></div> +<label class="fsh-ws-lib-search">${icon('search', 14)}<input class="fsh-input" type="search" placeholder="Search materials" aria-label="Search materials" spellcheck="false" autocomplete="off"></label> +<div class="fsh-ws-lib-shelves" role="tablist" aria-label="Shelves">${shelves}</div> +<div class="fsh-ws-lib-body"> + <ul class="fsh-ws-lib-cats" aria-label="Categories">${cats}</ul> + <div class="fsh-ws-lib-grid" role="list"> + <div class="fsh-ws-empty is-center">${icon('material', 28)}<p>${t('Materials arrive in 0.5.0')}</p></div> + </div> +</div> +<div class="fsh-ws-splitter" role="separator" aria-orientation="vertical" aria-label="Resize the library" tabindex="0"></div> +</div>`); + host.appendChild(root); + + let shelf = storedShelf(); + let category = ''; + const paint = (): void => { + for (const b of root.querySelectorAll<HTMLElement>('.fsh-ws-shelf')) { + const on = b.dataset.shelf === shelf; + setAttr(b, 'aria-selected', on ? 'true' : 'false'); + setAttr(b, 'tabindex', on ? '0' : '-1'); + } + for (const b of root.querySelectorAll<HTMLElement>('.fsh-ws-cat')) setAttr(b, 'aria-pressed', b.dataset.cat === category ? 'true' : 'false'); + }; + q(root, '.fsh-ws-lib-shelves').addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest<HTMLElement>('.fsh-ws-shelf'); + if (!b?.dataset.shelf) return; + shelf = b.dataset.shelf; + saveShelf(shelf); + paint(); + }); + q(root, '.fsh-ws-lib-cats').addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest<HTMLElement>('.fsh-ws-cat'); + if (!b?.dataset.cat) return; + category = category === b.dataset.cat ? '' : b.dataset.cat; + paint(); + }); + const search = q<HTMLInputElement>(root, 'input[type="search"]'); + search.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && search.value) { search.value = ''; e.stopPropagation(); } + }); + paint(); +``` + +### src/ui/library/actions.ts, details.ts, drag.ts, drop.ts, save.ts, src/ui/viewport.ts · applying, dragging and saving +- refers-to: src/ui/library/actions.ts; details.ts :: DetailsPopover; drag.ts :: PresetDrag; drop.ts :: attachPresetDrop, dropTarget; save.ts; src/ui/viewport.ts :: inputs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Window command ids are `preset.*` (`preset.apply`, `preset.applyGroup`, `preset.applySameMaterial`, `preset.favorite`, `preset.details`, `preset.remove`, `preset.saveSelected`) because Home already registers `library.*` ids for the project library; the tile menu is `context.library.tile`. Double-click or Enter applies to the selection at part scope through `library.apply`; In project tiles are document materials applied with `material.assign`, the scope resolved in the window. Drag uses pointer events, not HTML drag and drop, so modifier keys and the hint update while dragging: after 5 px a glass hint follows the pointer in `#overlay-root` at `--z-drag`, the part under the pointer is picked each frame from the raster id buffer (or `view.pick`, one request in flight), and the parts a drop would change are shown with the raster selection outline (the viewport has no hover highlight); a drop applies at part scope, Alt group, Shift same material, and a drop on empty space toasts. viewport.ts gained two lines: the import of `attachPresetDrop` and one call after `attachInput` in `inputs()`. Save (`preset.saveSelected`, hidden unless the engine has `library.save`) asks for a name and a category. The grid is one tab stop (`role="listbox"`, `aria-activedescendant`), arrows, Page Up and Down, Home and End move, Enter applies, the menu key or Shift+F10 opens the tile menu. 96 strings in the `library` namespace; a string another namespace already translates keeps that translation. + +### (library window) · verification +- refers-to: src/ui/library.ts, src/ui/library/ +- kind: verification +- logged: v0.6.0 · 2026-12-02 +Headless Chrome with the CPU throttled 4x: 1992 tiles (the 249 presets copied 8 times by a stand-in) scrolled through with 20 tile nodes before, during and after, median frame 16.7 ms; search, category, counts, every shelf, the menu, favourites, details, tile size, keyboard and reload restore all worked; no layout-shift entries. Against lib-engine's real commands and routes with engine-rendered thumbnails (about 12 s each on the loaded machine): ranked search, favourites, the user shelf, details; on the sample scene double-click and Enter applied Gold, polished, one Ctrl+Z restored the old material, a drop applied, Recent listed it; on the product scene a Shift-drop changed Body and Shoulder, an Alt-drop all four parts of the group, one Ctrl+Z undid it. Without library commands the grid says the engine has no `library.list` and the save button is hidden. Not run: Tauri, a real pointer, touch drag (off), `library.thumbnails` batch queueing (unused). + +## Labels, window textures and translations + +### src/ui/labels/ · the Labels section +- refers-to: src/ui/labels/index.ts :: mountLabels, LabelsSection; model.ts :: placeFromHit; image.ts; place.ts :: PlaceMode; labels.css; src/ui/pages/material.ts +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The reserved stub became the Labels section the Material page already mounted (`mountLabels(host, ws)` once into a 120 px reserved host, `show(key)` on material change). It shows the label list (grip, visibility, name, file name, remove) read through `material.labels`, a status line of reserved height and the selected label's fields; the fields block stays laid out (visibility hidden) when nothing is selected and the list reserves three rows, patched with `patchList`. Width and height in mm with a link toggle (proportions from the image size when known), rotation in degrees, depth in mm, opacity, and own roughness and metalness (a checkbox, then the value). Scrubbing sends coalesced `material.label_set` calls that merge, and release or any discrete edit sends `history.barrier`, so a drag is one undo step. Reordering is pointer based (no HTML drag and drop, which the Tauri webview may take for file drops): the row moves by transform, a drop line marks the slot, release sends `material.label_move`. Place on Surface takes the next pointerdown inside `.fsh-ws-vp-frame` through a window capture listener (so selection never sees it; Escape cancels), asks `view.pick` for the node, world point and normal, then `scene.meshes` for that instance's world matrix and material; it refuses a part that does not wear the shown material, and sends one `label_set {origin, normal, up}` in object space (up from world +Y, or world -Z on faces pointing up or down). Add from Image picks an image (the Tauri dialog path, or `POST /api/textures` in a browser) and sends `label_add` with 0.1 m width at the image's proportions; on the desktop the size is unknown until the engine reads it, so a second `label_set` fixes the height (two undo steps there). 40 strings in the `labels` namespace, first English placeholders, translated into the 23 languages by a later pass (tr-7). Verified in headless Chrome against an engine built from the labels branch through a harness copy of the page: empty state, two rows, unchanged section height with 0, 2 and 1 labels, Place on Surface on a cube's front face without changing the selection, a proportional width scrub as one undo step, reorder with the same nodes, hide, own roughness, removal; the shipped page's mount was checked after the merge only by type-checking. Not run: the desktop dialog path. + +### src/engine/gpu/textures.ts, texture-worker.ts, wasm.ts, engine.ts · textures for the window's engine +- refers-to: src/engine/gpu/textures.ts :: TextureFeed, WORKER_IDLE_MS; texture-worker.ts; wasm.ts :: compiled; engine.ts :: TEXTURE_CHECK_MS, rawStatus +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`TextureFeed` gets embedded bytes from the session (`take_embedded`) and outside files from `GET /api/engine/texture?path=` with `If-None-Match` (a file is fetched once per size and modified time, 304 after), decodes one image at a time in a module worker (`initSync` on the same compiled module the window uses: `wasm.ts` now compiles the `.wasm` itself and passes the module to init, so `compiled()` can hand it over), re-decodes every use of a file only when its ETag changed and otherwise only new uses, forgets validators of paths the document dropped, and stops the worker after 15 s idle (`WORKER_IDLE_MS`); without a worker it decodes in the window with a task yield between images. The engine loads textures after the first mirror sync and before `create_viewport`, and after each mirror change (and every 5 s for outside files, `TEXTURE_CHECK_MS`) before `set_scene`, so the viewport keeps refining the old picture and restarts once. A failed texture samples its fallback and becomes a note in the device menu ("Texture {name} could not be used ({reason}); its material shows the fallback" or the count form) and one console warning; the report survives a fallback to streamed frames. These two strings were in no i18n table at first; they are now in the `gpuview` namespace in every language (tr-7). Run with a stubbed viewport (SwiftShader cannot compile the kernel): textures ready before the viewport was created, all decoded in the worker; a 2048 px, 11.4 MB PNG gave exactly one `set_scene` 913 ms later with 55 frames drawn meanwhile and a largest gap of 45 ms; held texels went 12.9 MB, 35.0 MB, back to 12.9 MB when the image was dropped; a file rewritten on disk re-decoded once, unchanged files got 304. No textured picture was drawn by the real GPU viewport. + +### src/i18n/modules/{import,handoff,cad,material,graph,library}/ · translations +- refers-to: src/i18n/modules/*/<code>.json +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Six translators filled the six namespaces in 23 languages (de, fr, it, es; nl, sv, da, nb; fi, pl, cs, hu; ru, uk, tr, pt-BR; ja, ko, zh-CN, zh-TW; th, vi, id): 674 strings per language (import 88, handoff 60, cad 89, material 152, graph 189, library 96). Each kept its values in tables outside the repository and wrote the files with a script that asserted every key, the key order, identical `{placeholder}` sets and no en or em dash; registers follow the existing tables (de du, fr vous, it tu, es tu, pt-BR você). es-MX and fr-CA stay `{}`. `./formshot i18n check` passes, though it reports only the shell tables, so the module checks are the scripts' assertions. The interface lookup is one table across modules, so a key shared by two namespaces gets one translation: the graph help's Space key and the material page's object or world Space collided, and the graph help now asks for "Space bar" (lead commit ad44afb). The `labels` namespace (40 strings) and the two texture notes of the GPU viewport (now in `gpuview`) were translated afterwards into the same 23 languages by one more pass (tr-7), with terms taken from each language's material, graph and workspace tables; es-MX and fr-CA stay `{}`. + +## The polish pass + +### src/ui/material/store.ts, src/ui/graph/source.ts, src/ui/cad/parts.ts · engine reads instead of the project snapshot +- refers-to: src/ui/material/store.ts :: MaterialStore; src/ui/graph/source.ts :: GraphSource; src/ui/cad/parts.ts :: cadIndex +- kind: decision +- logged: v0.6.0 · 2026-12-02 +This supersedes the snapshot reading described in the Materials and CAD entries above. The Material page and the graph editor read a material only through `material.get` (its `textures` give the document's texture references), and the page loads `material.types` when its store is built; the CAD module builds its index from `cad.parts`. None of them reads `GET /api/engine/snapshot` any more (checked in headless Chrome: zero snapshot reads while the page, the node editor and the re-tessellate dialog worked). The two stored-ZIP readers they used were deleted. Removed `frontend/src/ui/material/zip.ts`, quoted in full: + +```ts +const EOCD = 0x06054b50; +const CENTRAL = 0x02014b50; +const LOCAL = 0x04034b50; + +export interface StoredMember { name: string; bytes: Uint8Array } + +export function readStoredZip(buf: ArrayBuffer, want: (name: string) => boolean): StoredMember[] { + const view = new DataView(buf); + const bytes = new Uint8Array(buf); + const names = new TextDecoder(); + let end = -1; + for (let i = buf.byteLength - 22; i >= Math.max(0, buf.byteLength - 22 - 65535); i--) { + if (view.getUint32(i, true) === EOCD) { end = i; break; } + } + if (end < 0) throw new Error('The project snapshot is not a ZIP archive'); + const count = view.getUint16(end + 10, true); + let at = view.getUint32(end + 16, true); + const out: StoredMember[] = []; + for (let i = 0; i < count; i++) { + if (view.getUint32(at, true) !== CENTRAL) throw new Error('The project snapshot has a damaged directory'); + const method = view.getUint16(at + 10, true); + const size = view.getUint32(at + 20, true); + const nameLen = view.getUint16(at + 28, true); + const extraLen = view.getUint16(at + 30, true); + const commentLen = view.getUint16(at + 32, true); + const local = view.getUint32(at + 42, true); + const name = names.decode(bytes.subarray(at + 46, at + 46 + nameLen)); + at += 46 + nameLen + extraLen + commentLen; + if (method !== 0 || !want(name)) continue; + if (view.getUint32(local, true) !== LOCAL) continue; + const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true); + out.push({ name, bytes: bytes.subarray(start, start + size) }); + } + return out; +} +``` + +Removed `frontend/src/ui/graph/zip.ts`, quoted in full: + +```ts +const EOCD = 0x06054b50; +const CENTRAL = 0x02014b50; +const LOCAL = 0x04034b50; + +export function zipMembers(bytes: Uint8Array, want: (name: string) => boolean): Map<string, Uint8Array> { + const out = new Map<string, Uint8Array>(); + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let end = -1; + for (let i = bytes.byteLength - 22; i >= Math.max(0, bytes.byteLength - 22 - 65535); i--) { + if (dv.getUint32(i, true) === EOCD) { end = i; break; } + } + if (end < 0) throw new Error('not a project file'); + const total = dv.getUint16(end + 10, true); + let at = dv.getUint32(end + 16, true); + const decoder = new TextDecoder(); + for (let i = 0; i < total; i++) { + if (at + 46 > bytes.byteLength || dv.getUint32(at, true) !== CENTRAL) throw new Error('damaged project file'); + const method = dv.getUint16(at + 10, true); + const size = dv.getUint32(at + 20, true); + const nlen = dv.getUint16(at + 28, true); + const elen = dv.getUint16(at + 30, true); + const clen = dv.getUint16(at + 32, true); + const local = dv.getUint32(at + 42, true); + const name = decoder.decode(bytes.subarray(at + 46, at + 46 + nlen)); + at += 46 + nlen + elen + clen; + if (method !== 0 || !want(name)) continue; + if (dv.getUint32(local, true) !== LOCAL) continue; + const start = local + 30 + dv.getUint16(local + 26, true) + dv.getUint16(local + 28, true); + out.set(name, bytes.subarray(start, start + size)); + } + return out; +} + +export function memberJson(members: Map<string, Uint8Array>, name: string): unknown { + const b = members.get(name); + if (!b) return null; + try { return JSON.parse(new TextDecoder().decode(b)) as unknown; } catch { return null; } +} +``` + +### src/shell/commands.ts, src/ui/graph/editor.ts, commit.ts · history refreshes and merged value drags +- refers-to: src/shell/commands.ts (client.onDispatch hook); src/ui/graph/editor.ts :: changed; src/ui/graph/commit.ts :: Committer +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Commands that answer `change: none` (undo or redo of an edit to an unused material, `material.create`, `set_graph` on an unused material, `history.end_group`) did not refresh the summary, so Undo and Redo went stale. One hook in the workspace commands now schedules a summary refresh after any mutating dispatch that answers change none, from every module, and the material store's and graph editor's own workarounds were removed. The graph editor's value drags now send `material.set_graph {merge: true}` at most once per frame and end with `history.barrier`, instead of a history group, so another view dispatching during a drag no longer joins the group (Add image still uses a group, being two different commands); a 13-call scrub was one undo step. Its quiet list gained `material.get` and `material.labels`, and `changed(live)` lost its label argument; the strings "Change a node value" and "Change a node setting" are no longer used but stay in the graph tables. Outside edits (agents, MCP) now arrive as change events from the service, so the window follows them (checked: an `/api/agent` create and an MCP rename appeared in the open material list). diff --git a/frontend/package-lock.json b/frontend/package-lock.json index d388543d..2d5d955a 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formshot", - "version": "0.4.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formshot", - "version": "0.4.0", + "version": "0.6.0", "license": "Apache-2.0", "dependencies": { "@fontsource/inter": "5.3.0", diff --git a/frontend/package.json b/frontend/package.json index 3bb21640..f2dd497d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "formshot", - "version": "0.4.0", + "version": "0.6.0", "private": true, "description": "FormShot product renderer", "license": "Apache-2.0", diff --git a/frontend/src/engine/gpu/engine.ts b/frontend/src/engine/gpu/engine.ts index 3a06fff1..f5b4c467 100644 --- a/frontend/src/engine/gpu/engine.ts +++ b/frontend/src/engine/gpu/engine.ts @@ -2,6 +2,7 @@ import { events } from '../../shell/events'; import { t } from '../../i18n'; import { viewportEngines, type Regime, type ViewportCamera, type ViewportEngine, type ViewportStatus } from '../viewport-engine'; import { ServiceMirror } from './mirror'; +import { TextureFeed, type TextureReport } from './textures'; import { guardMs, maxSide, parseRefusals, preference, refusalText, rememberFailure } from './probe'; import type { WasmEngine, WasmSession, WasmViewport } from './wasm'; @@ -17,6 +18,15 @@ const DEBUG_HANDLE = '__formshotGpuview'; const REGIMES: readonly Regime[] = ['moving', 'refining', 'settled']; const FIRST_PASS_POLL_MS = 100; +const TEXTURE_CHECK_MS = 5000; + +function textureNote(r: TextureReport): string { + if (!r.failed.length) return ''; + if (r.failed.length > 1) return t('{count} textures could not be used; their materials show the fallback', { count: r.failed.length }); + const f = r.failed[0]; + const name = f.path.split(/[\\/]/).pop() || f.path; + return t('Texture {name} could not be used ({reason}); its material shows the fallback', { name, reason: f.reason }); +} interface RawStatus { samples?: number; target?: number; regime?: string; adapter?: string; resolution_scale?: number; frames?: number; error?: string | null; @@ -52,6 +62,9 @@ export class GpuEngine implements ViewportEngine { fallbackReason = ''; private session: WasmSession | null = null; private mirror: ServiceMirror | null = null; + private textures: TextureFeed | null = null; + private textureNote = ''; + private textureChecked = 0; private viewport: WasmViewport | null = null; private canvas: HTMLCanvasElement | null = null; private sizer: ResizeObserver | null = null; @@ -86,7 +99,11 @@ export class GpuEngine implements ViewportEngine { } rawStatus(): string { - const extra = { startup_ms: this.startup, mirror: this.mirror ? { mode: this.mirror.mode, bytes: this.mirror.bytes, notes: this.mirror.notes } : null }; + const extra = { + startup_ms: this.startup, + mirror: this.mirror ? { mode: this.mirror.mode, bytes: this.mirror.bytes, notes: this.mirror.notes } : null, + texture_feed: this.textures ? { ...this.textures.report, note: this.textureNote } : null, + }; if (!this.viewport) return JSON.stringify({ fallback: this.fallbackReason || null, ...extra }); let s: Record<string, unknown> = {}; try { s = JSON.parse(this.viewport.status()) as Record<string, unknown>; } catch { s = {}; } @@ -113,7 +130,7 @@ export class GpuEngine implements ViewportEngine { private set(next: ViewportStatus): void { const a = this.info; if (a.state === next.state && a.samples === next.samples && a.target === next.target && a.regime === next.regime && a.device === next.device - && a.resolutionScale === next.resolutionScale && a.message === next.message) return; + && a.resolutionScale === next.resolutionScale && a.message === next.message && a.note === next.note) return; this.info = next; this.emit(); } @@ -224,6 +241,8 @@ export class GpuEngine implements ViewportEngine { this.session = session; this.mirror = new ServiceMirror(session); await this.mirror.sync(true); + this.textures = new TextureFeed(session, this.engine); + await this.loadTextures(); this.readIndex(); this.applyCamera(); if (!this.canvas) throw new Error(t('The viewport gave the GPU engine no canvas')); @@ -306,10 +325,29 @@ export class GpuEngine implements ViewportEngine { const state: ViewportStatus['state'] = !started ? 'starting' : regime === 'settled' ? 'settled' : 'converging'; this.set({ kind: GPU_KIND, state, regime, samples, target, device: s.adapter || this.adapterName, backend: 'WebGPU', - resolutionScale: typeof s.resolution_scale === 'number' ? s.resolution_scale : null, converged: null, message: '', + resolutionScale: typeof s.resolution_scale === 'number' ? s.resolution_scale : null, converged: null, message: '', note: this.textureNote, }); } + private async loadTextures(): Promise<boolean> { + const feed = this.textures; + if (!feed) return false; + let changed = false; + try { + changed = await feed.load(); + } catch (err) { + console.warn(`WebGPU viewport textures: ${message(err)}`); + } + this.textureChecked = performance.now(); + const note = textureNote(feed.report); + if (note !== this.textureNote) { + this.textureNote = note; + if (note) console.warn(`WebGPU viewport: ${note}`); + this.set({ ...this.info, note }); + } + return changed; + } + private schedulePoll(ms: number): void { window.clearTimeout(this.pollTimer); this.pollTimer = window.setTimeout(() => { void this.poll(); }, ms); @@ -320,8 +358,10 @@ export class GpuEngine implements ViewportEngine { if (this.syncing) { this.schedulePoll(POLL_MS); return; } this.syncing = true; try { - if (await this.mirror.sync()) { - if (this.fallback || !this.viewport) return; + const synced = await this.mirror.sync(); + const due = synced || performance.now() - this.textureChecked >= TEXTURE_CHECK_MS; + const loaded = due ? await this.loadTextures() : false; + if ((synced || loaded) && !this.fallback && this.viewport) { this.readIndex(); this.applyCamera(); this.viewport.set_scene(this.session.scene()); @@ -341,6 +381,7 @@ export class GpuEngine implements ViewportEngine { window.clearTimeout(this.stillTimer); this.fallbackReason = reason; if (this.gpuStarted) rememberFailure(reason); + this.textures?.close(); try { this.viewport?.free(); } catch { this.viewport = null; } this.viewport = null; const provider = viewportEngines().find((p) => p.kind === STREAMED); diff --git a/frontend/src/engine/gpu/texture-worker.ts b/frontend/src/engine/gpu/texture-worker.ts new file mode 100644 index 00000000..9a979fe7 --- /dev/null +++ b/frontend/src/engine/gpu/texture-worker.ts @@ -0,0 +1,45 @@ +interface DecoderModule { + initSync(input: { module: WebAssembly.Module }): unknown; + decode_texture(bytes: Uint8Array, path: string, colourSpace: string, mipmaps: boolean): Uint8Array; +} + +export interface DecodeJob { type: 'decode'; id: number; path: string; colourSpace: string; mipmaps: boolean; bytes: ArrayBuffer } +export type WorkerRequest = { type: 'init'; module: WebAssembly.Module } | DecodeJob; +export type WorkerReply = + | { type: 'ready' } + | { type: 'broken'; reason: string } + | { type: 'done'; id: number; packed: ArrayBuffer; ms: number } + | { type: 'failed'; id: number; reason: string }; + +const found = import.meta.glob<DecoderModule>('../pkg/fsh_wasm.js', { eager: true }); +const scope = self as unknown as { onmessage: ((e: MessageEvent<WorkerRequest>) => void) | null; postMessage(m: WorkerReply, transfer?: Transferable[]): void }; +let decoder: DecoderModule | null = null; + +function reason(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +scope.onmessage = (e: MessageEvent<WorkerRequest>): void => { + const msg = e.data; + if (msg.type === 'init') { + const mod = Object.values(found)[0]; + if (!mod) { scope.postMessage({ type: 'broken', reason: 'no package' }); return; } + try { + mod.initSync({ module: msg.module }); + decoder = mod; + scope.postMessage({ type: 'ready' }); + } catch (err) { + scope.postMessage({ type: 'broken', reason: reason(err) }); + } + return; + } + if (!decoder) { scope.postMessage({ type: 'failed', id: msg.id, reason: 'the decoder is not ready' }); return; } + const begun = performance.now(); + try { + const out = decoder.decode_texture(new Uint8Array(msg.bytes), msg.path, msg.colourSpace, msg.mipmaps); + const packed = out.byteOffset === 0 && out.byteLength === out.buffer.byteLength ? out.buffer as ArrayBuffer : out.slice().buffer as ArrayBuffer; + scope.postMessage({ type: 'done', id: msg.id, packed, ms: performance.now() - begun }, [packed]); + } catch (err) { + scope.postMessage({ type: 'failed', id: msg.id, reason: reason(err) }); + } +}; diff --git a/frontend/src/engine/gpu/textures.ts b/frontend/src/engine/gpu/textures.ts new file mode 100644 index 00000000..0156d7b7 --- /dev/null +++ b/frontend/src/engine/gpu/textures.ts @@ -0,0 +1,245 @@ +import { api } from '../../shell/api'; +import type { WasmEngine, WasmSession } from './wasm'; +import type { WorkerReply, WorkerRequest } from './texture-worker'; + +const TEXTURE_ROUTE = '/api/engine/texture'; +const WORKER_IDLE_MS = 15000; +const WORKER_START_MS = 20000; + +interface Listed { + path: string; + colour_space: string; + mipmaps: boolean; + embedded: boolean; + state: 'ready' | 'failed' | 'pending'; + reason: string | null; +} + +export interface TextureProblem { path: string; reason: string } + +export interface TextureReport { + count: number; + ready: number; + pending: number; + failed: TextureProblem[]; + bytes: number; + fetched: number; + unchanged: number; + decoded: number; + decodeMs: number; + worker: 'worker' | 'window' | 'none'; +} + +type Job = { resolve: (packed: ArrayBuffer) => void; reject: (reason: Error) => void }; + +function message(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +function nextTask(): Promise<void> { + return new Promise((resolve) => { window.setTimeout(resolve, 0); }); +} + +class Decoder { + private worker: Worker | null = null; + private ready: Promise<boolean> | null = null; + private readonly jobs = new Map<number, Job>(); + private nextId = 1; + private idle: number | undefined; + broken = false; + + constructor(private readonly engine: WasmEngine) {} + + private start(): Promise<boolean> { + if (this.ready) return this.ready; + const module = this.engine.compiled(); + if (!module || typeof Worker === 'undefined') { this.broken = true; return Promise.resolve(false); } + this.ready = new Promise<boolean>((resolve) => { + let worker: Worker; + try { + worker = new Worker(new URL('./texture-worker.ts', import.meta.url), { type: 'module' }); + } catch { + this.broken = true; + resolve(false); + return; + } + this.worker = worker; + const timer = window.setTimeout(() => { this.broken = true; this.close(); resolve(false); }, WORKER_START_MS); + worker.onmessage = (e: MessageEvent<WorkerReply>): void => { + const r = e.data; + if (r.type === 'ready') { window.clearTimeout(timer); resolve(true); return; } + if (r.type === 'broken') { window.clearTimeout(timer); this.broken = true; this.close(); resolve(false); return; } + const job = this.jobs.get(r.id); + if (!job) return; + this.jobs.delete(r.id); + if (r.type === 'done') job.resolve(r.packed); + else job.reject(new Error(r.reason)); + this.rest(); + }; + worker.onerror = (): void => { window.clearTimeout(timer); this.broken = true; this.close(); resolve(false); }; + const init: WorkerRequest = { type: 'init', module }; + worker.postMessage(init); + }); + return this.ready; + } + + private rest(): void { + window.clearTimeout(this.idle); + if (this.jobs.size === 0) this.idle = window.setTimeout(() => this.close(), WORKER_IDLE_MS); + } + + async decode(path: string, colourSpace: string, mipmaps: boolean, bytes: ArrayBuffer): Promise<ArrayBuffer | null> { + if (this.broken || !(await this.start()) || !this.worker) return null; + window.clearTimeout(this.idle); + const id = this.nextId++; + const worker = this.worker; + return new Promise<ArrayBuffer>((resolve, reject) => { + this.jobs.set(id, { resolve, reject }); + const job: WorkerRequest = { type: 'decode', id, path, colourSpace, mipmaps, bytes }; + worker.postMessage(job, [bytes]); + }); + } + + close(): void { + window.clearTimeout(this.idle); + this.worker?.terminate(); + this.worker = null; + this.ready = null; + for (const job of this.jobs.values()) job.reject(new Error('the decoding worker stopped')); + this.jobs.clear(); + } +} + +export class TextureFeed { + report: TextureReport = { count: 0, ready: 0, pending: 0, failed: [], bytes: 0, fetched: 0, unchanged: 0, decoded: 0, decodeMs: 0, worker: 'none' }; + private readonly tags = new Map<string, string>(); + private readonly decoder: Decoder; + private closed = false; + + constructor(private readonly session: WasmSession, engine: WasmEngine) { + this.decoder = new Decoder(engine); + } + + private list(): Listed[] { + try { + const o = JSON.parse(this.session.textures()) as { textures?: Listed[]; bytes?: number }; + this.report.bytes = typeof o.bytes === 'number' ? o.bytes : 0; + return Array.isArray(o.textures) ? o.textures : []; + } catch { + return []; + } + } + + private summarise(list: Listed[]): void { + const r = this.report; + r.count = list.length; + r.ready = list.filter((e) => e.state === 'ready').length; + r.pending = list.filter((e) => e.state === 'pending').length; + r.failed = list.filter((e) => e.state === 'failed').map((e) => ({ path: e.path, reason: e.reason ?? '' })); + } + + private async file(path: string, settled: boolean): Promise<{ bytes: ArrayBuffer; fresh: boolean } | 'unchanged'> { + const headers: Record<string, string> = {}; + const tag = this.tags.get(path); + if (tag && settled) headers['If-None-Match'] = tag; + const res = await fetch(`${api.url(TEXTURE_ROUTE)}?path=${encodeURIComponent(path)}`, { headers, cache: 'no-store' }); + if (res.status === 304) { this.report.unchanged++; return 'unchanged'; } + if (!res.ok) { + let detail = ''; + try { const b = await res.json() as { detail?: unknown }; detail = typeof b.detail === 'string' ? b.detail : ''; } catch { detail = ''; } + this.tags.delete(path); + throw new Error(detail || `HTTP ${res.status}`); + } + const bytes = await res.arrayBuffer(); + const etag = res.headers.get('ETag'); + if (etag) this.tags.set(path, etag); + else this.tags.delete(path); + this.report.fetched++; + return { bytes, fresh: !etag || etag !== tag }; + } + + private async decodeOne(e: Listed, bytes: ArrayBuffer): Promise<boolean> { + const begun = performance.now(); + const was = e.state === 'ready'; + let packed: ArrayBuffer | null = null; + try { + packed = await this.decoder.decode(e.path, e.colour_space, e.mipmaps, bytes); + } catch (err) { + if (this.closed) return false; + this.session.fail_texture(e.path, e.colour_space, e.mipmaps, message(err)); + return was; + } + if (this.closed) return false; + let put = true; + if (packed) { + this.report.worker = 'worker'; + try { + this.session.put_texture(e.path, e.colour_space, e.mipmaps, new Uint8Array(packed)); + } catch (err) { + this.session.fail_texture(e.path, e.colour_space, e.mipmaps, message(err)); + put = false; + } + } else { + this.report.worker = 'window'; + await nextTask(); + if (this.closed) return false; + put = this.session.decode_texture(e.path, e.colour_space, e.mipmaps, new Uint8Array(bytes)) == null; + } + this.report.decoded++; + this.report.decodeMs += performance.now() - begun; + return put || was; + } + + async load(): Promise<boolean> { + const list = this.list(); + let changed = false; + const byPath = new Map<string, Listed[]>(); + for (const e of list) byPath.set(e.path, [...(byPath.get(e.path) ?? []), e]); + for (const path of [...this.tags.keys()]) if (!byPath.has(path)) this.tags.delete(path); + for (const [path, entries] of byPath) { + if (this.closed) return changed; + const todo = entries.filter((e) => e.state === 'pending'); + let bytes: ArrayBuffer | null = null; + let targets = todo; + const embedded = entries[0]?.embedded ?? false; + if (embedded) { + if (!todo.length) continue; + try { + const b = this.session.take_embedded(path); + bytes = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer; + } catch (err) { + for (const e of todo) this.session.fail_texture(e.path, e.colour_space, e.mipmaps, message(err)); + continue; + } + } else { + try { + const got = await this.file(path, todo.length === 0); + if (got === 'unchanged') continue; + bytes = got.bytes; + if (got.fresh) targets = entries; + } catch (err) { + const reason = message(err); + for (const e of entries) { + if (e.state === 'failed' && e.reason === reason) continue; + this.session.fail_texture(e.path, e.colour_space, e.mipmaps, reason); + if (e.state === 'ready') changed = true; + } + continue; + } + } + if (this.closed) return changed; + for (let i = 0; i < targets.length; i++) { + const copy = i === targets.length - 1 ? bytes : bytes.slice(0); + if (await this.decodeOne(targets[i], copy)) changed = true; + if (this.closed) return changed; + } + } + this.summarise(this.list()); + return changed; + } + + close(): void { + this.closed = true; + this.decoder.close(); + } +} diff --git a/frontend/src/engine/gpu/wasm.ts b/frontend/src/engine/gpu/wasm.ts index fbcb152f..230e4990 100644 --- a/frontend/src/engine/gpu/wasm.ts +++ b/frontend/src/engine/gpu/wasm.ts @@ -16,6 +16,11 @@ export interface WasmSession { mirror_mesh(key: string, revision: number, positions: Float32Array, normals: Float32Array, indices: Uint32Array): void; mirror_apply(listingJson: string, summaryJson: string): string; scene(): WasmScene; + textures(): string; + take_embedded(path: string): Uint8Array; + put_texture(path: string, colourSpace: string, mipmaps: boolean, packed: Uint8Array): void; + fail_texture(path: string, colourSpace: string, mipmaps: boolean, reason: string): void; + decode_texture(path: string, colourSpace: string, mipmaps: boolean, bytes: Uint8Array): string | undefined; free(): void; } @@ -41,13 +46,28 @@ export interface WasmEngine { Session: new () => WasmSession; create_viewport(canvas: HTMLCanvasElement, scene: WasmScene, maxSide: number): Promise<WasmViewport>; scene_refusals(scene: WasmScene): string; + decode_texture(bytes: Uint8Array, path: string, colourSpace: string, mipmaps: boolean): Uint8Array; + compiled(): WebAssembly.Module | null; } -interface WasmModule extends WasmEngine { +interface WasmModule extends Omit<WasmEngine, 'compiled'> { default: (input?: unknown) => Promise<unknown>; } const found = import.meta.glob<WasmModule>('../pkg/fsh_wasm.js'); +const binary = import.meta.glob<string>('../pkg/fsh_wasm_bg.wasm', { query: '?url', import: 'default' }); + +async function compile(): Promise<WebAssembly.Module | null> { + const url = Object.values(binary)[0]; + if (!url) return null; + try { + const res = await fetch(await url()); + if (!res.ok) return null; + return await WebAssembly.compile(await res.arrayBuffer()); + } catch { + return null; + } +} let loading: Promise<WasmEngine> | null = null; export function packagePresent(): boolean { @@ -59,8 +79,10 @@ export function loadEngine(): Promise<WasmEngine> { const load = Object.values(found)[0]; if (!load) return Promise.reject(new Error(t('The browser engine package is not built (run ./formshot engine wasm)'))); loading = load().then(async (mod) => { - await mod.default(); - return mod; + const module = await compile(); + await mod.default(module ? { module_or_path: module } : undefined); + const engine: WasmEngine = { ...mod, compiled: () => module }; + return engine; }); loading.catch(() => { loading = null; }); return loading; diff --git a/frontend/src/engine/raster/materials.ts b/frontend/src/engine/raster/materials.ts new file mode 100644 index 00000000..30f24634 --- /dev/null +++ b/frontend/src/engine/raster/materials.ts @@ -0,0 +1,94 @@ +import type { Vec3 } from '../types'; + +export const PREVIEW_COMMAND = 'material.preview_maps'; +export const PREVIEW_SIZES = { smooth: 64, balanced: 128, sharp: 256 } as const; +export const PREVIEW_DEFAULT = 128; + +export type MapName = 'base_color' | 'roughness' | 'metalness' | 'normal'; +export const MAP_NAMES: readonly MapName[] = ['base_color', 'roughness', 'metalness', 'normal']; + +export interface PreviewValues { base: Vec3; roughness: number; metalness: number; opacity: number } + +export interface PreviewMaps { + key: string; + revision: number; + size: number; + constant: boolean; + values: PreviewValues; + images: Record<MapName, ImageBitmap> | null; +} + +type Dispatch = (name: string, args: Record<string, unknown>) => Promise<unknown>; + +const obj = (v: unknown): Record<string, unknown> | null => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null); +const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d); +const clamp01 = (v: number): number => Math.min(1, Math.max(0, v)); + +function values(v: unknown): PreviewValues { + const o = obj(v) ?? {}; + const c = Array.isArray(o.base_color) ? o.base_color : []; + return { + base: [clamp01(num(c[0], 0.8)), clamp01(num(c[1], 0.8)), clamp01(num(c[2], 0.8))], + roughness: clamp01(num(o.roughness, 0.5)), + metalness: clamp01(num(o.metalness, 0)), + opacity: clamp01(num(o.opacity, 1)), + }; +} + +async function decode(b64: unknown): Promise<ImageBitmap> { + if (typeof b64 !== 'string' || !b64) throw new Error('The preview map is missing'); + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + return createImageBitmap(new Blob([bytes], { type: 'image/png' }), { premultiplyAlpha: 'none', colorSpaceConversion: 'none' }); +} + +export async function parsePreview(raw: unknown, key: string, revision: number): Promise<PreviewMaps> { + const top = obj(raw); + const o = obj(top?.result) ?? top ?? {}; + const constant = o.constant === true; + const size = num(o.size, PREVIEW_DEFAULT); + const maps = obj(o.maps); + let images: PreviewMaps['images'] = null; + if (!constant && maps) { + const list = await Promise.all(MAP_NAMES.map((n) => decode(maps[n]))); + images = { base_color: list[0], roughness: list[1], metalness: list[2], normal: list[3] }; + } + return { key, revision, size, constant, values: values(o.values), images }; +} + +export function closePreview(p: PreviewMaps): void { + if (!p.images) return; + for (const n of MAP_NAMES) p.images[n].close(); + p.images = null; +} + +export class MaterialSource { + private readonly inflight = new Map<string, Promise<PreviewMaps>>(); + private readonly failed = new Map<string, string>(); + + constructor(private readonly dispatch: Dispatch, private readonly has: (name: string) => boolean) {} + + available(): boolean { return this.has(PREVIEW_COMMAND); } + + failure(key: string, revision: number, size: number): string | null { return this.failed.get(`${key}@${revision}x${size}`) ?? null; } + + maps(key: string, revision: number, size: number): Promise<PreviewMaps> { + const id = `${key}@${revision}x${size}`; + const running = this.inflight.get(id); + if (running) return running; + const job = this.dispatch(PREVIEW_COMMAND, { key, size }) + .then((raw) => parsePreview(raw, key, revision)) + .catch((err: unknown) => { + this.failed.set(id, err instanceof Error ? err.message : String(err)); + throw err; + }) + .finally(() => this.inflight.delete(id)); + this.inflight.set(id, job); + return job; + } + + forget(keep: ReadonlySet<string>): void { + for (const id of [...this.failed.keys()]) if (!keep.has(id.slice(0, id.indexOf('@')))) this.failed.delete(id); + } +} diff --git a/frontend/src/engine/raster/renderer.ts b/frontend/src/engine/raster/renderer.ts index 2e7490b8..c3ba6c97 100644 --- a/frontend/src/engine/raster/renderer.ts +++ b/frontend/src/engine/raster/renderer.ts @@ -3,6 +3,7 @@ import { maxSamples, Program, Target } from './gl'; import { add, identity, invert, length, lookAt, multiply, normalize, normalMatrix, orthographic, perspective, scale, sub, transformPoint, type Mat4, } from './math'; +import { closePreview, MAP_NAMES, type MapName, type PreviewMaps, type PreviewValues } from './materials'; import type { MeshData, RasterInstance } from './scene-data'; import { BLUR_FS, FULLSCREEN_VS, GROUND_FS, GROUND_VS, ID_FS, LINE_FS, LINE_VS, MESH_VS, OUTLINE_FS, SHADOW_FS, SHADOW_VS, SURFACE_FS, @@ -48,9 +49,26 @@ interface GpuMesh { vao: WebGLVertexArrayObject; buffers: WebGLBuffer[]; count: number; + hasUv: boolean; + hasTangent: boolean; edges: { vao: WebGLVertexArrayObject; buffer: WebGLBuffer; count: number } | null; } +interface GpuMaterial { + revision: number; + size: number; + constant: boolean; + values: PreviewValues; + textures: Record<MapName, WebGLTexture> | null; +} + +const MAP_UNIT: Record<MapName, number> = { base_color: 1, roughness: 2, metalness: 3, normal: 4 }; +const MAP_UNIFORM: Record<MapName, string> = { base_color: 'uBaseMap', roughness: 'uRoughMap', metalness: 'uMetalMap', normal: 'uNormalMap' }; + +function srgbEncode(c: Vec3): Vec3 { + return c.map((x) => (x <= 0.0031308 ? x * 12.92 : 1.055 * Math.pow(x, 1 / 2.4) - 0.055)) as Vec3; +} + interface LineSet { vao: WebGLVertexArrayObject; buffer: WebGLBuffer; count: number; color: [number, number, number, number] } const SHADOW_SIZE = 256; @@ -120,6 +138,9 @@ export class RasterRenderer { private selected = new Set<string>(); private readonly meshes = new Map<string, GpuMesh>(); private readonly meshData = new Map<string, MeshData>(); + private readonly materials = new Map<string, GpuMaterial>(); + private envTint: Vec3 = [1, 1, 1]; + private anisotropy: { ext: EXT_texture_filter_anisotropic; max: number } | null = null; private lines: LineSet[] = []; private lineSource: { segments: Float32Array; color: [number, number, number, number] }[] = []; private programs: Record<'surface' | 'id' | 'line' | 'shadow' | 'blur' | 'ground' | 'outline', Program> | null = null; @@ -135,6 +156,7 @@ export class RasterRenderer { private frame = 0; private lost = false; private readonly drawFns = new Set<() => void>(); + private readonly restoreFns = new Set<() => void>(); constructor(readonly canvas: HTMLCanvasElement) { let gl: WebGL2RenderingContext | null = null; @@ -146,7 +168,7 @@ export class RasterRenderer { this.gl = gl; if (!gl) { this.error ||= 'WebGL2 is not available in this window'; return; } canvas.addEventListener('webglcontextlost', (e) => { e.preventDefault(); this.lost = true; this.programs = null; }); - canvas.addEventListener('webglcontextrestored', () => { this.lost = false; this.init(); this.invalidate(); }); + canvas.addEventListener('webglcontextrestored', () => { this.lost = false; this.init(); this.invalidate(); for (const fn of this.restoreFns) fn(); }); this.init(); } @@ -159,6 +181,8 @@ export class RasterRenderer { onDraw(fn: () => void): () => void { this.drawFns.add(fn); return () => { this.drawFns.delete(fn); }; } + onRestore(fn: () => void): () => void { this.restoreFns.add(fn); return () => { this.restoreFns.delete(fn); }; } + private init(): void { const gl = this.gl; if (!gl) return; @@ -193,6 +217,11 @@ export class RasterRenderer { gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); this.emptyVao = gl.createVertexArray(); gl.bindVertexArray(null); + const aniso = gl.getExtension('EXT_texture_filter_anisotropic'); + this.anisotropy = aniso ? { ext: aniso, max: Math.min(4, Number(gl.getParameter(aniso.MAX_TEXTURE_MAX_ANISOTROPY_EXT)) || 1) } : null; + const sp = this.programs.surface.use(); + for (const n of MAP_NAMES) sp.int(MAP_UNIFORM[n], MAP_UNIT[n]); + this.materials.clear(); this.meshes.clear(); for (const m of this.meshData.values()) this.upload(m); this.setLines(this.lineSource); @@ -276,6 +305,51 @@ export class RasterRenderer { } } + hasMaterial(key: string, revision: number, size: number): boolean { + const m = this.materials.get(key); + return !!m && m.revision === revision && (m.constant || m.size === size); + } + + setMaterial(maps: PreviewMaps): void { + const gl = this.gl; + if (!gl || !this.ready) { closePreview(maps); return; } + let textures: GpuMaterial['textures'] = null; + if (!maps.constant && maps.images) { + const made: Partial<Record<MapName, WebGLTexture>> = {}; + for (const n of MAP_NAMES) { + const t = this.mapTexture(maps.images[n], n === 'base_color'); + if (t) made[n] = t; + } + if (MAP_NAMES.every((n) => made[n])) textures = made as Record<MapName, WebGLTexture>; + else for (const t of Object.values(made)) gl.deleteTexture(t); + } + closePreview(maps); + const old = this.materials.get(maps.key); + this.materials.set(maps.key, { revision: maps.revision, size: maps.size, constant: maps.constant || !textures, values: maps.values, textures }); + if (old) this.freeTextures(old); + if (this.mode === 'material') this.invalidate(); + } + + keepMaterials(keys: ReadonlySet<string>): void { + for (const [k, m] of [...this.materials]) { + if (keys.has(k)) continue; + this.freeTextures(m); + this.materials.delete(k); + } + } + + get materialBytes(): number { + let n = 0; + for (const m of this.materials.values()) if (m.textures) n += Math.round(m.size * m.size * 4 * 4 * 4 / 3); + return n; + } + + setEnvironmentTint(tint: Vec3): void { + if (tint.every((v, i) => v === this.envTint[i])) return; + this.envTint = [...tint]; + if (this.mode === 'material') this.invalidate(); + } + setLines(sets: { segments: Float32Array; color: [number, number, number, number] }[]): void { this.lineSource = sets; const gl = this.gl; @@ -406,6 +480,7 @@ export class RasterRenderer { if (this.frame) cancelAnimationFrame(this.frame); this.frame = 0; for (const k of [...this.meshes.keys()]) this.freeMesh(k); + this.keepMaterials(new Set()); this.setLines([]); this.scene?.release(); this.ids?.release(); @@ -437,8 +512,46 @@ export class RasterRenderer { gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idx); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data.indices, gl.STATIC_DRAW); + const buffers = [pos, nor, idx]; + const extra = (location: number, values: Float32Array | null, width: number): boolean => { + const b = values ? gl.createBuffer() : null; + if (!values || !b) { gl.disableVertexAttribArray(location); return false; } + gl.bindBuffer(gl.ARRAY_BUFFER, b); + gl.bufferData(gl.ARRAY_BUFFER, values, gl.STATIC_DRAW); + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, width, gl.FLOAT, false, 0, 0); + buffers.push(b); + return true; + }; + const hasUv = extra(2, data.uv0, 2); + const hasTangent = hasUv && extra(3, data.tangents, 4); gl.bindVertexArray(null); - this.meshes.set(data.key, { data, vao, buffers: [pos, nor, idx], count: data.indices.length, edges: null }); + this.meshes.set(data.key, { data, vao, buffers, count: data.indices.length, hasUv, hasTangent, edges: null }); + } + + private mapTexture(image: ImageBitmap, srgb: boolean): WebGLTexture | null { + const gl = this.gl as WebGL2RenderingContext; + const t = gl.createTexture(); + if (!t) return null; + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, t); + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); + gl.texImage2D(gl.TEXTURE_2D, 0, srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, image); + gl.generateMipmap(gl.TEXTURE_2D); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + if (this.anisotropy) gl.texParameterf(gl.TEXTURE_2D, this.anisotropy.ext.TEXTURE_MAX_ANISOTROPY_EXT, this.anisotropy.max); + gl.bindTexture(gl.TEXTURE_2D, null); + return t; + } + + private freeTextures(m: GpuMaterial): void { + const gl = this.gl; + if (!gl || !m.textures) return; + for (const n of MAP_NAMES) gl.deleteTexture(m.textures[n]); + m.textures = null; } private edgesOf(mesh: GpuMesh): GpuMesh['edges'] { @@ -487,11 +600,28 @@ export class RasterRenderer { gl.disable(gl.BLEND); gl.disable(gl.CULL_FACE); p.mat4('uViewProj', m.viewProj).vec3('uEye', m.eye).vec3('uCamRight', m.right).vec3('uCamUp', m.up).vec3('uCamBack', m.back); - p.int('uMode', this.mode === 'material' ? 1 : 0); + const material = this.mode === 'material'; + p.int('uMode', material ? 1 : 0).vec3('uEnvTint', this.envTint); + let bound: GpuMaterial | null = null; for (const { inst, mesh, world } of this.visible()) { - const look = this.mode === 'material' ? inst.shade : null; + let look = material ? inst.shade : null; + const mat = material && inst.material ? this.materials.get(inst.material) ?? null : null; + if (mat && (mat.constant || !mesh.hasUv)) { + const v = mat.values; + look = { base: inst.tinted ? inst.color : srgbEncode(v.base), metalness: v.metalness, roughness: Math.max(0.02, v.roughness) }; + } + const maps = mat && !mat.constant && mat.textures && mesh.hasUv ? mat : null; p.mat4('uModel', world).mat3('uNormalMat', normalMatrix(world)); p.vec3('uColor', look ? look.base : inst.color).float('uMetal', look ? look.metalness : 0).float('uRough', look ? look.roughness : 0.5); + p.int('uMaps', maps ? 1 : 0).int('uHasTangent', maps && mesh.hasTangent ? 1 : 0).int('uTint', inst.tinted ? 1 : 0); + if (maps && maps !== bound && maps.textures) { + for (const n of MAP_NAMES) { + gl.activeTexture(gl.TEXTURE0 + MAP_UNIT[n]); + gl.bindTexture(gl.TEXTURE_2D, maps.textures[n]); + } + gl.activeTexture(gl.TEXTURE0); + bound = maps; + } gl.bindVertexArray(mesh.vao); gl.drawElements(gl.TRIANGLES, mesh.count, gl.UNSIGNED_INT, 0); } diff --git a/frontend/src/engine/raster/scene-data.ts b/frontend/src/engine/raster/scene-data.ts index 50e24051..bdd91860 100644 --- a/frontend/src/engine/raster/scene-data.ts +++ b/frontend/src/engine/raster/scene-data.ts @@ -17,12 +17,18 @@ export interface RasterInstance { color: Vec3; visible: boolean; selected: boolean; + tinted: boolean; shade: MaterialLook | null; } export interface MaterialLook { base: Vec3; metalness: number; roughness: number } -export interface SceneMeshes { meshes: MeshInfo[]; instances: RasterInstance[]; revision: number } +export interface MaterialInfo { key: string; revision: number } + +export interface SceneMeshes { meshes: MeshInfo[]; instances: RasterInstance[]; materials: MaterialInfo[] | null; revision: number } + +export const FLAG_UV0 = 1; +export const FLAG_TANGENTS = 2; export interface MeshData { key: string; @@ -30,6 +36,8 @@ export interface MeshData { positions: Float32Array; normals: Float32Array; indices: Uint32Array; + uv0: Float32Array | null; + tangents: Float32Array | null; min: Vec3; max: Vec3; } @@ -86,10 +94,20 @@ export function parseSceneMeshes(raw: unknown): SceneMeshes | null { color, visible: e.visible !== false, selected: e.selected === true, + tinted: e.tinted === true, shade: look(e, color), }); } - return { meshes, instances, revision: num(o.revision) }; + let materials: MaterialInfo[] | null = null; + if (Array.isArray(o.materials)) { + materials = []; + for (const m of o.materials) { + const e = obj(m); + const key = str(e?.key); + if (e && key) materials.push({ key, revision: num(e.revision) }); + } + } + return { meshes, instances, materials, revision: num(o.revision) }; } function computeNormals(positions: Float32Array, indices: Uint32Array): Float32Array { @@ -108,7 +126,9 @@ function computeNormals(positions: Float32Array, indices: Uint32Array): Float32A return n; } -function finish(key: string, revision: number, positions: Float32Array, normals: Float32Array | null, indices: Uint32Array): MeshData { +interface Extra { uv0: Float32Array | null; tangents: Float32Array | null } + +function finish(key: string, revision: number, positions: Float32Array, normals: Float32Array | null, indices: Uint32Array, extra: Extra): MeshData { const min: Vec3 = [Infinity, Infinity, Infinity], max: Vec3 = [-Infinity, -Infinity, -Infinity]; for (let i = 0; i < positions.length; i += 3) { for (let a = 0; a < 3; a++) { @@ -119,23 +139,32 @@ function finish(key: string, revision: number, positions: Float32Array, normals: } if (!Number.isFinite(min[0])) { min.fill(0); max.fill(0); } const usable = normals && normals.length === positions.length && normals.some((v) => v !== 0); - return { key, revision, positions, normals: usable ? normals : computeNormals(positions, indices), indices, min, max }; + const vc = positions.length / 3; + const uv0 = extra.uv0 && extra.uv0.length === vc * 2 && vc > 0 ? extra.uv0 : null; + const tangents = uv0 && extra.tangents && extra.tangents.length === vc * 4 ? extra.tangents : null; + return { key, revision, positions, normals: usable ? normals : computeNormals(positions, indices), indices, uv0, tangents, min, max }; } export function parseMeshBinary(key: string, revision: number, buf: ArrayBuffer): MeshData { if (buf.byteLength < 16) throw new Error('The mesh reply is too short'); const head = new DataView(buf, 0, 16); if (head.getUint32(0, true) !== MAGIC) throw new Error('The mesh reply is not an FSHM block'); + const flags = head.getUint32(4, true) >>> 16; const vc = head.getUint32(8, true); let ic = head.getUint32(12, true); const plain = 16 + vc * 24 + ic * 4; - if (buf.byteLength !== plain && buf.byteLength === 16 + vc * 24 + ic * 12) ic *= 3; - if (buf.byteLength < 16 + vc * 24 + ic * 4) throw new Error('The mesh reply is shorter than its header says'); - const copy = buf.slice(16, 16 + vc * 24 + ic * 4); + if (flags === 0 && buf.byteLength !== plain && buf.byteLength === 16 + vc * 24 + ic * 12) ic *= 3; + const base = 16 + vc * 24 + ic * 4; + const uvBytes = flags & FLAG_UV0 ? vc * 8 : 0; + const tanBytes = flags & FLAG_TANGENTS ? vc * 16 : 0; + if (buf.byteLength < base + uvBytes + tanBytes) throw new Error('The mesh reply is shorter than its header says'); + const copy = buf.slice(16, base + uvBytes + tanBytes); const positions = new Float32Array(copy, 0, vc * 3); const normals = new Float32Array(copy, vc * 12, vc * 3); const indices = new Uint32Array(copy, vc * 24, ic); - return finish(key, revision, positions, normals, indices); + const uv0 = uvBytes ? new Float32Array(copy, base - 16, vc * 2) : null; + const tangents = tanBytes ? new Float32Array(copy, base - 16 + uvBytes, vc * 4) : null; + return finish(key, revision, positions, normals, indices, { uv0, tangents }); } function fromBase64<T extends Float32Array | Uint32Array>(b64: unknown, Kind: { new (b: ArrayBuffer): T }): T { @@ -194,6 +223,8 @@ export class MeshSource { if (!this.has(MESH_DATA_COMMAND)) throw new Error('The engine cannot send mesh data'); const top = obj(await this.dispatch(MESH_DATA_COMMAND, { key: info.key })); const o = obj(top?.result) ?? top ?? {}; - return finish(info.key, info.revision, fromBase64(o.positions_b64, Float32Array), fromBase64(o.normals_b64, Float32Array), fromBase64(o.indices_b64, Uint32Array)); + const uv0 = typeof o.uv0_b64 === 'string' && o.uv0_b64 ? fromBase64(o.uv0_b64, Float32Array) : null; + const tangents = typeof o.tangents_b64 === 'string' && o.tangents_b64 ? fromBase64(o.tangents_b64, Float32Array) : null; + return finish(info.key, info.revision, fromBase64(o.positions_b64, Float32Array), fromBase64(o.normals_b64, Float32Array), fromBase64(o.indices_b64, Uint32Array), { uv0, tangents }); } } diff --git a/frontend/src/engine/raster/shaders.ts b/frontend/src/engine/raster/shaders.ts index 4cb1de8f..5c7e7882 100644 --- a/frontend/src/engine/raster/shaders.ts +++ b/frontend/src/engine/raster/shaders.ts @@ -14,21 +14,30 @@ vec3 toLinear(vec3 c) { export const MESH_VS = `${HEAD} layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNormal; +layout(location = 2) in vec2 aUv; +layout(location = 3) in vec4 aTangent; uniform mat4 uViewProj; uniform mat4 uModel; uniform mat3 uNormalMat; out vec3 vWorld; out vec3 vNormal; +out vec2 vUv; +out vec4 vTangent; void main() { vec4 w = uModel * vec4(aPos, 1.0); vWorld = w.xyz; vNormal = uNormalMat * aNormal; + mat3 m = mat3(uModel); + vUv = aUv; + vTangent = vec4(m * aTangent.xyz, (aTangent.w < 0.0 ? -1.0 : 1.0) * (determinant(m) < 0.0 ? -1.0 : 1.0)); gl_Position = uViewProj * w; }`; export const SURFACE_FS = `${HEAD} in vec3 vWorld; in vec3 vNormal; +in vec2 vUv; +in vec4 vTangent; uniform vec3 uEye; uniform vec3 uColor; uniform float uMetal; @@ -37,6 +46,14 @@ uniform int uMode; uniform vec3 uCamRight; uniform vec3 uCamUp; uniform vec3 uCamBack; +uniform int uMaps; +uniform int uHasTangent; +uniform int uTint; +uniform vec3 uEnvTint; +uniform sampler2D uBaseMap; +uniform sampler2D uRoughMap; +uniform sampler2D uMetalMap; +uniform sampler2D uNormalMap; out vec4 outColor; ${TONE} const vec3 KEY_DIR = vec3(-0.55, 0.75, 0.45); @@ -51,20 +68,8 @@ vec3 gradient(vec3 d, float soft) { vec3 c = mix(vec3(0.035, 0.035, 0.04), vec3(0.2, 0.205, 0.215), smoothstep(-0.3 - soft * 0.4, 0.05 + soft * 0.3, d.y)); return mix(c, vec3(0.34, 0.345, 0.36), smoothstep(0.15, 0.9 + soft * 0.3, d.y)); } -vec3 lobe(vec3 d, vec3 l, vec3 e, float w0, float rough) { - float w = w0 + rough * rough * 1.2; - return e / (6.2832 * w0) * exp((dot(d, normalize(l)) - 1.0) / w) * (w0 / w); -} -vec3 studioSpecular(vec3 r, float rough) { - vec3 c = gradient(r, rough); - c += lobe(r, KEY_DIR, KEY_E, 0.02, rough); - c += lobe(r, FILL_DIR, FILL_E, 0.035, rough); - c += lobe(r, BACK_DIR, BACK_E, 0.025, rough); - c += lobe(r, TOP_DIR, TOP_E, 0.1, rough); - return c; -} vec3 studioIrradiance(vec3 n) { - vec3 c = gradient(n, 1.0) * 0.9; + vec3 c = gradient(n, 1.0) * 0.9 * uEnvTint; c += KEY_E * max(dot(n, normalize(KEY_DIR)), 0.0) * 0.32; c += FILL_E * max(dot(n, normalize(FILL_DIR)), 0.0) * 0.32; c += BACK_E * max(dot(n, normalize(BACK_DIR)), 0.0) * 0.32; @@ -78,11 +83,66 @@ vec2 envBrdf(float nv, float rough) { float a004 = min(r.x * r.x, exp2(-9.28 * nv)) * r.x + r.y; return vec2(-1.04, 1.04) * a004 + r.zw; } +float ggx(float nh, float a) { + float a2 = a * a; + float d = nh * nh * (a2 - 1.0) + 1.0; + return a2 / (3.14159265 * d * d); +} +float smithVis(float nl, float nv, float a) { + float a2 = a * a; + float gv = nl * sqrt(nv * nv * (1.0 - a2) + a2); + float gl = nv * sqrt(nl * nl * (1.0 - a2) + a2); + return 0.5 / max(gv + gl, 1e-5); +} +vec3 lightGgx(vec3 n, vec3 v, vec3 dir, vec3 e, float w0, float rough, vec3 f0) { + vec3 l = normalize(dir); + float nl = dot(n, l); + if (nl <= 0.0) return vec3(0.0); + vec3 h = normalize(v + l); + float nh = max(dot(n, h), 0.0), nv = clamp(dot(n, v), 1e-3, 1.0), vh = max(dot(v, h), 0.0); + float a = sqrt(rough * rough * rough * rough + 0.5 * w0); + vec3 f = f0 + (1.0 - f0) * pow(1.0 - vh, 5.0); + return e * ggx(nh, a) * smithVis(nl, nv, a) * f * nl; +} +vec3 studioGgx(vec3 n, vec3 v, float rough, vec3 f0) { + vec3 c = lightGgx(n, v, KEY_DIR, KEY_E, 0.02, rough, f0); + c += lightGgx(n, v, FILL_DIR, FILL_E, 0.035, rough, f0); + c += lightGgx(n, v, BACK_DIR, BACK_E, 0.025, rough, f0); + c += lightGgx(n, v, TOP_DIR, TOP_E, 0.1, rough, f0); + return c; +} +mat3 tangentFrame(vec3 n) { + if (uHasTangent == 1) { + vec3 t = vTangent.xyz - n * dot(n, vTangent.xyz); + float l = length(t); + if (l > 1e-8) { t /= l; return mat3(t, vTangent.w * cross(n, t), n); } + } + vec3 dp1 = dFdx(vWorld), dp2 = dFdy(vWorld); + vec2 duv1 = dFdx(vUv), duv2 = dFdy(vUv); + vec3 dp2perp = cross(dp2, n), dp1perp = cross(n, dp1); + vec3 t = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 b = dp2perp * duv1.y + dp1perp * duv2.y; + float m = max(dot(t, t), dot(b, b)); + if (!(m > 1e-30)) return mat3(vec3(0.0), vec3(0.0), n); + float s = inversesqrt(m); + return mat3(t * s, b * s, n); +} void main() { vec3 n = normalize(vNormal); vec3 v = normalize(uEye - vWorld); if (!gl_FrontFacing) n = -n; vec3 base = toLinear(uColor); + float metal = uMetal; + float roughIn = uRough; + if (uMode != 0 && uMaps == 1) { + vec2 st = vec2(vUv.x, 1.0 - vUv.y); + if (uTint == 0) base = texture(uBaseMap, st).rgb; + roughIn = texture(uRoughMap, st).r; + metal = texture(uMetalMap, st).r; + vec3 tn = texture(uNormalMap, st).xyz * 2.0 - 1.0; + vec3 bent = tangentFrame(n) * tn; + if (dot(bent, bent) > 1e-12) n = normalize(bent); + } vec3 col; if (uMode == 0) { vec3 key = normalize(-0.45 * uCamRight + 0.75 * uCamUp + 0.55 * uCamBack); @@ -93,13 +153,13 @@ void main() { float rim = pow(1.0 - max(dot(n, v), 0.0), 3.0); col = base * (0.95 * k + 0.28 * f + mix(0.12, 0.3, hemi)) + vec3(0.05) * rim; } else { - float rough = clamp(uRough, 0.03, 1.0); + float rough = clamp(roughIn, 0.03, 1.0); float nv = clamp(dot(n, v), 1e-3, 1.0); - vec3 f0 = mix(vec3(0.04), base, uMetal); + vec3 f0 = mix(vec3(0.04), base, metal); vec2 ab = envBrdf(nv, rough); vec3 fresnel = f0 * ab.x + ab.y; - vec3 spec = studioSpecular(reflect(-v, n), rough) * fresnel; - vec3 diff = studioIrradiance(n) * base * (1.0 - uMetal) * (1.0 - fresnel); + vec3 spec = gradient(reflect(-v, n), rough) * uEnvTint * fresnel + studioGgx(n, v, rough, f0); + vec3 diff = studioIrradiance(n) * base * (1.0 - metal) * (1.0 - fresnel); col = diff + spec; } outColor = vec4(toDisplay(col), 1.0); diff --git a/frontend/src/i18n/modules/cad/cs.json b/frontend/src/i18n/modules/cad/cs.json new file mode 100644 index 00000000..a8bd5e50 --- /dev/null +++ b/frontend/src/i18n/modules/cad/cs.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% velikosti modelu", + "About {n} triangles afterwards.": "Poté bude přibližně {n} trojúhelníků.", + "All CAD parts": "Všechny části CAD", + "Angle": "Úhel", + "Angle in degrees": "Úhel ve stupních", + "Apply": "Použít", + "Beside the FormShot engine": "Vedle enginu FormShot", + "CAD Import": "Import CAD", + "CAD Import Settings...": "Nastavení importu CAD...", + "CAD Options in the Import Sheet": "Možnosti CAD v panelu importu", + "CAD worker": "Pracovní proces CAD", + "CAD worker: {stage}, {pct}%": "Pracovní proces CAD: {stage}, {pct} %", + "Check the worker": "Zkontrolovat pracovní proces", + "Checking every file": "Kontrola každého souboru", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Vyberte soubory STEP nebo IGES k importu; otevírají se pomocí pracovního procesu CAD.", + "Chord": "Tětiva", + "Chord as a percentage of the model size": "Tětiva v procentech velikosti modelu", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Tětiva musí být větší než 0 a nejvýše {max} % velikosti modelu; úhel od {min} do {amax} stupňů.", + "Chord {chord}% of the model size, angle {angle} degrees": "Tětiva {chord} % velikosti modelu, úhel {angle} stupňů", + "Could not re-tessellate: {reason}": "Opakovaná teselace se nezdařila: {reason}", + "Custom": "Vlastní", + "Custom ({chord}%, {angle}°)": "Vlastní ({chord} %, {angle}°)", + "Default CAD quality": "Výchozí kvalita CAD", + "Download": "Stáhnout", + "Download and check the program that opens STEP and IGES files.": "Stáhněte a zkontrolujte program, který otevírá soubory STEP a IGES.", + "Download the CAD Worker": "Stáhnout pracovní proces CAD", + "Download the CAD worker": "Stáhnout pracovní proces CAD", + "Downloaded into the cache folder": "Staženo do složky mezipaměti", + "Downloading": "Stahování", + "Found in": "Nalezeno v", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Jak jemně se plochy STEP a IGES při importu změní na trojúhelníky. Tětiva je největší odchylka mezi trojúhelníkem a skutečnou plochou jako podíl velikosti celého modelu; úhel je největší zalomení mezi sousedními trojúhelníky. Jemnější nastavení trvají déle a vytvářejí větší soubory. Panel importu začíná touto volbou; tam ji můžete změnit pro jeden import.", + "Installed": "Nainstalováno", + "Mixed": "Smíšené", + "Named by FORMSHOT_CAD_WORKER": "Určeno proměnnou FORMSHOT_CAD_WORKER", + "New quality": "Nová kvalita", + "None of the selected parts came from a STEP or IGES file.": "Žádná z vybraných částí nepochází ze souboru STEP ani IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Žádná z vybraných částí nepochází ze souboru STEP ani IGES. Zrušte výběr, aby se přestavěly všechny části CAD.", + "Not available.": "Není k dispozici.", + "Not available: {reason}": "Není k dispozici: {reason}", + "Not installed": "Nenainstalováno", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Zatím nenainstalováno. FormShot ho hledá ve složce {folder}; stáhněte jej zde, abyste mohli otevírat soubory STEP a IGES.", + "Not named": "Neurčeno", + "Not recorded": "Nezaznamenáno", + "Nothing in this document came from a STEP or IGES file.": "Nic v tomto dokumentu nepochází ze souboru STEP ani IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "Není nic vybráno, takže se přestavějí všechny části CAD.", + "Published": "Publikováno", + "Quality now": "Současná kvalita", + "Re-tessellate CAD Parts": "Znovu teselovat části CAD", + "Re-tessellate CAD Parts...": "Znovu teselovat části CAD...", + "Re-tessellated 1 CAD part at {quality}.": "Znovu teselována 1 část CAD v kvalitě {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "Znovu teselována 1 část CAD v kvalitě {quality}: z {before} na {after} trojúhelníků.", + "Re-tessellated {parts} CAD parts at {quality}.": "Znovu teselováno částí CAD: {parts}, kvalita {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "Znovu teselováno částí CAD: {parts}, kvalita {quality}: z {before} na {after} trojúhelníků.", + "Re-tessellating": "Znovu se teseluje", + "Read the status again": "Znovu načíst stav", + "Reading the published record": "Čtení publikovaného záznamu", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Přestaví sítě částí importovaných ze STEP nebo IGES v jiné kvalitě jako jeden krok zpět.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "Soubory STEP a IGES otevírá pracovní proces jádra FormCAD, samostatný program, který FormShot jednou stáhne, zkontroluje soubor po souboru a uchová ve vaší složce mezipaměti. Jiné formáty modelů ho nepotřebují.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "Soubory STEP a IGES potřebují pracovní proces CAD a pro tento počítač žádný není publikován.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "Soubory STEP a IGES potřebují pracovní proces CAD, který zatím není nainstalován.", + "Selected CAD parts": "Vybrané části CAD", + "Source": "Zdroj", + "The CAD worker is installed.": "Pracovní proces CAD je nainstalován.", + "The CAD worker is installed. You can import this file now.": "Pracovní proces CAD je nainstalován. Tento soubor můžete nyní importovat.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Pracovní proces CAD, který otevírá soubory STEP a IGES, a výchozí kvalita CAD.", + "The FormShot service is not reachable.": "Služba FormShot není dostupná.", + "The download failed: {reason}": "Stahování se nezdařilo: {reason}", + "The download was cancelled. Nothing was installed.": "Stahování bylo zrušeno. Nic nebylo nainstalováno.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Engine neposkytuje odhad; jemnější kvality trvají déle a vytvářejí více trojúhelníků.", + "The parts could not be read: {reason}": "Části se nepodařilo přečíst: {reason}", + "The service cannot stop a download once it has started.": "Služba nemůže zastavit stahování, jakmile začalo.", + "The service refused the request from this window.": "Služba odmítla požadavek z tohoto okna.", + "The status could not be read: {reason}": "Stav se nepodařilo přečíst: {reason}", + "The worker did not answer: {reason}": "Pracovní proces neodpověděl: {reason}", + "This computer": "Tento počítač", + "This engine cannot re-tessellate CAD parts.": "Tento engine neumí znovu teselovat části CAD.", + "Triangles now": "Nyní trojúhelníků", + "Try Again": "Zkusit znovu", + "Unknown": "Neznámé", + "Unpacking": "Rozbalování", + "Version": "Verze", + "degrees": "stupňů", + "no reason was given": "nebyl uveden důvod", + "{done} of {total}": "{done} z {total}", + "{n} files": "{n} souborů", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokol {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} rozbaleno, zkontrolováno soubor po souboru", + "{tag}: none for this computer": "{tag}: pro tento počítač žádný", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} souborů, {size} rozbaleno" +} diff --git a/frontend/src/i18n/modules/cad/da.json b/frontend/src/i18n/modules/cad/da.json new file mode 100644 index 00000000..b88723cf --- /dev/null +++ b/frontend/src/i18n/modules/cad/da.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% af modellens størrelse", + "About {n} triangles afterwards.": "Cirka {n} trekanter bagefter.", + "All CAD parts": "Alle CAD-dele", + "Angle": "Vinkel", + "Angle in degrees": "Vinkel i grader", + "Apply": "Anvend", + "Beside the FormShot engine": "Ved siden af FormShot-motoren", + "CAD Import": "CAD-import", + "CAD Import Settings...": "CAD-importindstillinger...", + "CAD Options in the Import Sheet": "CAD-indstillinger i importvinduet", + "CAD worker": "CAD-worker", + "CAD worker: {stage}, {pct}%": "CAD-worker: {stage}, {pct}%", + "Check the worker": "Kontrollér workeren", + "Checking every file": "Kontrollerer hver fil", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Vælg STEP- eller IGES-filer, der skal importeres; de åbnes via CAD-workeren.", + "Chord": "Korde", + "Chord as a percentage of the model size": "Korde som procent af modellens størrelse", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Korden skal være over 0 og højst {max}% af modellens størrelse; vinklen fra {min} til {amax} grader.", + "Chord {chord}% of the model size, angle {angle} degrees": "Korde {chord}% af modellens størrelse, vinkel {angle} grader", + "Could not re-tessellate: {reason}": "Gentessellering mislykkedes: {reason}", + "Custom": "Brugerdefineret", + "Custom ({chord}%, {angle}°)": "Brugerdefineret ({chord}%, {angle}°)", + "Default CAD quality": "Standard-CAD-kvalitet", + "Download": "Download", + "Download and check the program that opens STEP and IGES files.": "Download og kontrollér programmet, der åbner STEP- og IGES-filer.", + "Download the CAD Worker": "Download CAD-workeren", + "Download the CAD worker": "Download CAD-workeren", + "Downloaded into the cache folder": "Downloadet til cachemappen", + "Downloading": "Downloader", + "Found in": "Fundet i", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Hvor fint STEP- og IGES-overflader bliver til trekanter ved import. Korden er den største afstand mellem en trekant og den rigtige overflade, som andel af hele modellens størrelse; vinklen er det største knæk mellem naboliggende trekanter. Finere indstillinger tager længere tid og giver større filer. Importvinduet starter med dette valg; her kan du ændre det for én enkelt import.", + "Installed": "Installeret", + "Mixed": "Blandet", + "Named by FORMSHOT_CAD_WORKER": "Angivet af FORMSHOT_CAD_WORKER", + "New quality": "Ny kvalitet", + "None of the selected parts came from a STEP or IGES file.": "Ingen af de valgte dele kom fra en STEP- eller IGES-fil.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Ingen af de valgte dele kom fra en STEP- eller IGES-fil. Ryd markeringen for at genopbygge alle CAD-dele.", + "Not available.": "Ikke tilgængeligt.", + "Not available: {reason}": "Ikke tilgængeligt: {reason}", + "Not installed": "Ikke installeret", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Endnu ikke installeret. FormShot leder efter den i {folder}; download den her for at åbne STEP- og IGES-filer.", + "Not named": "Ikke angivet", + "Not recorded": "Ikke registreret", + "Nothing in this document came from a STEP or IGES file.": "Intet i dette dokument kom fra en STEP- eller IGES-fil.", + "Nothing is selected, so every CAD part is rebuilt.": "Intet er valgt, så alle CAD-dele genopbygges.", + "Published": "Udgivet", + "Quality now": "Kvalitet nu", + "Re-tessellate CAD Parts": "Gentesseller CAD-dele", + "Re-tessellate CAD Parts...": "Gentesseller CAD-dele...", + "Re-tessellated 1 CAD part at {quality}.": "1 CAD-del gentesselleret med {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 CAD-del gentesselleret med {quality}: {before} til {after} trekanter.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} CAD-dele gentesselleret med {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} CAD-dele gentesselleret med {quality}: {before} til {after} trekanter.", + "Re-tessellating": "Gentessellerer", + "Read the status again": "Læs status igen", + "Reading the published record": "Læser den udgivne post", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Genopbygger meshes for dele importeret fra STEP eller IGES med en anden kvalitet, som ét fortryd-trin.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP- og IGES-filer åbnes af FormCADs kerne-worker, et separat program, som FormShot downloader én gang, kontrollerer fil for fil og beholder i din cachemappe. Andre modelformater har ikke brug for det.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP- og IGES-filer kræver CAD-workeren, og der er ingen udgivet til denne computer.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP- og IGES-filer kræver CAD-workeren, som endnu ikke er installeret.", + "Selected CAD parts": "Valgte CAD-dele", + "Source": "Kilde", + "The CAD worker is installed.": "CAD-workeren er installeret.", + "The CAD worker is installed. You can import this file now.": "CAD-workeren er installeret. Du kan importere denne fil nu.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "CAD-workeren, der åbner STEP- og IGES-filer, og standard-CAD-kvaliteten.", + "The FormShot service is not reachable.": "FormShot-tjenesten er ikke tilgængelig.", + "The download failed: {reason}": "Downloadet mislykkedes: {reason}", + "The download was cancelled. Nothing was installed.": "Downloadet blev annulleret. Intet blev installeret.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Motoren giver intet estimat; finere kvaliteter tager længere tid og giver flere trekanter.", + "The parts could not be read: {reason}": "Dele kunne ikke læses: {reason}", + "The service cannot stop a download once it has started.": "Tjenesten kan ikke stoppe et download, når det først er startet.", + "The service refused the request from this window.": "Tjenesten afviste anmodningen fra dette vindue.", + "The status could not be read: {reason}": "Status kunne ikke læses: {reason}", + "The worker did not answer: {reason}": "Workeren svarede ikke: {reason}", + "This computer": "Denne computer", + "This engine cannot re-tessellate CAD parts.": "Denne motor kan ikke gentessellere CAD-dele.", + "Triangles now": "Trekanter nu", + "Try Again": "Prøv igen", + "Unknown": "Ukendt", + "Unpacking": "Pakker ud", + "Version": "Version", + "degrees": "grader", + "no reason was given": "ingen årsag blev angivet", + "{done} of {total}": "{done} af {total}", + "{n} files": "{n} filer", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokol {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} udpakket, kontrolleret fil for fil", + "{tag}: none for this computer": "{tag}: ingen til denne computer", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} filer, {size} udpakket" +} diff --git a/frontend/src/i18n/modules/cad/de.json b/frontend/src/i18n/modules/cad/de.json new file mode 100644 index 00000000..fc82b39f --- /dev/null +++ b/frontend/src/i18n/modules/cad/de.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% der Modellgröße", + "About {n} triangles afterwards.": "Danach etwa {n} Dreiecke.", + "All CAD parts": "Alle CAD-Teile", + "Angle": "Winkel", + "Angle in degrees": "Winkel in Grad", + "Apply": "Anwenden", + "Beside the FormShot engine": "Neben der FormShot-Engine", + "CAD Import": "CAD-Import", + "CAD Import Settings...": "CAD-Importeinstellungen ...", + "CAD Options in the Import Sheet": "CAD-Optionen im Importdialog", + "CAD worker": "CAD-Worker", + "CAD worker: {stage}, {pct}%": "CAD-Worker: {stage}, {pct} %", + "Check the worker": "Worker prüfen", + "Checking every file": "Jede Datei wird geprüft", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Wähle STEP- oder IGES-Dateien zum Importieren aus; sie werden über den CAD-Worker geöffnet.", + "Chord": "Sehne", + "Chord as a percentage of the model size": "Sehne in Prozent der Modellgröße", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Die Sehne muss größer als 0 und höchstens {max} % der Modellgröße sein; der Winkel von {min} bis {amax} Grad.", + "Chord {chord}% of the model size, angle {angle} degrees": "Sehne {chord} % der Modellgröße, Winkel {angle} Grad", + "Could not re-tessellate: {reason}": "Neue Tesselierung nicht möglich: {reason}", + "Custom": "Benutzerdefiniert", + "Custom ({chord}%, {angle}°)": "Benutzerdefiniert ({chord} %, {angle}°)", + "Default CAD quality": "Standard-CAD-Qualität", + "Download": "Herunterladen", + "Download and check the program that opens STEP and IGES files.": "Das Programm herunterladen und prüfen, das STEP- und IGES-Dateien öffnet.", + "Download the CAD Worker": "CAD-Worker herunterladen", + "Download the CAD worker": "CAD-Worker herunterladen", + "Downloaded into the cache folder": "In den Cache-Ordner heruntergeladen", + "Downloading": "Download läuft", + "Found in": "Gefunden in", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Wie fein STEP- und IGES-Flächen beim Import zu Dreiecken werden. Die Sehne ist der größte Abstand zwischen einem Dreieck und der echten Fläche, als Anteil an der Größe des ganzen Modells; der Winkel ist die größte Abknickung zwischen benachbarten Dreiecken. Feinere Einstellungen dauern länger und erzeugen größere Dateien. Der Importdialog beginnt mit dieser Auswahl; dort kannst du sie für einen einzelnen Import ändern.", + "Installed": "Installiert", + "Mixed": "Gemischt", + "Named by FORMSHOT_CAD_WORKER": "Benannt durch FORMSHOT_CAD_WORKER", + "New quality": "Neue Qualität", + "None of the selected parts came from a STEP or IGES file.": "Keines der ausgewählten Teile stammt aus einer STEP- oder IGES-Datei.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Keines der ausgewählten Teile stammt aus einer STEP- oder IGES-Datei. Hebe die Auswahl auf, um alle CAD-Teile neu aufzubauen.", + "Not available.": "Nicht verfügbar.", + "Not available: {reason}": "Nicht verfügbar: {reason}", + "Not installed": "Nicht installiert", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Noch nicht installiert. FormShot sucht es in {folder}; lade es hier herunter, um STEP- und IGES-Dateien zu öffnen.", + "Not named": "Nicht benannt", + "Not recorded": "Nicht aufgezeichnet", + "Nothing in this document came from a STEP or IGES file.": "Nichts in diesem Dokument stammt aus einer STEP- oder IGES-Datei.", + "Nothing is selected, so every CAD part is rebuilt.": "Nichts ist ausgewählt, daher werden alle CAD-Teile neu aufgebaut.", + "Published": "Veröffentlicht", + "Quality now": "Aktuelle Qualität", + "Re-tessellate CAD Parts": "CAD-Teile neu tesselieren", + "Re-tessellate CAD Parts...": "CAD-Teile neu tesselieren ...", + "Re-tessellated 1 CAD part at {quality}.": "1 CAD-Teil mit {quality} neu tesseliert.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 CAD-Teil mit {quality} neu tesseliert: {before} bis {after} Dreiecke.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} CAD-Teile mit {quality} neu tesseliert.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} CAD-Teile mit {quality} neu tesseliert: {before} bis {after} Dreiecke.", + "Re-tessellating": "Neue Tesselierung läuft", + "Read the status again": "Status erneut lesen", + "Reading the published record": "Veröffentlichter Eintrag wird gelesen", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Baut die Meshes von Teilen aus STEP- oder IGES-Importen mit einer anderen Qualität neu auf, als ein einziger Rückgängig-Schritt.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP- und IGES-Dateien werden vom Kernel-Worker von FormCAD geöffnet, einem separaten Programm, das FormShot einmal herunterlädt, Datei für Datei prüft und in deinem Cache-Ordner aufbewahrt. Andere Modellformate brauchen es nicht.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP- und IGES-Dateien brauchen den CAD-Worker, und für diesen Computer ist keiner veröffentlicht.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP- und IGES-Dateien brauchen den CAD-Worker, der noch nicht installiert ist.", + "Selected CAD parts": "Ausgewählte CAD-Teile", + "Source": "Quelle", + "The CAD worker is installed.": "Der CAD-Worker ist installiert.", + "The CAD worker is installed. You can import this file now.": "Der CAD-Worker ist installiert. Du kannst diese Datei jetzt importieren.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Der CAD-Worker, der STEP- und IGES-Dateien öffnet, und die Standard-CAD-Qualität.", + "The FormShot service is not reachable.": "Der FormShot-Dienst ist nicht erreichbar.", + "The download failed: {reason}": "Der Download ist fehlgeschlagen: {reason}", + "The download was cancelled. Nothing was installed.": "Der Download wurde abgebrochen. Es wurde nichts installiert.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Die Engine liefert keine Schätzung; feinere Qualitäten dauern länger und erzeugen mehr Dreiecke.", + "The parts could not be read: {reason}": "Die Teile konnten nicht gelesen werden: {reason}", + "The service cannot stop a download once it has started.": "Der Dienst kann einen gestarteten Download nicht mehr anhalten.", + "The service refused the request from this window.": "Der Dienst hat die Anfrage aus diesem Fenster abgelehnt.", + "The status could not be read: {reason}": "Der Status konnte nicht gelesen werden: {reason}", + "The worker did not answer: {reason}": "Der Worker hat nicht geantwortet: {reason}", + "This computer": "Dieser Computer", + "This engine cannot re-tessellate CAD parts.": "Diese Engine kann CAD-Teile nicht neu tesselieren.", + "Triangles now": "Aktuelle Dreiecke", + "Try Again": "Erneut versuchen", + "Unknown": "Unbekannt", + "Unpacking": "Wird entpackt", + "Version": "Version", + "degrees": "Grad", + "no reason was given": "es wurde kein Grund angegeben", + "{done} of {total}": "{done} von {total}", + "{n} files": "{n} Dateien", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, Protokoll {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} entpackt, Datei für Datei geprüft", + "{tag}: none for this computer": "{tag}: keiner für diesen Computer", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} Dateien, {size} entpackt" +} diff --git a/frontend/src/i18n/modules/cad/es-MX.json b/frontend/src/i18n/modules/cad/es-MX.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/cad/es-MX.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/cad/es.json b/frontend/src/i18n/modules/cad/es.json new file mode 100644 index 00000000..8f848789 --- /dev/null +++ b/frontend/src/i18n/modules/cad/es.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% del tamaño del modelo", + "About {n} triangles afterwards.": "Unos {n} triángulos después.", + "All CAD parts": "Todas las piezas CAD", + "Angle": "Ángulo", + "Angle in degrees": "Ángulo en grados", + "Apply": "Aplicar", + "Beside the FormShot engine": "Junto al motor de FormShot", + "CAD Import": "Importación CAD", + "CAD Import Settings...": "Ajustes de importación CAD...", + "CAD Options in the Import Sheet": "Opciones CAD en el panel de importación", + "CAD worker": "Worker CAD", + "CAD worker: {stage}, {pct}%": "Worker CAD: {stage}, {pct}%", + "Check the worker": "Comprobar el worker", + "Checking every file": "Comprobando cada archivo", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Elige archivos STEP o IGES para importar; se abren mediante el worker CAD.", + "Chord": "Cuerda", + "Chord as a percentage of the model size": "Cuerda como porcentaje del tamaño del modelo", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "La cuerda debe ser mayor que 0 y como máximo el {max} % del tamaño del modelo; el ángulo, de {min} a {amax} grados.", + "Chord {chord}% of the model size, angle {angle} degrees": "Cuerda {chord} % del tamaño del modelo, ángulo {angle} grados", + "Could not re-tessellate: {reason}": "No se pudo volver a teselar: {reason}", + "Custom": "Personalizada", + "Custom ({chord}%, {angle}°)": "Personalizada ({chord} %, {angle}°)", + "Default CAD quality": "Calidad CAD predeterminada", + "Download": "Descargar", + "Download and check the program that opens STEP and IGES files.": "Descarga y comprueba el programa que abre los archivos STEP e IGES.", + "Download the CAD Worker": "Descargar el worker CAD", + "Download the CAD worker": "Descargar el worker CAD", + "Downloaded into the cache folder": "Descargado en la carpeta de caché", + "Downloading": "Descargando", + "Found in": "Encontrado en", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Con qué finura las superficies STEP e IGES se convierten en triángulos al importarlas. La cuerda es la mayor separación entre un triángulo y la superficie real, como proporción del tamaño de todo el modelo; el ángulo es la mayor curvatura entre triángulos vecinos. Los ajustes más finos tardan más y generan archivos más grandes. El panel de importación parte de esta elección; allí puedes cambiarla para una sola importación.", + "Installed": "Instalado", + "Mixed": "Mixto", + "Named by FORMSHOT_CAD_WORKER": "Indicado por FORMSHOT_CAD_WORKER", + "New quality": "Calidad nueva", + "None of the selected parts came from a STEP or IGES file.": "Ninguna de las piezas seleccionadas procede de un archivo STEP o IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Ninguna de las piezas seleccionadas procede de un archivo STEP o IGES. Borra la selección para reconstruir todas las piezas CAD.", + "Not available.": "No disponible.", + "Not available: {reason}": "No disponible: {reason}", + "Not installed": "No instalado", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Aún no está instalado. FormShot lo busca en {folder}; descárgalo aquí para abrir archivos STEP e IGES.", + "Not named": "Sin indicar", + "Not recorded": "Sin registrar", + "Nothing in this document came from a STEP or IGES file.": "Nada de este documento procede de un archivo STEP o IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "No hay nada seleccionado, así que se reconstruyen todas las piezas CAD.", + "Published": "Publicado", + "Quality now": "Calidad actual", + "Re-tessellate CAD Parts": "Volver a teselar piezas CAD", + "Re-tessellate CAD Parts...": "Volver a teselar piezas CAD...", + "Re-tessellated 1 CAD part at {quality}.": "Se volvió a teselar 1 pieza CAD con calidad {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "Se volvió a teselar 1 pieza CAD con calidad {quality}: de {before} a {after} triángulos.", + "Re-tessellated {parts} CAD parts at {quality}.": "Se volvieron a teselar {parts} piezas CAD con calidad {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "Se volvieron a teselar {parts} piezas CAD con calidad {quality}: de {before} a {after} triángulos.", + "Re-tessellating": "Volviendo a teselar", + "Read the status again": "Volver a leer el estado", + "Reading the published record": "Leyendo el registro publicado", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Reconstruye las mallas de las piezas importadas de STEP o IGES con otra calidad, como un solo paso de deshacer.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "Los archivos STEP e IGES los abre el worker del kernel de FormCAD, un programa aparte que FormShot descarga una vez, comprueba archivo por archivo y guarda en tu carpeta de caché. Los demás formatos de modelo no lo necesitan.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "Los archivos STEP e IGES necesitan el worker CAD, y no hay ninguno publicado para este ordenador.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "Los archivos STEP e IGES necesitan el worker CAD, que aún no está instalado.", + "Selected CAD parts": "Piezas CAD seleccionadas", + "Source": "Origen", + "The CAD worker is installed.": "El worker CAD está instalado.", + "The CAD worker is installed. You can import this file now.": "El worker CAD está instalado. Ya puedes importar este archivo.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "El worker CAD que abre los archivos STEP e IGES y la calidad CAD predeterminada.", + "The FormShot service is not reachable.": "El servicio de FormShot no está disponible.", + "The download failed: {reason}": "La descarga falló: {reason}", + "The download was cancelled. Nothing was installed.": "Se canceló la descarga. No se instaló nada.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "El motor no ofrece ninguna estimación; las calidades más finas tardan más y generan más triángulos.", + "The parts could not be read: {reason}": "No se pudieron leer las piezas: {reason}", + "The service cannot stop a download once it has started.": "El servicio no puede detener una descarga una vez iniciada.", + "The service refused the request from this window.": "El servicio rechazó la solicitud de esta ventana.", + "The status could not be read: {reason}": "No se pudo leer el estado: {reason}", + "The worker did not answer: {reason}": "El worker no respondió: {reason}", + "This computer": "Este ordenador", + "This engine cannot re-tessellate CAD parts.": "Este motor no puede volver a teselar piezas CAD.", + "Triangles now": "Triángulos actuales", + "Try Again": "Reintentar", + "Unknown": "Desconocido", + "Unpacking": "Descomprimiendo", + "Version": "Versión", + "degrees": "grados", + "no reason was given": "no se indicó ningún motivo", + "{done} of {total}": "{done} de {total}", + "{n} files": "{n} archivos", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protocolo {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} descomprimidos, comprobados archivo por archivo", + "{tag}: none for this computer": "{tag}: ninguno para este ordenador", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} archivos, {size} descomprimidos" +} diff --git a/frontend/src/i18n/modules/cad/fi.json b/frontend/src/i18n/modules/cad/fi.json new file mode 100644 index 00000000..89373a13 --- /dev/null +++ b/frontend/src/i18n/modules/cad/fi.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% mallin koosta", + "About {n} triangles afterwards.": "Jälkeenpäin noin {n} kolmiota.", + "All CAD parts": "Kaikki CAD-osat", + "Angle": "Kulma", + "Angle in degrees": "Kulma asteina", + "Apply": "Käytä", + "Beside the FormShot engine": "FormShot-moottorin vieressä", + "CAD Import": "CAD-tuonti", + "CAD Import Settings...": "CAD-tuonnin asetukset...", + "CAD Options in the Import Sheet": "CAD-valinnat tuontiarkissa", + "CAD worker": "CAD-työprosessi", + "CAD worker: {stage}, {pct}%": "CAD-työprosessi: {stage}, {pct} %", + "Check the worker": "Tarkista työprosessi", + "Checking every file": "Tarkistetaan jokainen tiedosto", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Valitse tuotavat STEP- tai IGES-tiedostot; ne avataan CAD-työprosessin kautta.", + "Chord": "Jänne", + "Chord as a percentage of the model size": "Jänne prosentteina mallin koosta", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Jänteen on oltava yli 0 ja enintään {max} % mallin koosta; kulman {min} - {amax} astetta.", + "Chord {chord}% of the model size, angle {angle} degrees": "Jänne {chord} % mallin koosta, kulma {angle} astetta", + "Could not re-tessellate: {reason}": "Uudelleentesselointi epäonnistui: {reason}", + "Custom": "Mukautettu", + "Custom ({chord}%, {angle}°)": "Mukautettu ({chord} %, {angle}°)", + "Default CAD quality": "Oletus-CAD-laatu", + "Download": "Lataa", + "Download and check the program that opens STEP and IGES files.": "Lataa ja tarkista ohjelma, joka avaa STEP- ja IGES-tiedostot.", + "Download the CAD Worker": "Lataa CAD-työprosessi", + "Download the CAD worker": "Lataa CAD-työprosessi", + "Downloaded into the cache folder": "Ladattu välimuistikansioon", + "Downloading": "Ladataan", + "Found in": "Löytyi kohteesta", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Kuinka hienoksi STEP- ja IGES-pinnat muuttuvat kolmioiksi tuonnissa. Jänne on suurin etäisyys kolmion ja todellisen pinnan välillä osuutena koko mallin koosta; kulma on suurin taite vierekkäisten kolmioiden välillä. Hienommat asetukset kestävät kauemmin ja tuottavat suurempia tiedostoja. Tuontiarkki alkaa tällä valinnalla; voit muuttaa sitä siellä yhtä tuontia varten.", + "Installed": "Asennettu", + "Mixed": "Sekalainen", + "Named by FORMSHOT_CAD_WORKER": "Nimetty muuttujalla FORMSHOT_CAD_WORKER", + "New quality": "Uusi laatu", + "None of the selected parts came from a STEP or IGES file.": "Yksikään valituista osista ei tullut STEP- tai IGES-tiedostosta.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Yksikään valituista osista ei tullut STEP- tai IGES-tiedostosta. Tyhjennä valinta, jos haluat rakentaa kaikki CAD-osat uudelleen.", + "Not available.": "Ei saatavilla.", + "Not available: {reason}": "Ei saatavilla: {reason}", + "Not installed": "Ei asennettu", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Ei vielä asennettu. FormShot etsii sitä kansiosta {folder}; lataa se tässä avataksesi STEP- ja IGES-tiedostoja.", + "Not named": "Ei nimetty", + "Not recorded": "Ei tallennettu", + "Nothing in this document came from a STEP or IGES file.": "Mikään tässä dokumentissa ei tullut STEP- tai IGES-tiedostosta.", + "Nothing is selected, so every CAD part is rebuilt.": "Mitään ei ole valittu, joten kaikki CAD-osat rakennetaan uudelleen.", + "Published": "Julkaistu", + "Quality now": "Nykyinen laatu", + "Re-tessellate CAD Parts": "Tesseloi CAD-osat uudelleen", + "Re-tessellate CAD Parts...": "Tesseloi CAD-osat uudelleen...", + "Re-tessellated 1 CAD part at {quality}.": "1 CAD-osa tesseloitu uudelleen laadulla {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 CAD-osa tesseloitu uudelleen laadulla {quality}: {before} kolmiosta {after} kolmioon.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} CAD-osaa tesseloitu uudelleen laadulla {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} CAD-osaa tesseloitu uudelleen laadulla {quality}: {before} kolmiosta {after} kolmioon.", + "Re-tessellating": "Tesseloidaan uudelleen", + "Read the status again": "Lue tila uudelleen", + "Reading the published record": "Luetaan julkaistua tietuetta", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Rakenna STEP- tai IGES-tiedostosta tuotujen osien verkot uudelleen toisella laadulla yhtenä kumoamisvaiheena.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP- ja IGES-tiedostot avaa FormCADin ydintyöprosessi, erillinen ohjelma, jonka FormShot lataa kerran, tarkistaa tiedosto tiedostolta ja säilyttää välimuistikansiossasi. Muut mallimuodot eivät tarvitse sitä.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP- ja IGES-tiedostot tarvitsevat CAD-työprosessin, eikä tälle tietokoneelle ole julkaistu sellaista.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP- ja IGES-tiedostot tarvitsevat CAD-työprosessin, jota ei ole vielä asennettu.", + "Selected CAD parts": "Valitut CAD-osat", + "Source": "Lähde", + "The CAD worker is installed.": "CAD-työprosessi on asennettu.", + "The CAD worker is installed. You can import this file now.": "CAD-työprosessi on asennettu. Voit nyt tuoda tämän tiedoston.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "CAD-työprosessi, joka avaa STEP- ja IGES-tiedostot, sekä oletus-CAD-laatu.", + "The FormShot service is not reachable.": "FormShot-palvelu ei ole tavoitettavissa.", + "The download failed: {reason}": "Lataus epäonnistui: {reason}", + "The download was cancelled. Nothing was installed.": "Lataus peruttiin. Mitään ei asennettu.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Moottori ei anna arviota; hienommat laadut kestävät kauemmin ja tuottavat enemmän kolmioita.", + "The parts could not be read: {reason}": "Osia ei voitu lukea: {reason}", + "The service cannot stop a download once it has started.": "Palvelu ei voi pysäyttää latausta sen alettua.", + "The service refused the request from this window.": "Palvelu hylkäsi tämän ikkunan pyynnön.", + "The status could not be read: {reason}": "Tilaa ei voitu lukea: {reason}", + "The worker did not answer: {reason}": "Työprosessi ei vastannut: {reason}", + "This computer": "Tämä tietokone", + "This engine cannot re-tessellate CAD parts.": "Tämä moottori ei voi tesseloida CAD-osia uudelleen.", + "Triangles now": "Kolmioita nyt", + "Try Again": "Yritä uudelleen", + "Unknown": "Tuntematon", + "Unpacking": "Puretaan", + "Version": "Versio", + "degrees": "astetta", + "no reason was given": "syytä ei annettu", + "{done} of {total}": "{done} / {total}", + "{n} files": "{n} tiedostoa", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokolla {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} purettuna, tarkistettu tiedosto tiedostolta", + "{tag}: none for this computer": "{tag}: ei tälle tietokoneelle", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} tiedostoa, {size} purettuna" +} diff --git a/frontend/src/i18n/modules/cad/fr-CA.json b/frontend/src/i18n/modules/cad/fr-CA.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/cad/fr-CA.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/cad/fr.json b/frontend/src/i18n/modules/cad/fr.json new file mode 100644 index 00000000..284f13a1 --- /dev/null +++ b/frontend/src/i18n/modules/cad/fr.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% de la taille du modèle", + "About {n} triangles afterwards.": "Environ {n} triangles ensuite.", + "All CAD parts": "Toutes les pièces CAO", + "Angle": "Angle", + "Angle in degrees": "Angle en degrés", + "Apply": "Appliquer", + "Beside the FormShot engine": "À côté du moteur FormShot", + "CAD Import": "Import CAO", + "CAD Import Settings...": "Réglages d'import CAO...", + "CAD Options in the Import Sheet": "Options CAO dans la fenêtre d'import", + "CAD worker": "Worker CAO", + "CAD worker: {stage}, {pct}%": "Worker CAO : {stage}, {pct} %", + "Check the worker": "Vérifier le worker", + "Checking every file": "Vérification de chaque fichier", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Choisissez des fichiers STEP ou IGES à importer ; ils s'ouvrent via le worker CAO.", + "Chord": "Corde", + "Chord as a percentage of the model size": "Corde en pourcentage de la taille du modèle", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "La corde doit être supérieure à 0 et au plus égale à {max} % de la taille du modèle ; l'angle de {min} à {amax} degrés.", + "Chord {chord}% of the model size, angle {angle} degrees": "Corde {chord} % de la taille du modèle, angle {angle} degrés", + "Could not re-tessellate: {reason}": "Impossible de retesseller : {reason}", + "Custom": "Personnalisée", + "Custom ({chord}%, {angle}°)": "Personnalisée ({chord} %, {angle}°)", + "Default CAD quality": "Qualité CAO par défaut", + "Download": "Télécharger", + "Download and check the program that opens STEP and IGES files.": "Télécharger et vérifier le programme qui ouvre les fichiers STEP et IGES.", + "Download the CAD Worker": "Télécharger le worker CAO", + "Download the CAD worker": "Télécharger le worker CAO", + "Downloaded into the cache folder": "Téléchargé dans le dossier de cache", + "Downloading": "Téléchargement en cours", + "Found in": "Trouvé dans", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Précision avec laquelle les surfaces STEP et IGES deviennent des triangles à l'import. La corde est l'écart maximal entre un triangle et la surface réelle, en proportion de la taille du modèle entier ; l'angle est la plus grande déviation entre triangles voisins. Des réglages plus fins prennent plus de temps et produisent des fichiers plus volumineux. La fenêtre d'import démarre avec ce choix ; vous pouvez le modifier pour un seul import.", + "Installed": "Installé", + "Mixed": "Mixte", + "Named by FORMSHOT_CAD_WORKER": "Désigné par FORMSHOT_CAD_WORKER", + "New quality": "Nouvelle qualité", + "None of the selected parts came from a STEP or IGES file.": "Aucune des pièces sélectionnées ne provient d'un fichier STEP ou IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Aucune des pièces sélectionnées ne provient d'un fichier STEP ou IGES. Effacez la sélection pour reconstruire toutes les pièces CAO.", + "Not available.": "Indisponible.", + "Not available: {reason}": "Indisponible : {reason}", + "Not installed": "Non installé", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Pas encore installé. FormShot le cherche dans {folder} ; téléchargez-le ici pour ouvrir les fichiers STEP et IGES.", + "Not named": "Non désigné", + "Not recorded": "Non enregistré", + "Nothing in this document came from a STEP or IGES file.": "Rien dans ce document ne provient d'un fichier STEP ou IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "Rien n'est sélectionné, toutes les pièces CAO sont donc reconstruites.", + "Published": "Publié", + "Quality now": "Qualité actuelle", + "Re-tessellate CAD Parts": "Retesseller les pièces CAO", + "Re-tessellate CAD Parts...": "Retesseller les pièces CAO...", + "Re-tessellated 1 CAD part at {quality}.": "1 pièce CAO retessellée en {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 pièce CAO retessellée en {quality} : de {before} à {after} triangles.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} pièces CAO retessellées en {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} pièces CAO retessellées en {quality} : de {before} à {after} triangles.", + "Re-tessellating": "Retessellation en cours", + "Read the status again": "Relire l'état", + "Reading the published record": "Lecture de l'enregistrement publié", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Reconstruit les maillages des pièces importées depuis STEP ou IGES avec une autre qualité, en une seule étape d'annulation.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "Les fichiers STEP et IGES sont ouverts par le worker noyau de FormCAD, un programme distinct que FormShot télécharge une fois, vérifie fichier par fichier et conserve dans votre dossier de cache. Les autres formats de modèle n'en ont pas besoin.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "Les fichiers STEP et IGES nécessitent le worker CAO, et aucun n'est publié pour cet ordinateur.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "Les fichiers STEP et IGES nécessitent le worker CAO, qui n'est pas encore installé.", + "Selected CAD parts": "Pièces CAO sélectionnées", + "Source": "Source", + "The CAD worker is installed.": "Le worker CAO est installé.", + "The CAD worker is installed. You can import this file now.": "Le worker CAO est installé. Vous pouvez importer ce fichier maintenant.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Le worker CAO qui ouvre les fichiers STEP et IGES, et la qualité CAO par défaut.", + "The FormShot service is not reachable.": "Le service FormShot est injoignable.", + "The download failed: {reason}": "Le téléchargement a échoué : {reason}", + "The download was cancelled. Nothing was installed.": "Le téléchargement a été annulé. Rien n'a été installé.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Le moteur ne fournit aucune estimation ; les qualités plus fines prennent plus de temps et produisent plus de triangles.", + "The parts could not be read: {reason}": "Impossible de lire les pièces : {reason}", + "The service cannot stop a download once it has started.": "Le service ne peut pas arrêter un téléchargement une fois commencé.", + "The service refused the request from this window.": "Le service a refusé la requête de cette fenêtre.", + "The status could not be read: {reason}": "Impossible de lire l'état : {reason}", + "The worker did not answer: {reason}": "Le worker n'a pas répondu : {reason}", + "This computer": "Cet ordinateur", + "This engine cannot re-tessellate CAD parts.": "Ce moteur ne peut pas retesseller les pièces CAO.", + "Triangles now": "Triangles actuels", + "Try Again": "Réessayer", + "Unknown": "Inconnu", + "Unpacking": "Décompression", + "Version": "Version", + "degrees": "degrés", + "no reason was given": "aucune raison n'a été donnée", + "{done} of {total}": "{done} sur {total}", + "{n} files": "{n} fichiers", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protocole {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} décompressés, vérifiés fichier par fichier", + "{tag}: none for this computer": "{tag} : aucun pour cet ordinateur", + "{tag}: {files} files, {size} unpacked": "{tag} : {files} fichiers, {size} décompressés" +} diff --git a/frontend/src/i18n/modules/cad/hu.json b/frontend/src/i18n/modules/cad/hu.json new file mode 100644 index 00000000..ce0e8695 --- /dev/null +++ b/frontend/src/i18n/modules/cad/hu.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% a modell méretéből", + "About {n} triangles afterwards.": "Utána körülbelül {n} háromszög lesz.", + "All CAD parts": "Az összes CAD-alkatrész", + "Angle": "Szög", + "Angle in degrees": "Szög fokban", + "Apply": "Alkalmaz", + "Beside the FormShot engine": "A FormShot motor mellett", + "CAD Import": "CAD-importálás", + "CAD Import Settings...": "CAD-importálási beállítások...", + "CAD Options in the Import Sheet": "CAD-opciók az importálási panelen", + "CAD worker": "CAD-háttérfolyamat", + "CAD worker: {stage}, {pct}%": "CAD-háttérfolyamat: {stage}, {pct}%", + "Check the worker": "Háttérfolyamat ellenőrzése", + "Checking every file": "Minden fájl ellenőrzése", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Válassza ki az importálandó STEP vagy IGES fájlokat; ezek a CAD-háttérfolyamaton keresztül nyílnak meg.", + "Chord": "Húr", + "Chord as a percentage of the model size": "A húr a modell méretének százalékában", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "A húr értékének 0-nál nagyobbnak kell lennie, és legfeljebb a modell méretének {max}%-a lehet; a szög {min} és {amax} fok között lehet.", + "Chord {chord}% of the model size, angle {angle} degrees": "Húr: a modell méretének {chord}%-a, szög: {angle} fok", + "Could not re-tessellate: {reason}": "Az újratesszellálás nem sikerült: {reason}", + "Custom": "Egyéni", + "Custom ({chord}%, {angle}°)": "Egyéni ({chord}%, {angle}°)", + "Default CAD quality": "Alapértelmezett CAD-minőség", + "Download": "Letöltés", + "Download and check the program that opens STEP and IGES files.": "A STEP és IGES fájlokat megnyitó program letöltése és ellenőrzése.", + "Download the CAD Worker": "CAD-háttérfolyamat letöltése", + "Download the CAD worker": "CAD-háttérfolyamat letöltése", + "Downloaded into the cache folder": "Letöltve a gyorsítótár mappájába", + "Downloading": "Letöltés", + "Found in": "Található itt", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Mennyire finoman alakulnak háromszögekké a STEP és IGES felületek importáláskor. A húr a háromszög és a valódi felület közötti legnagyobb eltérés a teljes modell méretének arányában; a szög a szomszédos háromszögek közötti legnagyobb törés. A finomabb beállítások tovább tartanak, és nagyobb fájlokat eredményeznek. Az importálási panel ezzel az értékkel indul; ott egyetlen importáláshoz módosíthatja.", + "Installed": "Telepítve", + "Mixed": "Vegyes", + "Named by FORMSHOT_CAD_WORKER": "A FORMSHOT_CAD_WORKER adja meg", + "New quality": "Új minőség", + "None of the selected parts came from a STEP or IGES file.": "A kijelölt alkatrészek egyike sem STEP vagy IGES fájlból származik.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "A kijelölt alkatrészek egyike sem STEP vagy IGES fájlból származik. Szüntesse meg a kijelölést, hogy az összes CAD-alkatrész újra felépüljön.", + "Not available.": "Nem érhető el.", + "Not available: {reason}": "Nem érhető el: {reason}", + "Not installed": "Nincs telepítve", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Még nincs telepítve. A FormShot ebben keresi: {folder}; innen töltse le a STEP és IGES fájlok megnyitásához.", + "Not named": "Nincs megadva", + "Not recorded": "Nincs rögzítve", + "Nothing in this document came from a STEP or IGES file.": "A dokumentumban semmi sem származik STEP vagy IGES fájlból.", + "Nothing is selected, so every CAD part is rebuilt.": "Nincs kijelölés, ezért az összes CAD-alkatrész újra felépül.", + "Published": "Közzétéve", + "Quality now": "Jelenlegi minőség", + "Re-tessellate CAD Parts": "CAD-alkatrészek újratesszellálása", + "Re-tessellate CAD Parts...": "CAD-alkatrészek újratesszellálása...", + "Re-tessellated 1 CAD part at {quality}.": "1 CAD-alkatrész újratesszellálva, minőség: {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 CAD-alkatrész újratesszellálva, minőség: {quality}: {before} háromszögről {after} háromszögre.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} CAD-alkatrész újratesszellálva, minőség: {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} CAD-alkatrész újratesszellálva, minőség: {quality}: {before} háromszögről {after} háromszögre.", + "Re-tessellating": "Újratesszellálás", + "Read the status again": "Állapot újraolvasása", + "Reading the published record": "A közzétett rekord beolvasása", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "A STEP vagy IGES fájlból importált alkatrészek hálóinak újraépítése más minőségben, egyetlen visszavonási lépésként.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "A STEP és IGES fájlokat a FormCAD magfolyamata nyitja meg, egy különálló program, amelyet a FormShot egyszer letölt, fájlonként ellenőriz, és a gyorsítótár mappájában tart. Más modellformátumokhoz nincs rá szükség.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "A STEP és IGES fájlokhoz CAD-háttérfolyamat kell, és ehhez a számítógéphez nincs közzétéve ilyen.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "A STEP és IGES fájlokhoz CAD-háttérfolyamat kell, amely még nincs telepítve.", + "Selected CAD parts": "Kijelölt CAD-alkatrészek", + "Source": "Forrás", + "The CAD worker is installed.": "A CAD-háttérfolyamat telepítve van.", + "The CAD worker is installed. You can import this file now.": "A CAD-háttérfolyamat telepítve van. Most már importálhatja ezt a fájlt.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "A STEP és IGES fájlokat megnyitó CAD-háttérfolyamat és az alapértelmezett CAD-minőség.", + "The FormShot service is not reachable.": "A FormShot szolgáltatás nem érhető el.", + "The download failed: {reason}": "A letöltés sikertelen: {reason}", + "The download was cancelled. Nothing was installed.": "A letöltés megszakadt. Semmi sem lett telepítve.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "A motor nem ad becslést; a finomabb minőségek tovább tartanak, és több háromszöget adnak.", + "The parts could not be read: {reason}": "Az alkatrészeket nem sikerült beolvasni: {reason}", + "The service cannot stop a download once it has started.": "A szolgáltatás nem tudja leállítani a letöltést, ha az már elindult.", + "The service refused the request from this window.": "A szolgáltatás elutasította az ebből az ablakból érkező kérést.", + "The status could not be read: {reason}": "Az állapotot nem sikerült beolvasni: {reason}", + "The worker did not answer: {reason}": "A háttérfolyamat nem válaszolt: {reason}", + "This computer": "Ez a számítógép", + "This engine cannot re-tessellate CAD parts.": "Ez a motor nem tudja újratesszellálni a CAD-alkatrészeket.", + "Triangles now": "Jelenlegi háromszögek", + "Try Again": "Próbálja újra", + "Unknown": "Ismeretlen", + "Unpacking": "Kicsomagolás", + "Version": "Verzió", + "degrees": "fok", + "no reason was given": "nem adtak meg okot", + "{done} of {total}": "{done} / {total}", + "{n} files": "{n} fájl", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokoll: {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} kicsomagolva, fájlonként ellenőrizve", + "{tag}: none for this computer": "{tag}: ehhez a számítógéphez nincs", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} fájl, {size} kicsomagolva" +} diff --git a/frontend/src/i18n/modules/cad/id.json b/frontend/src/i18n/modules/cad/id.json new file mode 100644 index 00000000..d4d2417e --- /dev/null +++ b/frontend/src/i18n/modules/cad/id.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% dari ukuran model", + "About {n} triangles afterwards.": "Sekitar {n} segitiga setelahnya.", + "All CAD parts": "Semua bagian CAD", + "Angle": "Sudut", + "Angle in degrees": "Sudut dalam derajat", + "Apply": "Terapkan", + "Beside the FormShot engine": "Di samping mesin FormShot", + "CAD Import": "Impor CAD", + "CAD Import Settings...": "Pengaturan Impor CAD...", + "CAD Options in the Import Sheet": "Opsi CAD di Lembar Impor", + "CAD worker": "Worker CAD", + "CAD worker: {stage}, {pct}%": "Worker CAD: {stage}, {pct}%", + "Check the worker": "Periksa worker", + "Checking every file": "Memeriksa setiap file", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Pilih file STEP atau IGES untuk diimpor; file ini dibuka lewat worker CAD.", + "Chord": "Chord", + "Chord as a percentage of the model size": "Chord sebagai persentase ukuran model", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Chord harus di atas 0 dan paling besar {max}% dari ukuran model; sudut dari {min} sampai {amax} derajat.", + "Chord {chord}% of the model size, angle {angle} degrees": "Chord {chord}% dari ukuran model, sudut {angle} derajat", + "Could not re-tessellate: {reason}": "Tidak dapat melakukan tesselasi ulang: {reason}", + "Custom": "Kustom", + "Custom ({chord}%, {angle}°)": "Kustom ({chord}%, {angle}°)", + "Default CAD quality": "Kualitas CAD default", + "Download": "Unduh", + "Download and check the program that opens STEP and IGES files.": "Unduh dan periksa program yang membuka file STEP dan IGES.", + "Download the CAD Worker": "Unduh Worker CAD", + "Download the CAD worker": "Unduh worker CAD", + "Downloaded into the cache folder": "Diunduh ke folder cache", + "Downloading": "Mengunduh", + "Found in": "Ditemukan di", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Seberapa halus permukaan STEP dan IGES diubah menjadi segitiga saat diimpor. Chord adalah celah terbesar antara segitiga dan permukaan sebenarnya, sebagai porsi dari ukuran seluruh model; sudut adalah tekukan terbesar antara segitiga yang bersebelahan. Pengaturan yang lebih halus memakan waktu lebih lama dan menghasilkan file lebih besar. Lembar impor dimulai dengan pilihan ini; Anda dapat mengubahnya untuk satu impor di sana.", + "Installed": "Terpasang", + "Mixed": "Campuran", + "Named by FORMSHOT_CAD_WORKER": "Dinamai oleh FORMSHOT_CAD_WORKER", + "New quality": "Kualitas baru", + "None of the selected parts came from a STEP or IGES file.": "Tidak ada bagian terpilih yang berasal dari file STEP atau IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Tidak ada bagian terpilih yang berasal dari file STEP atau IGES. Kosongkan pilihan untuk membangun ulang semua bagian CAD.", + "Not available.": "Tidak tersedia.", + "Not available: {reason}": "Tidak tersedia: {reason}", + "Not installed": "Belum terpasang", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Belum terpasang. FormShot mencarinya di {folder}; unduh di sini untuk membuka file STEP dan IGES.", + "Not named": "Tidak dinamai", + "Not recorded": "Tidak tercatat", + "Nothing in this document came from a STEP or IGES file.": "Tidak ada yang berasal dari file STEP atau IGES di dokumen ini.", + "Nothing is selected, so every CAD part is rebuilt.": "Tidak ada yang dipilih, sehingga semua bagian CAD dibangun ulang.", + "Published": "Dipublikasikan", + "Quality now": "Kualitas saat ini", + "Re-tessellate CAD Parts": "Tesselasi Ulang Bagian CAD", + "Re-tessellate CAD Parts...": "Tesselasi Ulang Bagian CAD...", + "Re-tessellated 1 CAD part at {quality}.": "1 bagian CAD ditesselasi ulang pada {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 bagian CAD ditesselasi ulang pada {quality}: {before} menjadi {after} segitiga.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} bagian CAD ditesselasi ulang pada {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} bagian CAD ditesselasi ulang pada {quality}: {before} menjadi {after} segitiga.", + "Re-tessellating": "Melakukan tesselasi ulang", + "Read the status again": "Baca ulang status", + "Reading the published record": "Membaca catatan yang dipublikasikan", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Bangun ulang mesh bagian yang diimpor dari STEP atau IGES pada kualitas lain, sebagai satu langkah urungkan.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "File STEP dan IGES dibuka oleh worker kernel FormCAD, program terpisah yang diunduh FormShot sekali, diperiksa file demi file, dan disimpan di folder cache Anda. Format model lain tidak memerlukannya.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "File STEP dan IGES memerlukan worker CAD, dan belum ada yang dipublikasikan untuk komputer ini.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "File STEP dan IGES memerlukan worker CAD, yang belum terpasang.", + "Selected CAD parts": "Bagian CAD terpilih", + "Source": "Sumber", + "The CAD worker is installed.": "Worker CAD sudah terpasang.", + "The CAD worker is installed. You can import this file now.": "Worker CAD sudah terpasang. Anda dapat mengimpor file ini sekarang.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Worker CAD yang membuka file STEP dan IGES, dan kualitas CAD default.", + "The FormShot service is not reachable.": "Layanan FormShot tidak dapat dijangkau.", + "The download failed: {reason}": "Pengunduhan gagal: {reason}", + "The download was cancelled. Nothing was installed.": "Pengunduhan dibatalkan. Tidak ada yang dipasang.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Mesin tidak memberikan perkiraan; kualitas yang lebih halus memakan waktu lebih lama dan menghasilkan lebih banyak segitiga.", + "The parts could not be read: {reason}": "Bagian tidak dapat dibaca: {reason}", + "The service cannot stop a download once it has started.": "Layanan tidak dapat menghentikan unduhan yang sudah dimulai.", + "The service refused the request from this window.": "Layanan menolak permintaan dari jendela ini.", + "The status could not be read: {reason}": "Status tidak dapat dibaca: {reason}", + "The worker did not answer: {reason}": "Worker tidak menjawab: {reason}", + "This computer": "Komputer ini", + "This engine cannot re-tessellate CAD parts.": "Mesin ini tidak dapat melakukan tesselasi ulang bagian CAD.", + "Triangles now": "Segitiga saat ini", + "Try Again": "Coba Lagi", + "Unknown": "Tidak diketahui", + "Unpacking": "Mengekstrak", + "Version": "Versi", + "degrees": "derajat", + "no reason was given": "tidak ada alasan yang diberikan", + "{done} of {total}": "{done} dari {total}", + "{n} files": "{n} file", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokol {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} diekstrak, diperiksa file demi file", + "{tag}: none for this computer": "{tag}: tidak ada untuk komputer ini", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} file, {size} diekstrak" +} diff --git a/frontend/src/i18n/modules/cad/it.json b/frontend/src/i18n/modules/cad/it.json new file mode 100644 index 00000000..7c9e5654 --- /dev/null +++ b/frontend/src/i18n/modules/cad/it.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% delle dimensioni del modello", + "About {n} triangles afterwards.": "Circa {n} triangoli dopo.", + "All CAD parts": "Tutte le parti CAD", + "Angle": "Angolo", + "Angle in degrees": "Angolo in gradi", + "Apply": "Applica", + "Beside the FormShot engine": "Accanto al motore di FormShot", + "CAD Import": "Importazione CAD", + "CAD Import Settings...": "Impostazioni importazione CAD...", + "CAD Options in the Import Sheet": "Opzioni CAD nel pannello di importazione", + "CAD worker": "Worker CAD", + "CAD worker: {stage}, {pct}%": "Worker CAD: {stage}, {pct}%", + "Check the worker": "Controlla il worker", + "Checking every file": "Controllo di ogni file", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Scegli i file STEP o IGES da importare; si aprono tramite il worker CAD.", + "Chord": "Corda", + "Chord as a percentage of the model size": "Corda in percentuale delle dimensioni del modello", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "La corda deve essere maggiore di 0 e al massimo {max}% delle dimensioni del modello; l'angolo da {min} a {amax} gradi.", + "Chord {chord}% of the model size, angle {angle} degrees": "Corda {chord}% delle dimensioni del modello, angolo {angle} gradi", + "Could not re-tessellate: {reason}": "Impossibile ritassellare: {reason}", + "Custom": "Personalizzata", + "Custom ({chord}%, {angle}°)": "Personalizzata ({chord}%, {angle}°)", + "Default CAD quality": "Qualità CAD predefinita", + "Download": "Scarica", + "Download and check the program that opens STEP and IGES files.": "Scarica e controlla il programma che apre i file STEP e IGES.", + "Download the CAD Worker": "Scarica il worker CAD", + "Download the CAD worker": "Scarica il worker CAD", + "Downloaded into the cache folder": "Scaricato nella cartella della cache", + "Downloading": "Download in corso", + "Found in": "Trovato in", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Quanto finemente le superfici STEP e IGES diventano triangoli durante l'importazione. La corda è lo scarto massimo tra un triangolo e la superficie reale, come frazione delle dimensioni dell'intero modello; l'angolo è la massima piegatura tra triangoli adiacenti. Impostazioni più fini richiedono più tempo e producono file più grandi. Il pannello di importazione parte da questa scelta; lì puoi cambiarla per una singola importazione.", + "Installed": "Installato", + "Mixed": "Misto", + "Named by FORMSHOT_CAD_WORKER": "Indicato da FORMSHOT_CAD_WORKER", + "New quality": "Nuova qualità", + "None of the selected parts came from a STEP or IGES file.": "Nessuna delle parti selezionate proviene da un file STEP o IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Nessuna delle parti selezionate proviene da un file STEP o IGES. Annulla la selezione per ricostruire tutte le parti CAD.", + "Not available.": "Non disponibile.", + "Not available: {reason}": "Non disponibile: {reason}", + "Not installed": "Non installato", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Non ancora installato. FormShot lo cerca in {folder}; scaricalo qui per aprire i file STEP e IGES.", + "Not named": "Non indicato", + "Not recorded": "Non registrato", + "Nothing in this document came from a STEP or IGES file.": "Nulla in questo documento proviene da un file STEP o IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "Nessuna selezione, quindi vengono ricostruite tutte le parti CAD.", + "Published": "Pubblicato", + "Quality now": "Qualità attuale", + "Re-tessellate CAD Parts": "Ritassella parti CAD", + "Re-tessellate CAD Parts...": "Ritassella parti CAD...", + "Re-tessellated 1 CAD part at {quality}.": "1 parte CAD ritassellata con qualità {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 parte CAD ritassellata con qualità {quality}: da {before} a {after} triangoli.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} parti CAD ritassellate con qualità {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} parti CAD ritassellate con qualità {quality}: da {before} a {after} triangoli.", + "Re-tessellating": "Ritassellazione in corso", + "Read the status again": "Rileggi lo stato", + "Reading the published record": "Lettura del record pubblicato", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Ricostruisce le mesh delle parti importate da STEP o IGES con un'altra qualità, come un unico passaggio di annullamento.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "I file STEP e IGES vengono aperti dal worker del kernel di FormCAD, un programma separato che FormShot scarica una volta, controlla file per file e conserva nella tua cartella della cache. Gli altri formati di modello non ne hanno bisogno.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "I file STEP e IGES richiedono il worker CAD, e per questo computer non ne è pubblicato nessuno.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "I file STEP e IGES richiedono il worker CAD, che non è ancora installato.", + "Selected CAD parts": "Parti CAD selezionate", + "Source": "Sorgente", + "The CAD worker is installed.": "Il worker CAD è installato.", + "The CAD worker is installed. You can import this file now.": "Il worker CAD è installato. Ora puoi importare questo file.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Il worker CAD che apre i file STEP e IGES e la qualità CAD predefinita.", + "The FormShot service is not reachable.": "Il servizio FormShot non è raggiungibile.", + "The download failed: {reason}": "Il download non è riuscito: {reason}", + "The download was cancelled. Nothing was installed.": "Il download è stato annullato. Non è stato installato nulla.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Il motore non fornisce una stima; le qualità più fini richiedono più tempo e producono più triangoli.", + "The parts could not be read: {reason}": "Impossibile leggere le parti: {reason}", + "The service cannot stop a download once it has started.": "Il servizio non può interrompere un download già avviato.", + "The service refused the request from this window.": "Il servizio ha rifiutato la richiesta di questa finestra.", + "The status could not be read: {reason}": "Impossibile leggere lo stato: {reason}", + "The worker did not answer: {reason}": "Il worker non ha risposto: {reason}", + "This computer": "Questo computer", + "This engine cannot re-tessellate CAD parts.": "Questo motore non può ritassellare le parti CAD.", + "Triangles now": "Triangoli attuali", + "Try Again": "Riprova", + "Unknown": "Sconosciuto", + "Unpacking": "Decompressione", + "Version": "Versione", + "degrees": "gradi", + "no reason was given": "non è stato indicato alcun motivo", + "{done} of {total}": "{done} di {total}", + "{n} files": "{n} file", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protocollo {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} decompressi, controllati file per file", + "{tag}: none for this computer": "{tag}: nessuno per questo computer", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} file, {size} decompressi" +} diff --git a/frontend/src/i18n/modules/cad/ja.json b/frontend/src/i18n/modules/cad/ja.json new file mode 100644 index 00000000..98998a0c --- /dev/null +++ b/frontend/src/i18n/modules/cad/ja.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "モデルサイズに対する %", + "About {n} triangles afterwards.": "変更後は約 {n} 個の三角形になります。", + "All CAD parts": "すべての CAD パーツ", + "Angle": "角度", + "Angle in degrees": "角度 (度)", + "Apply": "適用", + "Beside the FormShot engine": "FormShot エンジンの隣", + "CAD Import": "CAD インポート", + "CAD Import Settings...": "CAD インポート設定...", + "CAD Options in the Import Sheet": "インポートシートの CAD オプション", + "CAD worker": "CAD ワーカー", + "CAD worker: {stage}, {pct}%": "CAD ワーカー: {stage}、{pct}%", + "Check the worker": "ワーカーを確認", + "Checking every file": "すべてのファイルを確認中", + "Choose STEP or IGES files to import; they open through the CAD worker.": "STEP または IGES ファイルを選んで読み込みます。ファイルは CAD ワーカー経由で開かれます。", + "Chord": "コード長", + "Chord as a percentage of the model size": "コード長 (モデルサイズに対する割合)", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "コード長は 0 より大きく、モデルサイズの {max}% 以下にしてください。角度は {min} から {amax} 度の範囲です。", + "Chord {chord}% of the model size, angle {angle} degrees": "コード長 モデルサイズの {chord}%、角度 {angle} 度", + "Could not re-tessellate: {reason}": "再テッセレートできませんでした: {reason}", + "Custom": "カスタム", + "Custom ({chord}%, {angle}°)": "カスタム ({chord}%、{angle}°)", + "Default CAD quality": "既定の CAD 品質", + "Download": "ダウンロード", + "Download and check the program that opens STEP and IGES files.": "STEP と IGES ファイルを開くプログラムをダウンロードして確認します。", + "Download the CAD Worker": "CAD ワーカーをダウンロード", + "Download the CAD worker": "CAD ワーカーをダウンロード", + "Downloaded into the cache folder": "キャッシュフォルダにダウンロードしました", + "Downloading": "ダウンロード中", + "Found in": "検出場所", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "STEP と IGES のサーフェスを読み込むときに、どれだけ細かく三角形に分割するかを決めます。コード長は、三角形と実際のサーフェスとの最大の隔たりを、モデル全体のサイズに対する割合で表したものです。角度は、隣り合う三角形の間の最大の折れ曲がりです。細かい設定ほど時間がかかり、ファイルも大きくなります。インポートシートはこの選択で始まり、1 回の読み込みに限ってそこで変更できます。", + "Installed": "インストール済み", + "Mixed": "混在", + "Named by FORMSHOT_CAD_WORKER": "FORMSHOT_CAD_WORKER で指定", + "New quality": "新しい品質", + "None of the selected parts came from a STEP or IGES file.": "選択したパーツに、STEP または IGES ファイル由来のものはありません。", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "選択したパーツに、STEP または IGES ファイル由来のものはありません。選択を解除すると、すべての CAD パーツを再構築します。", + "Not available.": "利用できません。", + "Not available: {reason}": "利用できません: {reason}", + "Not installed": "未インストール", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "まだインストールされていません。FormShot は {folder} で探します。STEP と IGES ファイルを開くには、ここからダウンロードしてください。", + "Not named": "未指定", + "Not recorded": "記録なし", + "Nothing in this document came from a STEP or IGES file.": "このドキュメントに、STEP または IGES ファイル由来のものはありません。", + "Nothing is selected, so every CAD part is rebuilt.": "何も選択されていないため、すべての CAD パーツを再構築します。", + "Published": "公開済み", + "Quality now": "現在の品質", + "Re-tessellate CAD Parts": "CAD パーツを再テッセレート", + "Re-tessellate CAD Parts...": "CAD パーツを再テッセレート...", + "Re-tessellated 1 CAD part at {quality}.": "CAD パーツ 1 個を {quality} で再テッセレートしました。", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "CAD パーツ 1 個を {quality} で再テッセレートしました: 三角形 {before} 個から {after} 個へ。", + "Re-tessellated {parts} CAD parts at {quality}.": "CAD パーツ {parts} 個を {quality} で再テッセレートしました。", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "CAD パーツ {parts} 個を {quality} で再テッセレートしました: 三角形 {before} 個から {after} 個へ。", + "Re-tessellating": "再テッセレート中", + "Read the status again": "状態を再読み込み", + "Reading the published record": "公開レコードを読み取り中", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "STEP または IGES から読み込んだパーツのメッシュを、別の品質で再構築します。取り消しは 1 回で戻せます。", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP と IGES ファイルは、FormCAD のカーネルワーカーで開きます。これは別のプログラムで、FormShot が一度だけダウンロードし、ファイルごとに確認して、キャッシュフォルダに保管します。ほかのモデル形式では不要です。", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP と IGES ファイルには CAD ワーカーが必要ですが、このコンピュータ向けには公開されていません。", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP と IGES ファイルには CAD ワーカーが必要ですが、まだインストールされていません。", + "Selected CAD parts": "選択中の CAD パーツ", + "Source": "ソース", + "The CAD worker is installed.": "CAD ワーカーはインストールされています。", + "The CAD worker is installed. You can import this file now.": "CAD ワーカーはインストールされています。このファイルを今すぐ読み込めます。", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "STEP と IGES ファイルを開く CAD ワーカーと、既定の CAD 品質です。", + "The FormShot service is not reachable.": "FormShot サービスに接続できません。", + "The download failed: {reason}": "ダウンロードに失敗しました: {reason}", + "The download was cancelled. Nothing was installed.": "ダウンロードはキャンセルされました。何もインストールされていません。", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "エンジンは見積もりを返しません。品質を上げるほど時間がかかり、三角形も増えます。", + "The parts could not be read: {reason}": "パーツを読み取れませんでした: {reason}", + "The service cannot stop a download once it has started.": "サービスは、ダウンロードを開始すると中止できません。", + "The service refused the request from this window.": "サービスがこのウィンドウからのリクエストを拒否しました。", + "The status could not be read: {reason}": "状態を読み取れませんでした: {reason}", + "The worker did not answer: {reason}": "ワーカーから応答がありませんでした: {reason}", + "This computer": "このコンピュータ", + "This engine cannot re-tessellate CAD parts.": "このエンジンは CAD パーツを再テッセレートできません。", + "Triangles now": "現在の三角形数", + "Try Again": "再試行", + "Unknown": "不明", + "Unpacking": "展開中", + "Version": "バージョン", + "degrees": "度", + "no reason was given": "理由は示されませんでした", + "{done} of {total}": "{done} / {total}", + "{n} files": "{n} 個のファイル", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}、OpenCascade {occt}、プロトコル {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}、展開後 {size}、ファイルごとに確認済み", + "{tag}: none for this computer": "{tag}: このコンピュータ向けはありません", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} 個のファイル、展開後 {size}" +} diff --git a/frontend/src/i18n/modules/cad/ko.json b/frontend/src/i18n/modules/cad/ko.json new file mode 100644 index 00000000..8eb1430b --- /dev/null +++ b/frontend/src/i18n/modules/cad/ko.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "모델 크기 대비 %", + "About {n} triangles afterwards.": "이후 삼각형은 약 {n}개가 됩니다.", + "All CAD parts": "모든 CAD 파트", + "Angle": "각도", + "Angle in degrees": "각도(도)", + "Apply": "적용", + "Beside the FormShot engine": "FormShot 엔진 옆", + "CAD Import": "CAD 가져오기", + "CAD Import Settings...": "CAD 가져오기 설정...", + "CAD Options in the Import Sheet": "가져오기 시트의 CAD 옵션", + "CAD worker": "CAD 워커", + "CAD worker: {stage}, {pct}%": "CAD 워커: {stage}, {pct}%", + "Check the worker": "워커 확인", + "Checking every file": "모든 파일 확인 중", + "Choose STEP or IGES files to import; they open through the CAD worker.": "가져올 STEP 또는 IGES 파일을 선택하세요. 파일은 CAD 워커를 통해 열립니다.", + "Chord": "현", + "Chord as a percentage of the model size": "현(모델 크기 대비 비율)", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "현은 0보다 크고 모델 크기의 {max}% 이하여야 합니다. 각도는 {min}에서 {amax}도 사이여야 합니다.", + "Chord {chord}% of the model size, angle {angle} degrees": "현: 모델 크기의 {chord}%, 각도 {angle}도", + "Could not re-tessellate: {reason}": "다시 테셀레이션하지 못했습니다: {reason}", + "Custom": "사용자 지정", + "Custom ({chord}%, {angle}°)": "사용자 지정 ({chord}%, {angle}°)", + "Default CAD quality": "기본 CAD 품질", + "Download": "다운로드", + "Download and check the program that opens STEP and IGES files.": "STEP 및 IGES 파일을 여는 프로그램을 다운로드하고 확인합니다.", + "Download the CAD Worker": "CAD 워커 다운로드", + "Download the CAD worker": "CAD 워커 다운로드", + "Downloaded into the cache folder": "캐시 폴더에 다운로드됨", + "Downloading": "다운로드 중", + "Found in": "발견된 위치", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "STEP 및 IGES 서피스를 가져올 때 삼각형으로 얼마나 촘촘히 나눌지 정합니다. 현은 삼각형과 실제 서피스 사이의 최대 간격을 모델 전체 크기의 비율로 나타낸 값이고, 각도는 이웃한 삼각형 사이의 최대 꺾임입니다. 설정이 촘촘할수록 시간이 오래 걸리고 파일이 커집니다. 가져오기 시트는 이 선택으로 시작하며, 한 번의 가져오기에 한해 시트에서 바꿀 수 있습니다.", + "Installed": "설치됨", + "Mixed": "혼합", + "Named by FORMSHOT_CAD_WORKER": "FORMSHOT_CAD_WORKER로 지정됨", + "New quality": "새 품질", + "None of the selected parts came from a STEP or IGES file.": "선택한 파트 중 STEP 또는 IGES 파일에서 온 것이 없습니다.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "선택한 파트 중 STEP 또는 IGES 파일에서 온 것이 없습니다. 선택을 해제하면 모든 CAD 파트를 다시 만듭니다.", + "Not available.": "사용할 수 없음.", + "Not available: {reason}": "사용할 수 없음: {reason}", + "Not installed": "설치되지 않음", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "아직 설치되지 않았습니다. FormShot은 {folder}에서 찾습니다. STEP 및 IGES 파일을 열려면 여기서 다운로드하세요.", + "Not named": "지정되지 않음", + "Not recorded": "기록되지 않음", + "Nothing in this document came from a STEP or IGES file.": "이 문서에는 STEP 또는 IGES 파일에서 온 항목이 없습니다.", + "Nothing is selected, so every CAD part is rebuilt.": "선택한 항목이 없으므로 모든 CAD 파트를 다시 만듭니다.", + "Published": "게시됨", + "Quality now": "현재 품질", + "Re-tessellate CAD Parts": "CAD 파트 다시 테셀레이션", + "Re-tessellate CAD Parts...": "CAD 파트 다시 테셀레이션...", + "Re-tessellated 1 CAD part at {quality}.": "CAD 파트 1개를 {quality}(으)로 다시 테셀레이션했습니다.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "CAD 파트 1개를 {quality}(으)로 다시 테셀레이션했습니다: 삼각형 {before}개에서 {after}개로.", + "Re-tessellated {parts} CAD parts at {quality}.": "CAD 파트 {parts}개를 {quality}(으)로 다시 테셀레이션했습니다.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "CAD 파트 {parts}개를 {quality}(으)로 다시 테셀레이션했습니다: 삼각형 {before}개에서 {after}개로.", + "Re-tessellating": "다시 테셀레이션하는 중", + "Read the status again": "상태 다시 읽기", + "Reading the published record": "게시된 기록을 읽는 중", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "STEP 또는 IGES에서 가져온 파트의 메시를 다른 품질로 다시 만듭니다. 실행 취소는 한 단계로 처리됩니다.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP 및 IGES 파일은 FormCAD의 커널 워커로 엽니다. 이 별도의 프로그램은 FormShot이 한 번 다운로드하고 파일별로 확인한 뒤 캐시 폴더에 보관합니다. 다른 모델 형식에는 필요하지 않습니다.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP 및 IGES 파일에는 CAD 워커가 필요하지만, 이 컴퓨터용으로 게시된 것이 없습니다.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP 및 IGES 파일에는 CAD 워커가 필요하지만 아직 설치되지 않았습니다.", + "Selected CAD parts": "선택한 CAD 파트", + "Source": "소스", + "The CAD worker is installed.": "CAD 워커가 설치되어 있습니다.", + "The CAD worker is installed. You can import this file now.": "CAD 워커가 설치되어 있습니다. 지금 이 파일을 가져올 수 있습니다.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "STEP 및 IGES 파일을 여는 CAD 워커와 기본 CAD 품질입니다.", + "The FormShot service is not reachable.": "FormShot 서비스에 연결할 수 없습니다.", + "The download failed: {reason}": "다운로드에 실패했습니다: {reason}", + "The download was cancelled. Nothing was installed.": "다운로드가 취소되었습니다. 설치된 것은 없습니다.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "엔진이 예상값을 제공하지 않습니다. 품질이 높을수록 시간이 오래 걸리고 삼각형이 늘어납니다.", + "The parts could not be read: {reason}": "파트를 읽지 못했습니다: {reason}", + "The service cannot stop a download once it has started.": "서비스는 다운로드를 시작하면 중단할 수 없습니다.", + "The service refused the request from this window.": "서비스가 이 창의 요청을 거부했습니다.", + "The status could not be read: {reason}": "상태를 읽지 못했습니다: {reason}", + "The worker did not answer: {reason}": "워커가 응답하지 않았습니다: {reason}", + "This computer": "이 컴퓨터", + "This engine cannot re-tessellate CAD parts.": "이 엔진은 CAD 파트를 다시 테셀레이션할 수 없습니다.", + "Triangles now": "현재 삼각형 수", + "Try Again": "다시 시도", + "Unknown": "알 수 없음", + "Unpacking": "압축 푸는 중", + "Version": "버전", + "degrees": "도", + "no reason was given": "이유가 제공되지 않았습니다", + "{done} of {total}": "{done} / {total}", + "{n} files": "파일 {n}개", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, 프로토콜 {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, 압축 해제 후 {size}, 파일별로 확인됨", + "{tag}: none for this computer": "{tag}: 이 컴퓨터용 없음", + "{tag}: {files} files, {size} unpacked": "{tag}: 파일 {files}개, 압축 해제 후 {size}" +} diff --git a/frontend/src/i18n/modules/cad/nb.json b/frontend/src/i18n/modules/cad/nb.json new file mode 100644 index 00000000..b2a8bf22 --- /dev/null +++ b/frontend/src/i18n/modules/cad/nb.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% av modellstørrelsen", + "About {n} triangles afterwards.": "Omtrent {n} trekanter etterpå.", + "All CAD parts": "Alle CAD-deler", + "Angle": "Vinkel", + "Angle in degrees": "Vinkel i grader", + "Apply": "Bruk", + "Beside the FormShot engine": "Ved siden av FormShot-motoren", + "CAD Import": "CAD-import", + "CAD Import Settings...": "CAD-importinnstillinger...", + "CAD Options in the Import Sheet": "CAD-alternativer i importvinduet", + "CAD worker": "CAD-worker", + "CAD worker: {stage}, {pct}%": "CAD-worker: {stage}, {pct}%", + "Check the worker": "Kontroller workeren", + "Checking every file": "Kontrollerer hver fil", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Velg STEP- eller IGES-filer som skal importeres; de åpnes via CAD-workeren.", + "Chord": "Korde", + "Chord as a percentage of the model size": "Korde som prosent av modellstørrelsen", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Korden må være over 0 og høyst {max}% av modellstørrelsen; vinkelen fra {min} til {amax} grader.", + "Chord {chord}% of the model size, angle {angle} degrees": "Korde {chord}% av modellstørrelsen, vinkel {angle} grader", + "Could not re-tessellate: {reason}": "Kunne ikke tesselere på nytt: {reason}", + "Custom": "Egendefinert", + "Custom ({chord}%, {angle}°)": "Egendefinert ({chord}%, {angle}°)", + "Default CAD quality": "Standard CAD-kvalitet", + "Download": "Last ned", + "Download and check the program that opens STEP and IGES files.": "Last ned og kontroller programmet som åpner STEP- og IGES-filer.", + "Download the CAD Worker": "Last ned CAD-workeren", + "Download the CAD worker": "Last ned CAD-workeren", + "Downloaded into the cache folder": "Lastet ned til hurtigbuffermappen", + "Downloading": "Laster ned", + "Found in": "Funnet i", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Hvor fint STEP- og IGES-flater blir til trekanter ved import. Korden er det største avviket mellom en trekant og den virkelige flaten, som andel av hele modellens størrelse; vinkelen er det største knekket mellom nabotrekanter. Finere innstillinger tar lengre tid og gir større filer. Importvinduet starter med dette valget; der kan du endre det for én enkelt import.", + "Installed": "Installert", + "Mixed": "Blandet", + "Named by FORMSHOT_CAD_WORKER": "Angitt av FORMSHOT_CAD_WORKER", + "New quality": "Ny kvalitet", + "None of the selected parts came from a STEP or IGES file.": "Ingen av de valgte delene kom fra en STEP- eller IGES-fil.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Ingen av de valgte delene kom fra en STEP- eller IGES-fil. Fjern markeringen for å bygge om alle CAD-deler.", + "Not available.": "Ikke tilgjengelig.", + "Not available: {reason}": "Ikke tilgjengelig: {reason}", + "Not installed": "Ikke installert", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Ikke installert ennå. FormShot leter etter den i {folder}; last den ned her for å åpne STEP- og IGES-filer.", + "Not named": "Ikke angitt", + "Not recorded": "Ikke registrert", + "Nothing in this document came from a STEP or IGES file.": "Ingenting i dette dokumentet kom fra en STEP- eller IGES-fil.", + "Nothing is selected, so every CAD part is rebuilt.": "Ingenting er valgt, så alle CAD-deler bygges om.", + "Published": "Publisert", + "Quality now": "Kvalitet nå", + "Re-tessellate CAD Parts": "Tesseler CAD-deler på nytt", + "Re-tessellate CAD Parts...": "Tesseler CAD-deler på nytt...", + "Re-tessellated 1 CAD part at {quality}.": "1 CAD-del tesselert på nytt med {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 CAD-del tesselert på nytt med {quality}: {before} til {after} trekanter.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} CAD-deler tesselert på nytt med {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} CAD-deler tesselert på nytt med {quality}: {before} til {after} trekanter.", + "Re-tessellating": "Tesselerer på nytt", + "Read the status again": "Les statusen på nytt", + "Reading the published record": "Leser den publiserte posten", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Bygger om meshene til deler importert fra STEP eller IGES med en annen kvalitet, som ett angretrinn.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP- og IGES-filer åpnes av FormCADs kjerne-worker, et eget program som FormShot laster ned én gang, kontrollerer fil for fil og beholder i hurtigbuffermappen din. Andre modellformater trenger det ikke.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP- og IGES-filer krever CAD-workeren, og ingen er publisert for denne datamaskinen.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP- og IGES-filer krever CAD-workeren, som ikke er installert ennå.", + "Selected CAD parts": "Valgte CAD-deler", + "Source": "Kilde", + "The CAD worker is installed.": "CAD-workeren er installert.", + "The CAD worker is installed. You can import this file now.": "CAD-workeren er installert. Du kan importere denne filen nå.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "CAD-workeren som åpner STEP- og IGES-filer, og standard CAD-kvalitet.", + "The FormShot service is not reachable.": "FormShot-tjenesten er ikke tilgjengelig.", + "The download failed: {reason}": "Nedlastingen mislyktes: {reason}", + "The download was cancelled. Nothing was installed.": "Nedlastingen ble avbrutt. Ingenting ble installert.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Motoren gir ikke noe anslag; finere kvaliteter tar lengre tid og gir flere trekanter.", + "The parts could not be read: {reason}": "Delene kunne ikke leses: {reason}", + "The service cannot stop a download once it has started.": "Tjenesten kan ikke stoppe en nedlasting når den først har startet.", + "The service refused the request from this window.": "Tjenesten avviste forespørselen fra dette vinduet.", + "The status could not be read: {reason}": "Statusen kunne ikke leses: {reason}", + "The worker did not answer: {reason}": "Workeren svarte ikke: {reason}", + "This computer": "Denne datamaskinen", + "This engine cannot re-tessellate CAD parts.": "Denne motoren kan ikke tesselere CAD-deler på nytt.", + "Triangles now": "Trekanter nå", + "Try Again": "Prøv igjen", + "Unknown": "Ukjent", + "Unpacking": "Pakker ut", + "Version": "Versjon", + "degrees": "grader", + "no reason was given": "ingen årsak ble oppgitt", + "{done} of {total}": "{done} av {total}", + "{n} files": "{n} filer", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokoll {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} utpakket, kontrollert fil for fil", + "{tag}: none for this computer": "{tag}: ingen for denne datamaskinen", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} filer, {size} utpakket" +} diff --git a/frontend/src/i18n/modules/cad/nl.json b/frontend/src/i18n/modules/cad/nl.json new file mode 100644 index 00000000..2d47ad15 --- /dev/null +++ b/frontend/src/i18n/modules/cad/nl.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% van de modelgrootte", + "About {n} triangles afterwards.": "Daarna ongeveer {n} driehoeken.", + "All CAD parts": "Alle CAD-onderdelen", + "Angle": "Hoek", + "Angle in degrees": "Hoek in graden", + "Apply": "Toepassen", + "Beside the FormShot engine": "Naast de FormShot-engine", + "CAD Import": "CAD-import", + "CAD Import Settings...": "CAD-importinstellingen...", + "CAD Options in the Import Sheet": "CAD-opties in het importvenster", + "CAD worker": "CAD-worker", + "CAD worker: {stage}, {pct}%": "CAD-worker: {stage}, {pct}%", + "Check the worker": "Worker controleren", + "Checking every file": "Elk bestand controleren", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Kies STEP- of IGES-bestanden om te importeren; ze worden geopend via de CAD-worker.", + "Chord": "Koorde", + "Chord as a percentage of the model size": "Koorde als percentage van de modelgrootte", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "De koorde moet groter zijn dan 0 en hoogstens {max}% van de modelgrootte; de hoek ligt tussen {min} en {amax} graden.", + "Chord {chord}% of the model size, angle {angle} degrees": "Koorde {chord}% van de modelgrootte, hoek {angle} graden", + "Could not re-tessellate: {reason}": "Opnieuw tesselleren is mislukt: {reason}", + "Custom": "Aangepast", + "Custom ({chord}%, {angle}°)": "Aangepast ({chord}%, {angle}°)", + "Default CAD quality": "Standaard CAD-kwaliteit", + "Download": "Downloaden", + "Download and check the program that opens STEP and IGES files.": "Download en controleer het programma dat STEP- en IGES-bestanden opent.", + "Download the CAD Worker": "CAD-worker downloaden", + "Download the CAD worker": "CAD-worker downloaden", + "Downloaded into the cache folder": "Gedownload naar de cachemap", + "Downloading": "Downloaden", + "Found in": "Gevonden in", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Hoe fijn STEP- en IGES-oppervlakken bij het importeren in driehoeken worden omgezet. De koorde is de grootste afstand tussen een driehoek en het echte oppervlak, als deel van de grootte van het hele model; de hoek is de grootste knik tussen naburige driehoeken. Fijnere instellingen duren langer en geven grotere bestanden. Het importvenster begint met deze keuze; daar kun je haar voor één import wijzigen.", + "Installed": "Geïnstalleerd", + "Mixed": "Gemengd", + "Named by FORMSHOT_CAD_WORKER": "Opgegeven door FORMSHOT_CAD_WORKER", + "New quality": "Nieuwe kwaliteit", + "None of the selected parts came from a STEP or IGES file.": "Geen van de geselecteerde onderdelen komt uit een STEP- of IGES-bestand.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Geen van de geselecteerde onderdelen komt uit een STEP- of IGES-bestand. Hef de selectie op om alle CAD-onderdelen opnieuw op te bouwen.", + "Not available.": "Niet beschikbaar.", + "Not available: {reason}": "Niet beschikbaar: {reason}", + "Not installed": "Niet geïnstalleerd", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Nog niet geïnstalleerd. FormShot zoekt ernaar in {folder}; download het hier om STEP- en IGES-bestanden te openen.", + "Not named": "Niet opgegeven", + "Not recorded": "Niet vastgelegd", + "Nothing in this document came from a STEP or IGES file.": "Niets in dit document komt uit een STEP- of IGES-bestand.", + "Nothing is selected, so every CAD part is rebuilt.": "Er is niets geselecteerd, dus alle CAD-onderdelen worden opnieuw opgebouwd.", + "Published": "Gepubliceerd", + "Quality now": "Huidige kwaliteit", + "Re-tessellate CAD Parts": "CAD-onderdelen opnieuw tesselleren", + "Re-tessellate CAD Parts...": "CAD-onderdelen opnieuw tesselleren...", + "Re-tessellated 1 CAD part at {quality}.": "1 CAD-onderdeel opnieuw getesselleerd met {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 CAD-onderdeel opnieuw getesselleerd met {quality}: van {before} naar {after} driehoeken.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} CAD-onderdelen opnieuw getesselleerd met {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} CAD-onderdelen opnieuw getesselleerd met {quality}: van {before} naar {after} driehoeken.", + "Re-tessellating": "Opnieuw tesselleren", + "Read the status again": "Status opnieuw lezen", + "Reading the published record": "Het gepubliceerde record lezen", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Bouwt de meshes van onderdelen uit STEP of IGES opnieuw op met een andere kwaliteit, als één ongedaanmakingsstap.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP- en IGES-bestanden worden geopend door de kernel-worker van FormCAD, een apart programma dat FormShot eenmalig downloadt, bestand voor bestand controleert en in je cachemap bewaart. Andere modelindelingen hebben het niet nodig.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP- en IGES-bestanden hebben de CAD-worker nodig, en er is er geen gepubliceerd voor deze computer.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP- en IGES-bestanden hebben de CAD-worker nodig, die nog niet is geïnstalleerd.", + "Selected CAD parts": "Geselecteerde CAD-onderdelen", + "Source": "Bron", + "The CAD worker is installed.": "De CAD-worker is geïnstalleerd.", + "The CAD worker is installed. You can import this file now.": "De CAD-worker is geïnstalleerd. Je kunt dit bestand nu importeren.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "De CAD-worker die STEP- en IGES-bestanden opent, en de standaard CAD-kwaliteit.", + "The FormShot service is not reachable.": "De FormShot-service is niet bereikbaar.", + "The download failed: {reason}": "Het downloaden is mislukt: {reason}", + "The download was cancelled. Nothing was installed.": "Het downloaden is geannuleerd. Er is niets geïnstalleerd.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "De engine geeft geen schatting; fijnere kwaliteiten duren langer en geven meer driehoeken.", + "The parts could not be read: {reason}": "De onderdelen konden niet worden gelezen: {reason}", + "The service cannot stop a download once it has started.": "De service kan een download niet stoppen zodra die is gestart.", + "The service refused the request from this window.": "De service heeft het verzoek van dit venster geweigerd.", + "The status could not be read: {reason}": "De status kon niet worden gelezen: {reason}", + "The worker did not answer: {reason}": "De worker gaf geen antwoord: {reason}", + "This computer": "Deze computer", + "This engine cannot re-tessellate CAD parts.": "Deze engine kan CAD-onderdelen niet opnieuw tesselleren.", + "Triangles now": "Huidige driehoeken", + "Try Again": "Opnieuw proberen", + "Unknown": "Onbekend", + "Unpacking": "Uitpakken", + "Version": "Versie", + "degrees": "graden", + "no reason was given": "er is geen reden opgegeven", + "{done} of {total}": "{done} van {total}", + "{n} files": "{n} bestanden", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protocol {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} uitgepakt, bestand voor bestand gecontroleerd", + "{tag}: none for this computer": "{tag}: geen voor deze computer", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} bestanden, {size} uitgepakt" +} diff --git a/frontend/src/i18n/modules/cad/pl.json b/frontend/src/i18n/modules/cad/pl.json new file mode 100644 index 00000000..b3633a81 --- /dev/null +++ b/frontend/src/i18n/modules/cad/pl.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% rozmiaru modelu", + "About {n} triangles afterwards.": "Potem będzie około {n} trójkątów.", + "All CAD parts": "Wszystkie części CAD", + "Angle": "Kąt", + "Angle in degrees": "Kąt w stopniach", + "Apply": "Zastosuj", + "Beside the FormShot engine": "Obok silnika FormShot", + "CAD Import": "Import CAD", + "CAD Import Settings...": "Ustawienia importu CAD...", + "CAD Options in the Import Sheet": "Opcje CAD w oknie importu", + "CAD worker": "Proces roboczy CAD", + "CAD worker: {stage}, {pct}%": "Proces roboczy CAD: {stage}, {pct}%", + "Check the worker": "Sprawdź proces roboczy", + "Checking every file": "Sprawdzanie każdego pliku", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Wybierz pliki STEP lub IGES do zaimportowania; otwierane są przez proces roboczy CAD.", + "Chord": "Cięciwa", + "Chord as a percentage of the model size": "Cięciwa jako procent rozmiaru modelu", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Cięciwa musi być większa od 0 i wynosić najwyżej {max}% rozmiaru modelu; kąt od {min} do {amax} stopni.", + "Chord {chord}% of the model size, angle {angle} degrees": "Cięciwa {chord}% rozmiaru modelu, kąt {angle} stopni", + "Could not re-tessellate: {reason}": "Nie udało się ponownie wykonać teselacji: {reason}", + "Custom": "Własne", + "Custom ({chord}%, {angle}°)": "Własne ({chord}%, {angle}°)", + "Default CAD quality": "Domyślna jakość CAD", + "Download": "Pobierz", + "Download and check the program that opens STEP and IGES files.": "Pobierz i sprawdź program, który otwiera pliki STEP i IGES.", + "Download the CAD Worker": "Pobierz proces roboczy CAD", + "Download the CAD worker": "Pobierz proces roboczy CAD", + "Downloaded into the cache folder": "Pobrano do folderu pamięci podręcznej", + "Downloading": "Pobieranie", + "Found in": "Znaleziono w", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Jak drobno powierzchnie STEP i IGES zamieniają się w trójkąty podczas importu. Cięciwa to największa odległość między trójkątem a rzeczywistą powierzchnią, wyrażona jako część rozmiaru całego modelu; kąt to największe załamanie między sąsiednimi trójkątami. Dokładniejsze ustawienia trwają dłużej i dają większe pliki. Okno importu zaczyna od tego wyboru; możesz go tam zmienić dla pojedynczego importu.", + "Installed": "Zainstalowano", + "Mixed": "Mieszane", + "Named by FORMSHOT_CAD_WORKER": "Wskazany przez FORMSHOT_CAD_WORKER", + "New quality": "Nowa jakość", + "None of the selected parts came from a STEP or IGES file.": "Żadna z zaznaczonych części nie pochodzi z pliku STEP ani IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Żadna z zaznaczonych części nie pochodzi z pliku STEP ani IGES. Wyczyść zaznaczenie, aby odbudować wszystkie części CAD.", + "Not available.": "Niedostępne.", + "Not available: {reason}": "Niedostępne: {reason}", + "Not installed": "Niezainstalowano", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Jeszcze nie zainstalowano. FormShot szuka go w {folder}; pobierz go tutaj, aby otwierać pliki STEP i IGES.", + "Not named": "Nie wskazano", + "Not recorded": "Nie zapisano", + "Nothing in this document came from a STEP or IGES file.": "Nic w tym dokumencie nie pochodzi z pliku STEP ani IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "Nic nie jest zaznaczone, więc zostaną odbudowane wszystkie części CAD.", + "Published": "Opublikowane", + "Quality now": "Obecna jakość", + "Re-tessellate CAD Parts": "Wykonaj ponownie teselację części CAD", + "Re-tessellate CAD Parts...": "Wykonaj ponownie teselację części CAD...", + "Re-tessellated 1 CAD part at {quality}.": "Ponownie wykonano teselację 1 części CAD w jakości {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "Ponownie wykonano teselację 1 części CAD w jakości {quality}: z {before} do {after} trójkątów.", + "Re-tessellated {parts} CAD parts at {quality}.": "Ponownie wykonano teselację części CAD ({parts}) w jakości {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "Ponownie wykonano teselację części CAD ({parts}) w jakości {quality}: z {before} do {after} trójkątów.", + "Re-tessellating": "Ponowna teselacja", + "Read the status again": "Odczytaj stan ponownie", + "Reading the published record": "Odczytywanie opublikowanego rekordu", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Odbuduj siatki części zaimportowanych z STEP lub IGES w innej jakości, jako jeden krok cofania.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "Pliki STEP i IGES otwiera proces roboczy jądra FormCAD, osobny program, który FormShot pobiera jednorazowo, sprawdza plik po pliku i przechowuje w Twoim folderze pamięci podręcznej. Inne formaty modeli go nie potrzebują.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "Pliki STEP i IGES wymagają procesu roboczego CAD, a dla tego komputera żaden nie został opublikowany.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "Pliki STEP i IGES wymagają procesu roboczego CAD, który nie jest jeszcze zainstalowany.", + "Selected CAD parts": "Zaznaczone części CAD", + "Source": "Źródło", + "The CAD worker is installed.": "Proces roboczy CAD jest zainstalowany.", + "The CAD worker is installed. You can import this file now.": "Proces roboczy CAD jest zainstalowany. Możesz teraz zaimportować ten plik.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Proces roboczy CAD, który otwiera pliki STEP i IGES, oraz domyślna jakość CAD.", + "The FormShot service is not reachable.": "Usługa FormShot jest nieosiągalna.", + "The download failed: {reason}": "Pobieranie nie powiodło się: {reason}", + "The download was cancelled. Nothing was installed.": "Pobieranie zostało anulowane. Nic nie zainstalowano.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Silnik nie podaje oszacowania; dokładniejsze jakości trwają dłużej i dają więcej trójkątów.", + "The parts could not be read: {reason}": "Nie udało się odczytać części: {reason}", + "The service cannot stop a download once it has started.": "Usługa nie może zatrzymać pobierania po jego rozpoczęciu.", + "The service refused the request from this window.": "Usługa odrzuciła żądanie z tego okna.", + "The status could not be read: {reason}": "Nie udało się odczytać stanu: {reason}", + "The worker did not answer: {reason}": "Proces roboczy nie odpowiedział: {reason}", + "This computer": "Ten komputer", + "This engine cannot re-tessellate CAD parts.": "Ten silnik nie potrafi ponownie wykonać teselacji części CAD.", + "Triangles now": "Obecnie trójkątów", + "Try Again": "Spróbuj ponownie", + "Unknown": "Nieznane", + "Unpacking": "Rozpakowywanie", + "Version": "Wersja", + "degrees": "stopni", + "no reason was given": "nie podano przyczyny", + "{done} of {total}": "{done} z {total}", + "{n} files": "Pliki: {n}", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokół {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} po rozpakowaniu, sprawdzono plik po pliku", + "{tag}: none for this computer": "{tag}: brak dla tego komputera", + "{tag}: {files} files, {size} unpacked": "{tag}: pliki: {files}, {size} po rozpakowaniu" +} diff --git a/frontend/src/i18n/modules/cad/pt-BR.json b/frontend/src/i18n/modules/cad/pt-BR.json new file mode 100644 index 00000000..616fc419 --- /dev/null +++ b/frontend/src/i18n/modules/cad/pt-BR.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% do tamanho do modelo", + "About {n} triangles afterwards.": "Cerca de {n} triângulos depois.", + "All CAD parts": "Todas as peças CAD", + "Angle": "Ângulo", + "Angle in degrees": "Ângulo em graus", + "Apply": "Aplicar", + "Beside the FormShot engine": "Ao lado do motor do FormShot", + "CAD Import": "Importação CAD", + "CAD Import Settings...": "Configurações de importação CAD...", + "CAD Options in the Import Sheet": "Opções CAD na folha de importação", + "CAD worker": "Worker CAD", + "CAD worker: {stage}, {pct}%": "Worker CAD: {stage}, {pct}%", + "Check the worker": "Verificar o worker", + "Checking every file": "Verificando cada arquivo", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Escolha arquivos STEP ou IGES para importar; eles são abertos pelo worker CAD.", + "Chord": "Corda", + "Chord as a percentage of the model size": "Corda como porcentagem do tamanho do modelo", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "A corda deve ser maior que 0 e no máximo {max}% do tamanho do modelo; o ângulo, de {min} a {amax} graus.", + "Chord {chord}% of the model size, angle {angle} degrees": "Corda de {chord}% do tamanho do modelo, ângulo de {angle} graus", + "Could not re-tessellate: {reason}": "Não foi possível retesselar: {reason}", + "Custom": "Personalizado", + "Custom ({chord}%, {angle}°)": "Personalizado ({chord}%, {angle}°)", + "Default CAD quality": "Qualidade CAD padrão", + "Download": "Baixar", + "Download and check the program that opens STEP and IGES files.": "Baixe e verifique o programa que abre arquivos STEP e IGES.", + "Download the CAD Worker": "Baixar o worker CAD", + "Download the CAD worker": "Baixar o worker CAD", + "Downloaded into the cache folder": "Baixado para a pasta de cache", + "Downloading": "Baixando", + "Found in": "Encontrado em", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Define quão finamente as superfícies STEP e IGES viram triângulos ao serem importadas. Corda é a maior folga entre um triângulo e a superfície real, como fração do tamanho de todo o modelo; ângulo é a maior curvatura entre triângulos vizinhos. Configurações mais finas demoram mais e geram arquivos maiores. A folha de importação começa com esta escolha; lá você pode alterá-la para uma única importação.", + "Installed": "Instalado", + "Mixed": "Misto", + "Named by FORMSHOT_CAD_WORKER": "Definido por FORMSHOT_CAD_WORKER", + "New quality": "Nova qualidade", + "None of the selected parts came from a STEP or IGES file.": "Nenhuma das peças selecionadas veio de um arquivo STEP ou IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Nenhuma das peças selecionadas veio de um arquivo STEP ou IGES. Limpe a seleção para reconstruir todas as peças CAD.", + "Not available.": "Indisponível.", + "Not available: {reason}": "Indisponível: {reason}", + "Not installed": "Não instalado", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Ainda não instalado. O FormShot o procura em {folder}; baixe-o aqui para abrir arquivos STEP e IGES.", + "Not named": "Não informado", + "Not recorded": "Não registrado", + "Nothing in this document came from a STEP or IGES file.": "Nada neste documento veio de um arquivo STEP ou IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "Nada está selecionado, então todas as peças CAD serão reconstruídas.", + "Published": "Publicado", + "Quality now": "Qualidade atual", + "Re-tessellate CAD Parts": "Retesselar peças CAD", + "Re-tessellate CAD Parts...": "Retesselar peças CAD...", + "Re-tessellated 1 CAD part at {quality}.": "1 peça CAD retesselada em {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 peça CAD retesselada em {quality}: de {before} para {after} triângulos.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} peças CAD retesseladas em {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} peças CAD retesseladas em {quality}: de {before} para {after} triângulos.", + "Re-tessellating": "Retesselando", + "Read the status again": "Ler o status novamente", + "Reading the published record": "Lendo o registro publicado", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Reconstrua as malhas das peças importadas de STEP ou IGES em outra qualidade, como uma única etapa de desfazer.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "Arquivos STEP e IGES são abertos pelo worker de kernel do FormCAD, um programa separado que o FormShot baixa uma vez, verifica arquivo por arquivo e guarda na sua pasta de cache. Outros formatos de modelo não precisam dele.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "Arquivos STEP e IGES precisam do worker CAD, e nenhum está publicado para este computador.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "Arquivos STEP e IGES precisam do worker CAD, que ainda não está instalado.", + "Selected CAD parts": "Peças CAD selecionadas", + "Source": "Origem", + "The CAD worker is installed.": "O worker CAD está instalado.", + "The CAD worker is installed. You can import this file now.": "O worker CAD está instalado. Você já pode importar este arquivo.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "O worker CAD que abre arquivos STEP e IGES e a qualidade CAD padrão.", + "The FormShot service is not reachable.": "O serviço do FormShot não está acessível.", + "The download failed: {reason}": "O download falhou: {reason}", + "The download was cancelled. Nothing was installed.": "O download foi cancelado. Nada foi instalado.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "O motor não dá estimativa; qualidades mais finas demoram mais e geram mais triângulos.", + "The parts could not be read: {reason}": "Não foi possível ler as peças: {reason}", + "The service cannot stop a download once it has started.": "O serviço não pode interromper um download depois de iniciado.", + "The service refused the request from this window.": "O serviço recusou a solicitação desta janela.", + "The status could not be read: {reason}": "Não foi possível ler o status: {reason}", + "The worker did not answer: {reason}": "O worker não respondeu: {reason}", + "This computer": "Este computador", + "This engine cannot re-tessellate CAD parts.": "Este motor não consegue retesselar peças CAD.", + "Triangles now": "Triângulos agora", + "Try Again": "Tentar novamente", + "Unknown": "Desconhecido", + "Unpacking": "Descompactando", + "Version": "Versão", + "degrees": "graus", + "no reason was given": "nenhum motivo foi informado", + "{done} of {total}": "{done} de {total}", + "{n} files": "{n} arquivos", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protocolo {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} descompactados, verificados arquivo por arquivo", + "{tag}: none for this computer": "{tag}: nenhum para este computador", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} arquivos, {size} descompactados" +} diff --git a/frontend/src/i18n/modules/cad/ru.json b/frontend/src/i18n/modules/cad/ru.json new file mode 100644 index 00000000..4fe19fac --- /dev/null +++ b/frontend/src/i18n/modules/cad/ru.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% от размера модели", + "About {n} triangles afterwards.": "Примерно {n} треугольников после этого.", + "All CAD parts": "Все CAD-детали", + "Angle": "Угол", + "Angle in degrees": "Угол в градусах", + "Apply": "Применить", + "Beside the FormShot engine": "Рядом с движком FormShot", + "CAD Import": "Импорт CAD", + "CAD Import Settings...": "Настройки импорта CAD...", + "CAD Options in the Import Sheet": "Параметры CAD в окне импорта", + "CAD worker": "Рабочий процесс CAD", + "CAD worker: {stage}, {pct}%": "Рабочий процесс CAD: {stage}, {pct}%", + "Check the worker": "Проверить рабочий процесс", + "Checking every file": "Проверка каждого файла", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Выберите файлы STEP или IGES для импорта; они открываются через рабочий процесс CAD.", + "Chord": "Хорда", + "Chord as a percentage of the model size": "Хорда в процентах от размера модели", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Хорда должна быть больше 0 и не более {max}% от размера модели; угол от {min} до {amax} градусов.", + "Chord {chord}% of the model size, angle {angle} degrees": "Хорда {chord}% от размера модели, угол {angle} градусов", + "Could not re-tessellate: {reason}": "Не удалось выполнить повторную тесселяцию: {reason}", + "Custom": "Своё", + "Custom ({chord}%, {angle}°)": "Своё ({chord}%, {angle}°)", + "Default CAD quality": "Качество CAD по умолчанию", + "Download": "Скачать", + "Download and check the program that opens STEP and IGES files.": "Скачайте и проверьте программу, открывающую файлы STEP и IGES.", + "Download the CAD Worker": "Скачать рабочий процесс CAD", + "Download the CAD worker": "Скачать рабочий процесс CAD", + "Downloaded into the cache folder": "Скачано в папку кэша", + "Downloading": "Скачивание", + "Found in": "Найдено в", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Насколько мелко поверхности STEP и IGES превращаются в треугольники при импорте. Хорда: наибольший зазор между треугольником и настоящей поверхностью в долях размера всей модели; угол: наибольший изгиб между соседними треугольниками. Более мелкие настройки работают дольше и дают файлы больше. Окно импорта начинается с этого выбора; для одного импорта его можно изменить там.", + "Installed": "Установлено", + "Mixed": "Смешанное", + "Named by FORMSHOT_CAD_WORKER": "Задано через FORMSHOT_CAD_WORKER", + "New quality": "Новое качество", + "None of the selected parts came from a STEP or IGES file.": "Ни одна из выбранных деталей не получена из файла STEP или IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Ни одна из выбранных деталей не получена из файла STEP или IGES. Снимите выделение, чтобы перестроить все CAD-детали.", + "Not available.": "Недоступно.", + "Not available: {reason}": "Недоступно: {reason}", + "Not installed": "Не установлено", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Пока не установлено. FormShot ищет его в {folder}; скачайте его здесь, чтобы открывать файлы STEP и IGES.", + "Not named": "Не задано", + "Not recorded": "Не записано", + "Nothing in this document came from a STEP or IGES file.": "В этом документе нет ничего из файлов STEP или IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "Ничего не выбрано, поэтому будут перестроены все CAD-детали.", + "Published": "Опубликовано", + "Quality now": "Текущее качество", + "Re-tessellate CAD Parts": "Повторная тесселяция CAD-деталей", + "Re-tessellate CAD Parts...": "Повторная тесселяция CAD-деталей...", + "Re-tessellated 1 CAD part at {quality}.": "Повторная тесселяция 1 CAD-детали с качеством {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "Повторная тесселяция 1 CAD-детали с качеством {quality}: треугольников было {before}, стало {after}.", + "Re-tessellated {parts} CAD parts at {quality}.": "Повторная тесселяция CAD-деталей: {parts}, качество {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "Повторная тесселяция CAD-деталей: {parts}, качество {quality}: треугольников было {before}, стало {after}.", + "Re-tessellating": "Повторная тесселяция", + "Read the status again": "Прочитать состояние заново", + "Reading the published record": "Чтение опубликованной записи", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Перестройте меши деталей, импортированных из STEP или IGES, с другим качеством, одним шагом отмены.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "Файлы STEP и IGES открывает рабочий процесс ядра FormCAD, отдельная программа, которую FormShot скачивает один раз, проверяет файл за файлом и хранит в папке кэша. Другие форматы моделей в ней не нуждаются.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "Для файлов STEP и IGES нужен рабочий процесс CAD, но для этого компьютера он не опубликован.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "Для файлов STEP и IGES нужен рабочий процесс CAD, который ещё не установлен.", + "Selected CAD parts": "Выбранные CAD-детали", + "Source": "Источник", + "The CAD worker is installed.": "Рабочий процесс CAD установлен.", + "The CAD worker is installed. You can import this file now.": "Рабочий процесс CAD установлен. Теперь можно импортировать этот файл.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Рабочий процесс CAD, открывающий файлы STEP и IGES, и качество CAD по умолчанию.", + "The FormShot service is not reachable.": "Служба FormShot недоступна.", + "The download failed: {reason}": "Не удалось скачать: {reason}", + "The download was cancelled. Nothing was installed.": "Скачивание отменено. Ничего не установлено.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Движок не даёт оценки; более высокое качество занимает больше времени и даёт больше треугольников.", + "The parts could not be read: {reason}": "Не удалось прочитать детали: {reason}", + "The service cannot stop a download once it has started.": "Служба не может остановить скачивание после его начала.", + "The service refused the request from this window.": "Служба отклонила запрос из этого окна.", + "The status could not be read: {reason}": "Не удалось прочитать состояние: {reason}", + "The worker did not answer: {reason}": "Рабочий процесс не ответил: {reason}", + "This computer": "Этот компьютер", + "This engine cannot re-tessellate CAD parts.": "Этот движок не умеет повторно выполнять тесселяцию CAD-деталей.", + "Triangles now": "Сейчас треугольников", + "Try Again": "Повторить", + "Unknown": "Неизвестно", + "Unpacking": "Распаковка", + "Version": "Версия", + "degrees": "градусов", + "no reason was given": "причина не указана", + "{done} of {total}": "{done} из {total}", + "{n} files": "Файлов: {n}", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, протокол {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, распаковано {size}, проверено файл за файлом", + "{tag}: none for this computer": "{tag}: для этого компьютера нет", + "{tag}: {files} files, {size} unpacked": "{tag}: файлов {files}, распаковано {size}" +} diff --git a/frontend/src/i18n/modules/cad/strings.json b/frontend/src/i18n/modules/cad/strings.json new file mode 100644 index 00000000..a3f50ed0 --- /dev/null +++ b/frontend/src/i18n/modules/cad/strings.json @@ -0,0 +1,91 @@ +[ + "% of the model size", + "About {n} triangles afterwards.", + "All CAD parts", + "Angle", + "Angle in degrees", + "Apply", + "Beside the FormShot engine", + "CAD Import", + "CAD Import Settings...", + "CAD Options in the Import Sheet", + "CAD worker", + "CAD worker: {stage}, {pct}%", + "Check the worker", + "Checking every file", + "Choose STEP or IGES files to import; they open through the CAD worker.", + "Chord", + "Chord as a percentage of the model size", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.", + "Chord {chord}% of the model size, angle {angle} degrees", + "Could not re-tessellate: {reason}", + "Custom", + "Custom ({chord}%, {angle}°)", + "Default CAD quality", + "Download", + "Download and check the program that opens STEP and IGES files.", + "Download the CAD Worker", + "Download the CAD worker", + "Downloaded into the cache folder", + "Downloading", + "Found in", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.", + "Installed", + "Mixed", + "Named by FORMSHOT_CAD_WORKER", + "New quality", + "None of the selected parts came from a STEP or IGES file.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.", + "Not available.", + "Not available: {reason}", + "Not installed", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.", + "Not named", + "Not recorded", + "Nothing in this document came from a STEP or IGES file.", + "Nothing is selected, so every CAD part is rebuilt.", + "Published", + "Quality now", + "Re-tessellate CAD Parts", + "Re-tessellate CAD Parts...", + "Re-tessellated 1 CAD part at {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.", + "Re-tessellated {parts} CAD parts at {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.", + "Re-tessellating", + "Read the status again", + "Reading the published record", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.", + "STEP and IGES files need the CAD worker, and none is published for this computer.", + "STEP and IGES files need the CAD worker, which is not installed yet.", + "Selected CAD parts", + "Source", + "The CAD worker is installed.", + "The CAD worker is installed. You can import this file now.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.", + "The FormShot service is not reachable.", + "The download failed: {reason}", + "The download was cancelled. Nothing was installed.", + "The engine gives no estimate; finer qualities take longer and make more triangles.", + "The parts could not be read: {reason}", + "The service cannot stop a download once it has started.", + "The service refused the request from this window.", + "The status could not be read: {reason}", + "The worker did not answer: {reason}", + "This computer", + "This engine cannot re-tessellate CAD parts.", + "Triangles now", + "Try Again", + "Unknown", + "Unpacking", + "Version", + "degrees", + "no reason was given", + "{done} of {total}", + "{n} files", + "{tag}, OpenCascade {occt}, protocol {protocol}", + "{tag}, {size} unpacked, checked file by file", + "{tag}: none for this computer", + "{tag}: {files} files, {size} unpacked" +] diff --git a/frontend/src/i18n/modules/cad/sv.json b/frontend/src/i18n/modules/cad/sv.json new file mode 100644 index 00000000..925367ea --- /dev/null +++ b/frontend/src/i18n/modules/cad/sv.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% av modellens storlek", + "About {n} triangles afterwards.": "Ungefär {n} trianglar efteråt.", + "All CAD parts": "Alla CAD-delar", + "Angle": "Vinkel", + "Angle in degrees": "Vinkel i grader", + "Apply": "Använd", + "Beside the FormShot engine": "Bredvid FormShot-motorn", + "CAD Import": "CAD-import", + "CAD Import Settings...": "CAD-importinställningar...", + "CAD Options in the Import Sheet": "CAD-alternativ i importrutan", + "CAD worker": "CAD-worker", + "CAD worker: {stage}, {pct}%": "CAD-worker: {stage}, {pct}%", + "Check the worker": "Kontrollera workern", + "Checking every file": "Kontrollerar varje fil", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Välj STEP- eller IGES-filer att importera; de öppnas via CAD-workern.", + "Chord": "Korda", + "Chord as a percentage of the model size": "Korda som procent av modellens storlek", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Kordan måste vara över 0 och högst {max}% av modellens storlek; vinkeln från {min} till {amax} grader.", + "Chord {chord}% of the model size, angle {angle} degrees": "Korda {chord}% av modellens storlek, vinkel {angle} grader", + "Could not re-tessellate: {reason}": "Det gick inte att tessellera om: {reason}", + "Custom": "Anpassad", + "Custom ({chord}%, {angle}°)": "Anpassad ({chord}%, {angle}°)", + "Default CAD quality": "Standard-CAD-kvalitet", + "Download": "Ladda ned", + "Download and check the program that opens STEP and IGES files.": "Ladda ned och kontrollera programmet som öppnar STEP- och IGES-filer.", + "Download the CAD Worker": "Ladda ned CAD-workern", + "Download the CAD worker": "Ladda ned CAD-workern", + "Downloaded into the cache folder": "Nedladdad till cachemappen", + "Downloading": "Laddar ned", + "Found in": "Hittades i", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Hur fint STEP- och IGES-ytor delas upp i trianglar vid import. Kordan är det största avståndet mellan en triangel och den verkliga ytan, som andel av hela modellens storlek; vinkeln är den största knäcken mellan angränsande trianglar. Finare inställningar tar längre tid och ger större filer. Importrutan börjar med det här valet; där kan du ändra det för en enskild import.", + "Installed": "Installerad", + "Mixed": "Blandad", + "Named by FORMSHOT_CAD_WORKER": "Angiven av FORMSHOT_CAD_WORKER", + "New quality": "Ny kvalitet", + "None of the selected parts came from a STEP or IGES file.": "Ingen av de markerade delarna kom från en STEP- eller IGES-fil.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Ingen av de markerade delarna kom från en STEP- eller IGES-fil. Avmarkera allt för att bygga om alla CAD-delar.", + "Not available.": "Inte tillgängligt.", + "Not available: {reason}": "Inte tillgängligt: {reason}", + "Not installed": "Inte installerad", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Inte installerad ännu. FormShot letar efter den i {folder}; ladda ned den här för att öppna STEP- och IGES-filer.", + "Not named": "Inte angiven", + "Not recorded": "Inte registrerad", + "Nothing in this document came from a STEP or IGES file.": "Inget i det här dokumentet kom från en STEP- eller IGES-fil.", + "Nothing is selected, so every CAD part is rebuilt.": "Inget är markerat, så alla CAD-delar byggs om.", + "Published": "Publicerad", + "Quality now": "Kvalitet nu", + "Re-tessellate CAD Parts": "Tessellera om CAD-delar", + "Re-tessellate CAD Parts...": "Tessellera om CAD-delar...", + "Re-tessellated 1 CAD part at {quality}.": "1 CAD-del omtesselerad med {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 CAD-del omtesselerad med {quality}: {before} till {after} trianglar.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} CAD-delar omtesselerade med {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} CAD-delar omtesselerade med {quality}: {before} till {after} trianglar.", + "Re-tessellating": "Tesselerar om", + "Read the status again": "Läs statusen igen", + "Reading the published record": "Läser den publicerade posten", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Bygger om meshar för delar importerade från STEP eller IGES med en annan kvalitet, som ett enda ångrasteg.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP- och IGES-filer öppnas av FormCADs kärn-worker, ett separat program som FormShot laddar ned en gång, kontrollerar fil för fil och behåller i din cachemapp. Andra modellformat behöver det inte.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP- och IGES-filer kräver CAD-workern, och ingen är publicerad för den här datorn.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP- och IGES-filer kräver CAD-workern, som inte är installerad ännu.", + "Selected CAD parts": "Markerade CAD-delar", + "Source": "Källa", + "The CAD worker is installed.": "CAD-workern är installerad.", + "The CAD worker is installed. You can import this file now.": "CAD-workern är installerad. Du kan importera den här filen nu.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "CAD-workern som öppnar STEP- och IGES-filer, och standardkvaliteten för CAD.", + "The FormShot service is not reachable.": "FormShot-tjänsten går inte att nå.", + "The download failed: {reason}": "Nedladdningen misslyckades: {reason}", + "The download was cancelled. Nothing was installed.": "Nedladdningen avbröts. Inget installerades.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Motorn ger ingen uppskattning; finare kvaliteter tar längre tid och ger fler trianglar.", + "The parts could not be read: {reason}": "Delarna kunde inte läsas: {reason}", + "The service cannot stop a download once it has started.": "Tjänsten kan inte stoppa en nedladdning när den har startat.", + "The service refused the request from this window.": "Tjänsten avvisade begäran från det här fönstret.", + "The status could not be read: {reason}": "Statusen kunde inte läsas: {reason}", + "The worker did not answer: {reason}": "Workern svarade inte: {reason}", + "This computer": "Den här datorn", + "This engine cannot re-tessellate CAD parts.": "Den här motorn kan inte tessellera om CAD-delar.", + "Triangles now": "Trianglar nu", + "Try Again": "Försök igen", + "Unknown": "Okänd", + "Unpacking": "Packar upp", + "Version": "Version", + "degrees": "grader", + "no reason was given": "ingen orsak angavs", + "{done} of {total}": "{done} av {total}", + "{n} files": "{n} filer", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokoll {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, {size} uppackad, kontrollerad fil för fil", + "{tag}: none for this computer": "{tag}: ingen för den här datorn", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} filer, {size} uppackad" +} diff --git a/frontend/src/i18n/modules/cad/th.json b/frontend/src/i18n/modules/cad/th.json new file mode 100644 index 00000000..4403fe92 --- /dev/null +++ b/frontend/src/i18n/modules/cad/th.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% ของขนาดโมเดล", + "About {n} triangles afterwards.": "หลังจากนี้ประมาณ {n} สามเหลี่ยม", + "All CAD parts": "ชิ้นส่วน CAD ทั้งหมด", + "Angle": "มุม", + "Angle in degrees": "มุมเป็นองศา", + "Apply": "นำไปใช้", + "Beside the FormShot engine": "อยู่ข้างเอนจิน FormShot", + "CAD Import": "นำเข้า CAD", + "CAD Import Settings...": "การตั้งค่านำเข้า CAD...", + "CAD Options in the Import Sheet": "ตัวเลือก CAD ในหน้านำเข้า", + "CAD worker": "เวิร์กเกอร์ CAD", + "CAD worker: {stage}, {pct}%": "เวิร์กเกอร์ CAD: {stage}, {pct}%", + "Check the worker": "ตรวจสอบเวิร์กเกอร์", + "Checking every file": "กำลังตรวจสอบทุกไฟล์", + "Choose STEP or IGES files to import; they open through the CAD worker.": "เลือกไฟล์ STEP หรือ IGES เพื่อนำเข้า ไฟล์เหล่านี้เปิดผ่านเวิร์กเกอร์ CAD", + "Chord": "คอร์ด", + "Chord as a percentage of the model size": "คอร์ดเป็นเปอร์เซ็นต์ของขนาดโมเดล", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "คอร์ดต้องมากกว่า 0 และไม่เกิน {max}% ของขนาดโมเดล มุมตั้งแต่ {min} ถึง {amax} องศา", + "Chord {chord}% of the model size, angle {angle} degrees": "คอร์ด {chord}% ของขนาดโมเดล มุม {angle} องศา", + "Could not re-tessellate: {reason}": "ไม่สามารถแปลงเป็นสามเหลี่ยมใหม่: {reason}", + "Custom": "กำหนดเอง", + "Custom ({chord}%, {angle}°)": "กำหนดเอง ({chord}%, {angle}°)", + "Default CAD quality": "คุณภาพ CAD เริ่มต้น", + "Download": "ดาวน์โหลด", + "Download and check the program that opens STEP and IGES files.": "ดาวน์โหลดและตรวจสอบโปรแกรมที่เปิดไฟล์ STEP และ IGES", + "Download the CAD Worker": "ดาวน์โหลดเวิร์กเกอร์ CAD", + "Download the CAD worker": "ดาวน์โหลดเวิร์กเกอร์ CAD", + "Downloaded into the cache folder": "ดาวน์โหลดลงโฟลเดอร์แคชแล้ว", + "Downloading": "กำลังดาวน์โหลด", + "Found in": "พบใน", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "พื้นผิว STEP และ IGES ถูกแบ่งเป็นสามเหลี่ยมละเอียดเพียงใดเมื่อนำเข้า คอร์ดคือช่องว่างที่ใหญ่ที่สุดระหว่างสามเหลี่ยมกับพื้นผิวจริง คิดเป็นสัดส่วนของขนาดทั้งโมเดล มุมคือการหักงอที่มากที่สุดระหว่างสามเหลี่ยมที่อยู่ติดกัน ค่าที่ละเอียดกว่าใช้เวลานานกว่าและได้ไฟล์ใหญ่กว่า หน้านำเข้าจะเริ่มด้วยตัวเลือกนี้ และคุณเปลี่ยนสำหรับการนำเข้าครั้งเดียวได้ที่นั่น", + "Installed": "ติดตั้งแล้ว", + "Mixed": "ผสม", + "Named by FORMSHOT_CAD_WORKER": "ระบุโดย FORMSHOT_CAD_WORKER", + "New quality": "คุณภาพใหม่", + "None of the selected parts came from a STEP or IGES file.": "ชิ้นส่วนที่เลือกไม่มีชิ้นใดมาจากไฟล์ STEP หรือ IGES", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "ชิ้นส่วนที่เลือกไม่มีชิ้นใดมาจากไฟล์ STEP หรือ IGES ยกเลิกการเลือกเพื่อสร้างชิ้นส่วน CAD ทั้งหมดใหม่", + "Not available.": "ไม่พร้อมใช้งาน", + "Not available: {reason}": "ไม่พร้อมใช้งาน: {reason}", + "Not installed": "ยังไม่ได้ติดตั้ง", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "ยังไม่ได้ติดตั้ง FormShot จะค้นหาใน {folder} ดาวน์โหลดที่นี่เพื่อเปิดไฟล์ STEP และ IGES", + "Not named": "ไม่ได้ระบุชื่อ", + "Not recorded": "ไม่ได้บันทึกไว้", + "Nothing in this document came from a STEP or IGES file.": "ไม่มีสิ่งใดในเอกสารนี้ที่มาจากไฟล์ STEP หรือ IGES", + "Nothing is selected, so every CAD part is rebuilt.": "ไม่ได้เลือกอะไร จึงสร้างชิ้นส่วน CAD ทั้งหมดใหม่", + "Published": "เผยแพร่แล้ว", + "Quality now": "คุณภาพปัจจุบัน", + "Re-tessellate CAD Parts": "แปลงชิ้นส่วน CAD เป็นสามเหลี่ยมใหม่", + "Re-tessellate CAD Parts...": "แปลงชิ้นส่วน CAD เป็นสามเหลี่ยมใหม่...", + "Re-tessellated 1 CAD part at {quality}.": "แปลงชิ้นส่วน CAD 1 ชิ้นเป็นสามเหลี่ยมใหม่ที่ {quality} แล้ว", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "แปลงชิ้นส่วน CAD 1 ชิ้นเป็นสามเหลี่ยมใหม่ที่ {quality} แล้ว: {before} เป็น {after} สามเหลี่ยม", + "Re-tessellated {parts} CAD parts at {quality}.": "แปลงชิ้นส่วน CAD {parts} ชิ้นเป็นสามเหลี่ยมใหม่ที่ {quality} แล้ว", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "แปลงชิ้นส่วน CAD {parts} ชิ้นเป็นสามเหลี่ยมใหม่ที่ {quality} แล้ว: {before} เป็น {after} สามเหลี่ยม", + "Re-tessellating": "กำลังแปลงเป็นสามเหลี่ยมใหม่", + "Read the status again": "อ่านสถานะอีกครั้ง", + "Reading the published record": "กำลังอ่านระเบียนที่เผยแพร่", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "สร้างเมชของชิ้นส่วนที่นำเข้าจาก STEP หรือ IGES ใหม่ที่คุณภาพอื่น เป็นการเลิกทำขั้นตอนเดียว", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "ไฟล์ STEP และ IGES เปิดโดยเวิร์กเกอร์เคอร์เนลของ FormCAD ซึ่งเป็นโปรแกรมแยกที่ FormShot ดาวน์โหลดครั้งเดียว ตรวจสอบทีละไฟล์ และเก็บไว้ในโฟลเดอร์แคชของคุณ รูปแบบโมเดลอื่นไม่ต้องใช้", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "ไฟล์ STEP และ IGES ต้องใช้เวิร์กเกอร์ CAD แต่ยังไม่มีการเผยแพร่สำหรับคอมพิวเตอร์เครื่องนี้", + "STEP and IGES files need the CAD worker, which is not installed yet.": "ไฟล์ STEP และ IGES ต้องใช้เวิร์กเกอร์ CAD ซึ่งยังไม่ได้ติดตั้ง", + "Selected CAD parts": "ชิ้นส่วน CAD ที่เลือก", + "Source": "ต้นทาง", + "The CAD worker is installed.": "ติดตั้งเวิร์กเกอร์ CAD แล้ว", + "The CAD worker is installed. You can import this file now.": "ติดตั้งเวิร์กเกอร์ CAD แล้ว คุณนำเข้าไฟล์นี้ได้เลย", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "เวิร์กเกอร์ CAD ที่เปิดไฟล์ STEP และ IGES และคุณภาพ CAD เริ่มต้น", + "The FormShot service is not reachable.": "เข้าถึงบริการ FormShot ไม่ได้", + "The download failed: {reason}": "ดาวน์โหลดล้มเหลว: {reason}", + "The download was cancelled. Nothing was installed.": "ยกเลิกการดาวน์โหลดแล้ว ไม่ได้ติดตั้งอะไร", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "เอนจินไม่มีค่าประมาณ ค่าที่ละเอียดกว่าใช้เวลานานกว่าและได้สามเหลี่ยมมากกว่า", + "The parts could not be read: {reason}": "อ่านชิ้นส่วนไม่ได้: {reason}", + "The service cannot stop a download once it has started.": "บริการหยุดการดาวน์โหลดที่เริ่มแล้วไม่ได้", + "The service refused the request from this window.": "บริการปฏิเสธคำขอจากหน้าต่างนี้", + "The status could not be read: {reason}": "อ่านสถานะไม่ได้: {reason}", + "The worker did not answer: {reason}": "เวิร์กเกอร์ไม่ตอบสนอง: {reason}", + "This computer": "คอมพิวเตอร์เครื่องนี้", + "This engine cannot re-tessellate CAD parts.": "เอนจินนี้แปลงชิ้นส่วน CAD เป็นสามเหลี่ยมใหม่ไม่ได้", + "Triangles now": "สามเหลี่ยมปัจจุบัน", + "Try Again": "ลองอีกครั้ง", + "Unknown": "ไม่ทราบ", + "Unpacking": "กำลังแตกไฟล์", + "Version": "เวอร์ชัน", + "degrees": "องศา", + "no reason was given": "ไม่ได้ระบุเหตุผล", + "{done} of {total}": "{done} จาก {total}", + "{n} files": "{n} ไฟล์", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, โพรโทคอล {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, แตกไฟล์แล้ว {size}, ตรวจสอบทีละไฟล์", + "{tag}: none for this computer": "{tag}: ไม่มีสำหรับคอมพิวเตอร์เครื่องนี้", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} ไฟล์, แตกไฟล์แล้ว {size}" +} diff --git a/frontend/src/i18n/modules/cad/tr.json b/frontend/src/i18n/modules/cad/tr.json new file mode 100644 index 00000000..642bc80c --- /dev/null +++ b/frontend/src/i18n/modules/cad/tr.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "Model boyutunun %", + "About {n} triangles afterwards.": "Sonrasında yaklaşık {n} üçgen olur.", + "All CAD parts": "Tüm CAD parçaları", + "Angle": "Açı", + "Angle in degrees": "Derece cinsinden açı", + "Apply": "Uygula", + "Beside the FormShot engine": "FormShot motorunun yanında", + "CAD Import": "CAD İçe Aktarma", + "CAD Import Settings...": "CAD İçe Aktarma Ayarları...", + "CAD Options in the Import Sheet": "İçe Aktarma Sayfasındaki CAD Seçenekleri", + "CAD worker": "CAD çalışanı", + "CAD worker: {stage}, {pct}%": "CAD çalışanı: {stage}, %{pct}", + "Check the worker": "Çalışanı denetle", + "Checking every file": "Her dosya denetleniyor", + "Choose STEP or IGES files to import; they open through the CAD worker.": "İçe aktarmak için STEP veya IGES dosyalarını seçin; bunlar CAD çalışanı üzerinden açılır.", + "Chord": "Kiriş", + "Chord as a percentage of the model size": "Kirişin model boyutuna yüzdesi", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Kiriş 0'dan büyük ve model boyutunun en fazla %{max} kadarı olmalıdır; açı {min} ile {amax} derece arasında olmalıdır.", + "Chord {chord}% of the model size, angle {angle} degrees": "Kiriş model boyutunun %{chord} kadarı, açı {angle} derece", + "Could not re-tessellate: {reason}": "Yeniden üçgenlere bölme yapılamadı: {reason}", + "Custom": "Özel", + "Custom ({chord}%, {angle}°)": "Özel (%{chord}, {angle}°)", + "Default CAD quality": "Varsayılan CAD kalitesi", + "Download": "İndir", + "Download and check the program that opens STEP and IGES files.": "STEP ve IGES dosyalarını açan programı indirin ve denetleyin.", + "Download the CAD Worker": "CAD Çalışanını İndir", + "Download the CAD worker": "CAD çalışanını indir", + "Downloaded into the cache folder": "Önbellek klasörüne indirildi", + "Downloading": "İndiriliyor", + "Found in": "Bulunduğu yer", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "STEP ve IGES yüzeylerinin içe aktarılırken ne kadar ince üçgenlere dönüştürüleceği. Kiriş, bir üçgen ile gerçek yüzey arasındaki en büyük boşluktur ve tüm model boyutunun oranı olarak verilir; açı, komşu üçgenler arasındaki en büyük kırılmadır. İnce ayarlar daha uzun sürer ve daha büyük dosyalar üretir. İçe aktarma sayfası bu seçimle başlar; orada tek bir içe aktarma için değiştirebilirsiniz.", + "Installed": "Yüklü", + "Mixed": "Karışık", + "Named by FORMSHOT_CAD_WORKER": "FORMSHOT_CAD_WORKER ile belirtildi", + "New quality": "Yeni kalite", + "None of the selected parts came from a STEP or IGES file.": "Seçili parçaların hiçbiri bir STEP veya IGES dosyasından gelmedi.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Seçili parçaların hiçbiri bir STEP veya IGES dosyasından gelmedi. Tüm CAD parçalarını yeniden oluşturmak için seçimi kaldırın.", + "Not available.": "Kullanılamıyor.", + "Not available: {reason}": "Kullanılamıyor: {reason}", + "Not installed": "Yüklü değil", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Henüz yüklü değil. FormShot onu {folder} içinde arar; STEP ve IGES dosyalarını açmak için buradan indirin.", + "Not named": "Belirtilmedi", + "Not recorded": "Kaydedilmedi", + "Nothing in this document came from a STEP or IGES file.": "Bu belgedeki hiçbir şey bir STEP veya IGES dosyasından gelmedi.", + "Nothing is selected, so every CAD part is rebuilt.": "Hiçbir şey seçili değil, bu yüzden tüm CAD parçaları yeniden oluşturulur.", + "Published": "Yayımlandı", + "Quality now": "Şimdiki kalite", + "Re-tessellate CAD Parts": "CAD Parçalarını Yeniden Üçgenle", + "Re-tessellate CAD Parts...": "CAD Parçalarını Yeniden Üçgenle...", + "Re-tessellated 1 CAD part at {quality}.": "1 CAD parçası {quality} kalitesinde yeniden üçgenlendi.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "1 CAD parçası {quality} kalitesinde yeniden üçgenlendi: {before} üçgenden {after} üçgene.", + "Re-tessellated {parts} CAD parts at {quality}.": "{parts} CAD parçası {quality} kalitesinde yeniden üçgenlendi.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "{parts} CAD parçası {quality} kalitesinde yeniden üçgenlendi: {before} üçgenden {after} üçgene.", + "Re-tessellating": "Yeniden üçgenleniyor", + "Read the status again": "Durumu yeniden oku", + "Reading the published record": "Yayımlanan kayıt okunuyor", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "STEP veya IGES'ten içe aktarılan parçaların meshlerini başka bir kalitede, tek bir geri alma adımı olarak yeniden oluşturun.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP ve IGES dosyalarını FormCAD'in çekirdek çalışanı açar; bu, FormShot'ın bir kez indirdiği, dosya dosya denetlediği ve önbellek klasörünüzde sakladığı ayrı bir programdır. Diğer model biçimleri ona ihtiyaç duymaz.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP ve IGES dosyaları CAD çalışanını gerektirir ve bu bilgisayar için yayımlanmış bir çalışan yok.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP ve IGES dosyaları CAD çalışanını gerektirir; o henüz yüklü değil.", + "Selected CAD parts": "Seçili CAD parçaları", + "Source": "Kaynak", + "The CAD worker is installed.": "CAD çalışanı yüklü.", + "The CAD worker is installed. You can import this file now.": "CAD çalışanı yüklü. Bu dosyayı şimdi içe aktarabilirsiniz.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "STEP ve IGES dosyalarını açan CAD çalışanı ve varsayılan CAD kalitesi.", + "The FormShot service is not reachable.": "FormShot hizmetine ulaşılamıyor.", + "The download failed: {reason}": "İndirme başarısız oldu: {reason}", + "The download was cancelled. Nothing was installed.": "İndirme iptal edildi. Hiçbir şey yüklenmedi.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Motor bir tahmin vermez; daha ince kaliteler daha uzun sürer ve daha çok üçgen üretir.", + "The parts could not be read: {reason}": "Parçalar okunamadı: {reason}", + "The service cannot stop a download once it has started.": "Hizmet, başladıktan sonra bir indirmeyi durduramaz.", + "The service refused the request from this window.": "Hizmet bu pencereden gelen isteği reddetti.", + "The status could not be read: {reason}": "Durum okunamadı: {reason}", + "The worker did not answer: {reason}": "Çalışan yanıt vermedi: {reason}", + "This computer": "Bu bilgisayar", + "This engine cannot re-tessellate CAD parts.": "Bu motor CAD parçalarını yeniden üçgenleyemez.", + "Triangles now": "Şimdiki üçgenler", + "Try Again": "Tekrar Dene", + "Unknown": "Bilinmiyor", + "Unpacking": "Açılıyor", + "Version": "Sürüm", + "degrees": "derece", + "no reason was given": "neden belirtilmedi", + "{done} of {total}": "{done} / {total}", + "{n} files": "{n} dosya", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, protokol {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, açılmış {size}, dosya dosya denetlendi", + "{tag}: none for this computer": "{tag}: bu bilgisayar için yok", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} dosya, açılmış {size}" +} diff --git a/frontend/src/i18n/modules/cad/uk.json b/frontend/src/i18n/modules/cad/uk.json new file mode 100644 index 00000000..95a0af64 --- /dev/null +++ b/frontend/src/i18n/modules/cad/uk.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% від розміру моделі", + "About {n} triangles afterwards.": "Приблизно {n} трикутників після цього.", + "All CAD parts": "Усі CAD-деталі", + "Angle": "Кут", + "Angle in degrees": "Кут у градусах", + "Apply": "Застосувати", + "Beside the FormShot engine": "Поруч із рушієм FormShot", + "CAD Import": "Імпорт CAD", + "CAD Import Settings...": "Налаштування імпорту CAD...", + "CAD Options in the Import Sheet": "Параметри CAD у вікні імпорту", + "CAD worker": "Робочий процес CAD", + "CAD worker: {stage}, {pct}%": "Робочий процес CAD: {stage}, {pct}%", + "Check the worker": "Перевірити робочий процес", + "Checking every file": "Перевірка кожного файлу", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Виберіть файли STEP або IGES для імпорту; вони відкриваються через робочий процес CAD.", + "Chord": "Хорда", + "Chord as a percentage of the model size": "Хорда у відсотках від розміру моделі", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Хорда має бути більшою за 0 і не більшою за {max}% від розміру моделі; кут від {min} до {amax} градусів.", + "Chord {chord}% of the model size, angle {angle} degrees": "Хорда {chord}% від розміру моделі, кут {angle} градусів", + "Could not re-tessellate: {reason}": "Не вдалося виконати повторну тесселяцію: {reason}", + "Custom": "Власне", + "Custom ({chord}%, {angle}°)": "Власне ({chord}%, {angle}°)", + "Default CAD quality": "Якість CAD за замовчуванням", + "Download": "Завантажити", + "Download and check the program that opens STEP and IGES files.": "Завантажте й перевірте програму, що відкриває файли STEP та IGES.", + "Download the CAD Worker": "Завантажити робочий процес CAD", + "Download the CAD worker": "Завантажити робочий процес CAD", + "Downloaded into the cache folder": "Завантажено в теку кешу", + "Downloading": "Завантаження", + "Found in": "Знайдено в", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Наскільки дрібно поверхні STEP та IGES перетворюються на трикутники під час імпорту. Хорда: найбільший проміжок між трикутником і справжньою поверхнею у частках розміру всієї моделі; кут: найбільший вигин між сусідніми трикутниками. Дрібніші налаштування працюють довше й дають більші файли. Вікно імпорту починається з цього вибору; для одного імпорту його можна змінити там.", + "Installed": "Встановлено", + "Mixed": "Змішане", + "Named by FORMSHOT_CAD_WORKER": "Задано через FORMSHOT_CAD_WORKER", + "New quality": "Нова якість", + "None of the selected parts came from a STEP or IGES file.": "Жодна з вибраних деталей не походить із файлу STEP чи IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Жодна з вибраних деталей не походить із файлу STEP чи IGES. Зніміть виділення, щоб перебудувати всі CAD-деталі.", + "Not available.": "Недоступно.", + "Not available: {reason}": "Недоступно: {reason}", + "Not installed": "Не встановлено", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Ще не встановлено. FormShot шукає його в {folder}; завантажте його тут, щоб відкривати файли STEP та IGES.", + "Not named": "Не задано", + "Not recorded": "Не записано", + "Nothing in this document came from a STEP or IGES file.": "У цьому документі немає нічого з файлів STEP чи IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "Нічого не вибрано, тому буде перебудовано всі CAD-деталі.", + "Published": "Опубліковано", + "Quality now": "Поточна якість", + "Re-tessellate CAD Parts": "Повторна тесселяція CAD-деталей", + "Re-tessellate CAD Parts...": "Повторна тесселяція CAD-деталей...", + "Re-tessellated 1 CAD part at {quality}.": "Повторна тесселяція 1 CAD-деталі з якістю {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "Повторна тесселяція 1 CAD-деталі з якістю {quality}: трикутників було {before}, стало {after}.", + "Re-tessellated {parts} CAD parts at {quality}.": "Повторна тесселяція CAD-деталей: {parts}, якість {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "Повторна тесселяція CAD-деталей: {parts}, якість {quality}: трикутників було {before}, стало {after}.", + "Re-tessellating": "Повторна тесселяція", + "Read the status again": "Прочитати стан заново", + "Reading the published record": "Читання опублікованого запису", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Перебудуйте меші деталей, імпортованих зі STEP чи IGES, з іншою якістю, одним кроком скасування.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "Файли STEP та IGES відкриває робочий процес ядра FormCAD, окрема програма, яку FormShot завантажує один раз, перевіряє файл за файлом і зберігає в теці кешу. Інші формати моделей її не потребують.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "Для файлів STEP та IGES потрібен робочий процес CAD, але для цього комп'ютера його не опубліковано.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "Для файлів STEP та IGES потрібен робочий процес CAD, який ще не встановлено.", + "Selected CAD parts": "Вибрані CAD-деталі", + "Source": "Джерело", + "The CAD worker is installed.": "Робочий процес CAD встановлено.", + "The CAD worker is installed. You can import this file now.": "Робочий процес CAD встановлено. Тепер можна імпортувати цей файл.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Робочий процес CAD, що відкриває файли STEP та IGES, і якість CAD за замовчуванням.", + "The FormShot service is not reachable.": "Служба FormShot недоступна.", + "The download failed: {reason}": "Не вдалося завантажити: {reason}", + "The download was cancelled. Nothing was installed.": "Завантаження скасовано. Нічого не встановлено.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Рушій не дає оцінки; вища якість займає більше часу й дає більше трикутників.", + "The parts could not be read: {reason}": "Не вдалося прочитати деталі: {reason}", + "The service cannot stop a download once it has started.": "Служба не може зупинити завантаження після його початку.", + "The service refused the request from this window.": "Служба відхилила запит із цього вікна.", + "The status could not be read: {reason}": "Не вдалося прочитати стан: {reason}", + "The worker did not answer: {reason}": "Робочий процес не відповів: {reason}", + "This computer": "Цей комп'ютер", + "This engine cannot re-tessellate CAD parts.": "Цей рушій не вміє повторно виконувати тесселяцію CAD-деталей.", + "Triangles now": "Зараз трикутників", + "Try Again": "Повторити", + "Unknown": "Невідомо", + "Unpacking": "Розпакування", + "Version": "Версія", + "degrees": "градусів", + "no reason was given": "причину не вказано", + "{done} of {total}": "{done} із {total}", + "{n} files": "Файлів: {n}", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, протокол {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, розпаковано {size}, перевірено файл за файлом", + "{tag}: none for this computer": "{tag}: для цього комп'ютера немає", + "{tag}: {files} files, {size} unpacked": "{tag}: файлів {files}, розпаковано {size}" +} diff --git a/frontend/src/i18n/modules/cad/vi.json b/frontend/src/i18n/modules/cad/vi.json new file mode 100644 index 00000000..470bf9ce --- /dev/null +++ b/frontend/src/i18n/modules/cad/vi.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "% kích thước mô hình", + "About {n} triangles afterwards.": "Sau đó khoảng {n} tam giác.", + "All CAD parts": "Tất cả bộ phận CAD", + "Angle": "Góc", + "Angle in degrees": "Góc theo độ", + "Apply": "Áp dụng", + "Beside the FormShot engine": "Cạnh công cụ FormShot", + "CAD Import": "Nhập CAD", + "CAD Import Settings...": "Cài đặt nhập CAD...", + "CAD Options in the Import Sheet": "Tùy chọn CAD trong bảng nhập", + "CAD worker": "Worker CAD", + "CAD worker: {stage}, {pct}%": "Worker CAD: {stage}, {pct}%", + "Check the worker": "Kiểm tra worker", + "Checking every file": "Đang kiểm tra từng tệp", + "Choose STEP or IGES files to import; they open through the CAD worker.": "Chọn tệp STEP hoặc IGES để nhập; các tệp này được mở bằng worker CAD.", + "Chord": "Dây cung", + "Chord as a percentage of the model size": "Dây cung theo phần trăm kích thước mô hình", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "Dây cung phải lớn hơn 0 và tối đa {max}% kích thước mô hình; góc từ {min} đến {amax} độ.", + "Chord {chord}% of the model size, angle {angle} degrees": "Dây cung {chord}% kích thước mô hình, góc {angle} độ", + "Could not re-tessellate: {reason}": "Không thể chia lại tam giác: {reason}", + "Custom": "Tùy chỉnh", + "Custom ({chord}%, {angle}°)": "Tùy chỉnh ({chord}%, {angle}°)", + "Default CAD quality": "Chất lượng CAD mặc định", + "Download": "Tải xuống", + "Download and check the program that opens STEP and IGES files.": "Tải xuống và kiểm tra chương trình mở tệp STEP và IGES.", + "Download the CAD Worker": "Tải xuống worker CAD", + "Download the CAD worker": "Tải xuống worker CAD", + "Downloaded into the cache folder": "Đã tải vào thư mục bộ nhớ đệm", + "Downloading": "Đang tải xuống", + "Found in": "Tìm thấy trong", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "Mức độ mịn khi bề mặt STEP và IGES được chia thành tam giác lúc nhập. Dây cung là khoảng hở lớn nhất giữa một tam giác và bề mặt thật, tính theo tỷ lệ kích thước cả mô hình; góc là độ gập lớn nhất giữa các tam giác kề nhau. Thiết lập mịn hơn mất nhiều thời gian hơn và tạo tệp lớn hơn. Bảng nhập bắt đầu với lựa chọn này; bạn có thể đổi cho một lần nhập ngay tại đó.", + "Installed": "Đã cài đặt", + "Mixed": "Hỗn hợp", + "Named by FORMSHOT_CAD_WORKER": "Được đặt tên bởi FORMSHOT_CAD_WORKER", + "New quality": "Chất lượng mới", + "None of the selected parts came from a STEP or IGES file.": "Không bộ phận nào trong số đã chọn đến từ tệp STEP hoặc IGES.", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "Không bộ phận nào trong số đã chọn đến từ tệp STEP hoặc IGES. Bỏ chọn để dựng lại mọi bộ phận CAD.", + "Not available.": "Không có sẵn.", + "Not available: {reason}": "Không có sẵn: {reason}", + "Not installed": "Chưa cài đặt", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "Chưa cài đặt. FormShot tìm trong {folder}; hãy tải xuống tại đây để mở tệp STEP và IGES.", + "Not named": "Không được đặt tên", + "Not recorded": "Chưa ghi nhận", + "Nothing in this document came from a STEP or IGES file.": "Không có gì trong tài liệu này đến từ tệp STEP hoặc IGES.", + "Nothing is selected, so every CAD part is rebuilt.": "Chưa chọn gì nên mọi bộ phận CAD sẽ được dựng lại.", + "Published": "Đã phát hành", + "Quality now": "Chất lượng hiện tại", + "Re-tessellate CAD Parts": "Chia lại tam giác cho bộ phận CAD", + "Re-tessellate CAD Parts...": "Chia lại tam giác cho bộ phận CAD...", + "Re-tessellated 1 CAD part at {quality}.": "Đã chia lại tam giác cho 1 bộ phận CAD ở mức {quality}.", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "Đã chia lại tam giác cho 1 bộ phận CAD ở mức {quality}: từ {before} thành {after} tam giác.", + "Re-tessellated {parts} CAD parts at {quality}.": "Đã chia lại tam giác cho {parts} bộ phận CAD ở mức {quality}.", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "Đã chia lại tam giác cho {parts} bộ phận CAD ở mức {quality}: từ {before} thành {after} tam giác.", + "Re-tessellating": "Đang chia lại tam giác", + "Read the status again": "Đọc lại trạng thái", + "Reading the published record": "Đang đọc bản ghi đã phát hành", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "Dựng lại mesh của các bộ phận nhập từ STEP hoặc IGES ở chất lượng khác, như một bước hoàn tác.", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "Tệp STEP và IGES được mở bởi worker lõi của FormCAD, một chương trình riêng mà FormShot tải xuống một lần, kiểm tra từng tệp và giữ trong thư mục bộ nhớ đệm của bạn. Các định dạng mô hình khác không cần đến nó.", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "Tệp STEP và IGES cần worker CAD, nhưng chưa có bản nào được phát hành cho máy tính này.", + "STEP and IGES files need the CAD worker, which is not installed yet.": "Tệp STEP và IGES cần worker CAD, hiện chưa được cài đặt.", + "Selected CAD parts": "Bộ phận CAD đã chọn", + "Source": "Nguồn", + "The CAD worker is installed.": "Worker CAD đã được cài đặt.", + "The CAD worker is installed. You can import this file now.": "Worker CAD đã được cài đặt. Bạn có thể nhập tệp này ngay.", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "Worker CAD mở tệp STEP và IGES, và chất lượng CAD mặc định.", + "The FormShot service is not reachable.": "Không kết nối được dịch vụ FormShot.", + "The download failed: {reason}": "Tải xuống không thành công: {reason}", + "The download was cancelled. Nothing was installed.": "Đã hủy tải xuống. Chưa cài đặt gì.", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "Công cụ không đưa ra ước tính; chất lượng mịn hơn mất nhiều thời gian hơn và tạo nhiều tam giác hơn.", + "The parts could not be read: {reason}": "Không thể đọc các bộ phận: {reason}", + "The service cannot stop a download once it has started.": "Dịch vụ không thể dừng tải xuống khi đã bắt đầu.", + "The service refused the request from this window.": "Dịch vụ từ chối yêu cầu từ cửa sổ này.", + "The status could not be read: {reason}": "Không thể đọc trạng thái: {reason}", + "The worker did not answer: {reason}": "Worker không phản hồi: {reason}", + "This computer": "Máy tính này", + "This engine cannot re-tessellate CAD parts.": "Công cụ này không thể chia lại tam giác cho bộ phận CAD.", + "Triangles now": "Số tam giác hiện tại", + "Try Again": "Thử lại", + "Unknown": "Không rõ", + "Unpacking": "Đang giải nén", + "Version": "Phiên bản", + "degrees": "độ", + "no reason was given": "không có lý do nào được nêu", + "{done} of {total}": "{done} trên {total}", + "{n} files": "{n} tệp", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag}, OpenCascade {occt}, giao thức {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag}, đã giải nén {size}, đã kiểm tra từng tệp", + "{tag}: none for this computer": "{tag}: không có bản cho máy tính này", + "{tag}: {files} files, {size} unpacked": "{tag}: {files} tệp, đã giải nén {size}" +} diff --git a/frontend/src/i18n/modules/cad/zh-CN.json b/frontend/src/i18n/modules/cad/zh-CN.json new file mode 100644 index 00000000..3a495c37 --- /dev/null +++ b/frontend/src/i18n/modules/cad/zh-CN.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "占模型尺寸的百分比", + "About {n} triangles afterwards.": "之后约有 {n} 个三角形。", + "All CAD parts": "所有 CAD 部件", + "Angle": "角度", + "Angle in degrees": "角度(度)", + "Apply": "应用", + "Beside the FormShot engine": "位于 FormShot 引擎旁边", + "CAD Import": "CAD 导入", + "CAD Import Settings...": "CAD 导入设置...", + "CAD Options in the Import Sheet": "导入面板中的 CAD 选项", + "CAD worker": "CAD 工作程序", + "CAD worker: {stage}, {pct}%": "CAD 工作程序:{stage},{pct}%", + "Check the worker": "检查工作程序", + "Checking every file": "正在检查所有文件", + "Choose STEP or IGES files to import; they open through the CAD worker.": "选择要导入的 STEP 或 IGES 文件;它们将通过 CAD 工作程序打开。", + "Chord": "弦差", + "Chord as a percentage of the model size": "弦差(占模型尺寸的百分比)", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "弦差必须大于 0 且不超过模型尺寸的 {max}%;角度范围为 {min} 到 {amax} 度。", + "Chord {chord}% of the model size, angle {angle} degrees": "弦差为模型尺寸的 {chord}%,角度 {angle} 度", + "Could not re-tessellate: {reason}": "无法重新细分:{reason}", + "Custom": "自定义", + "Custom ({chord}%, {angle}°)": "自定义({chord}%,{angle}°)", + "Default CAD quality": "默认 CAD 质量", + "Download": "下载", + "Download and check the program that opens STEP and IGES files.": "下载并检查用于打开 STEP 和 IGES 文件的程序。", + "Download the CAD Worker": "下载 CAD 工作程序", + "Download the CAD worker": "下载 CAD 工作程序", + "Downloaded into the cache folder": "已下载到缓存文件夹", + "Downloading": "正在下载", + "Found in": "发现位置", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "决定导入时 STEP 和 IGES 曲面被细分为三角形的精细程度。弦差是三角形与真实曲面之间的最大间隙,以占整个模型尺寸的比例表示;角度是相邻三角形之间的最大折角。设置越精细,耗时越长,文件也越大。导入面板以此选项为起点,你可以在面板中为单次导入修改。", + "Installed": "已安装", + "Mixed": "混合", + "Named by FORMSHOT_CAD_WORKER": "由 FORMSHOT_CAD_WORKER 指定", + "New quality": "新质量", + "None of the selected parts came from a STEP or IGES file.": "所选部件均不是来自 STEP 或 IGES 文件。", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "所选部件均不是来自 STEP 或 IGES 文件。清除选择即可重建所有 CAD 部件。", + "Not available.": "不可用。", + "Not available: {reason}": "不可用:{reason}", + "Not installed": "未安装", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "尚未安装。FormShot 会在 {folder} 中查找;可在此下载以打开 STEP 和 IGES 文件。", + "Not named": "未指定", + "Not recorded": "未记录", + "Nothing in this document came from a STEP or IGES file.": "此文档中没有来自 STEP 或 IGES 文件的内容。", + "Nothing is selected, so every CAD part is rebuilt.": "未选择任何内容,因此将重建所有 CAD 部件。", + "Published": "已发布", + "Quality now": "当前质量", + "Re-tessellate CAD Parts": "重新细分 CAD 部件", + "Re-tessellate CAD Parts...": "重新细分 CAD 部件...", + "Re-tessellated 1 CAD part at {quality}.": "已按 {quality} 重新细分 1 个 CAD 部件。", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "已按 {quality} 重新细分 1 个 CAD 部件:三角形从 {before} 个变为 {after} 个。", + "Re-tessellated {parts} CAD parts at {quality}.": "已按 {quality} 重新细分 {parts} 个 CAD 部件。", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "已按 {quality} 重新细分 {parts} 个 CAD 部件:三角形从 {before} 个变为 {after} 个。", + "Re-tessellating": "正在重新细分", + "Read the status again": "重新读取状态", + "Reading the published record": "正在读取已发布的记录", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "以另一种质量重建从 STEP 或 IGES 导入的部件网格,作为一个撤销步骤。", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP 和 IGES 文件由 FormCAD 的内核工作程序打开。这是一个独立的程序,FormShot 会下载一次,逐个文件检查,并保存在你的缓存文件夹中。其他模型格式不需要它。", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP 和 IGES 文件需要 CAD 工作程序,但没有适用于此计算机的发布版本。", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP 和 IGES 文件需要 CAD 工作程序,但尚未安装。", + "Selected CAD parts": "所选 CAD 部件", + "Source": "来源", + "The CAD worker is installed.": "CAD 工作程序已安装。", + "The CAD worker is installed. You can import this file now.": "CAD 工作程序已安装。现在可以导入此文件。", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "用于打开 STEP 和 IGES 文件的 CAD 工作程序,以及默认 CAD 质量。", + "The FormShot service is not reachable.": "无法连接 FormShot 服务。", + "The download failed: {reason}": "下载失败:{reason}", + "The download was cancelled. Nothing was installed.": "下载已取消,未安装任何内容。", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "引擎不提供估算值;质量越精细,耗时越长,三角形也越多。", + "The parts could not be read: {reason}": "无法读取这些部件:{reason}", + "The service cannot stop a download once it has started.": "下载开始后,服务无法停止。", + "The service refused the request from this window.": "服务拒绝了来自此窗口的请求。", + "The status could not be read: {reason}": "无法读取状态:{reason}", + "The worker did not answer: {reason}": "工作程序没有响应:{reason}", + "This computer": "此计算机", + "This engine cannot re-tessellate CAD parts.": "此引擎无法重新细分 CAD 部件。", + "Triangles now": "当前三角形数", + "Try Again": "重试", + "Unknown": "未知", + "Unpacking": "正在解压", + "Version": "版本", + "degrees": "度", + "no reason was given": "未给出原因", + "{done} of {total}": "{done} / {total}", + "{n} files": "{n} 个文件", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag},OpenCascade {occt},协议 {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag},解压后 {size},已逐个文件检查", + "{tag}: none for this computer": "{tag}:没有适用于此计算机的版本", + "{tag}: {files} files, {size} unpacked": "{tag}:{files} 个文件,解压后 {size}" +} diff --git a/frontend/src/i18n/modules/cad/zh-TW.json b/frontend/src/i18n/modules/cad/zh-TW.json new file mode 100644 index 00000000..979cd68d --- /dev/null +++ b/frontend/src/i18n/modules/cad/zh-TW.json @@ -0,0 +1,91 @@ +{ + "% of the model size": "佔模型尺寸的百分比", + "About {n} triangles afterwards.": "之後約有 {n} 個三角形。", + "All CAD parts": "所有 CAD 零件", + "Angle": "角度", + "Angle in degrees": "角度(度)", + "Apply": "套用", + "Beside the FormShot engine": "位於 FormShot 引擎旁邊", + "CAD Import": "CAD 匯入", + "CAD Import Settings...": "CAD 匯入設定...", + "CAD Options in the Import Sheet": "匯入面板中的 CAD 選項", + "CAD worker": "CAD 工作程式", + "CAD worker: {stage}, {pct}%": "CAD 工作程式:{stage},{pct}%", + "Check the worker": "檢查工作程式", + "Checking every file": "正在檢查所有檔案", + "Choose STEP or IGES files to import; they open through the CAD worker.": "選擇要匯入的 STEP 或 IGES 檔案;它們將透過 CAD 工作程式開啟。", + "Chord": "弦差", + "Chord as a percentage of the model size": "弦差(佔模型尺寸的百分比)", + "Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.": "弦差必須大於 0 且不超過模型尺寸的 {max}%;角度範圍為 {min} 到 {amax} 度。", + "Chord {chord}% of the model size, angle {angle} degrees": "弦差為模型尺寸的 {chord}%,角度 {angle} 度", + "Could not re-tessellate: {reason}": "無法重新細分:{reason}", + "Custom": "自訂", + "Custom ({chord}%, {angle}°)": "自訂({chord}%,{angle}°)", + "Default CAD quality": "預設 CAD 品質", + "Download": "下載", + "Download and check the program that opens STEP and IGES files.": "下載並檢查用於開啟 STEP 和 IGES 檔案的程式。", + "Download the CAD Worker": "下載 CAD 工作程式", + "Download the CAD worker": "下載 CAD 工作程式", + "Downloaded into the cache folder": "已下載到快取資料夾", + "Downloading": "正在下載", + "Found in": "發現位置", + "How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.": "決定匯入時 STEP 和 IGES 曲面被細分為三角形的精細程度。弦差是三角形與真實曲面之間的最大間隙,以佔整個模型尺寸的比例表示;角度是相鄰三角形之間的最大折角。設定越精細,耗時越長,檔案也越大。匯入面板以此選項為起點,你可以在面板中為單次匯入修改。", + "Installed": "已安裝", + "Mixed": "混合", + "Named by FORMSHOT_CAD_WORKER": "由 FORMSHOT_CAD_WORKER 指定", + "New quality": "新品質", + "None of the selected parts came from a STEP or IGES file.": "所選零件均不是來自 STEP 或 IGES 檔案。", + "None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.": "所選零件均不是來自 STEP 或 IGES 檔案。清除選取即可重建所有 CAD 零件。", + "Not available.": "無法使用。", + "Not available: {reason}": "無法使用:{reason}", + "Not installed": "未安裝", + "Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.": "尚未安裝。FormShot 會在 {folder} 中尋找;可在此下載以開啟 STEP 和 IGES 檔案。", + "Not named": "未指定", + "Not recorded": "未記錄", + "Nothing in this document came from a STEP or IGES file.": "此文件中沒有來自 STEP 或 IGES 檔案的內容。", + "Nothing is selected, so every CAD part is rebuilt.": "未選取任何內容,因此將重建所有 CAD 零件。", + "Published": "已發佈", + "Quality now": "目前品質", + "Re-tessellate CAD Parts": "重新細分 CAD 零件", + "Re-tessellate CAD Parts...": "重新細分 CAD 零件...", + "Re-tessellated 1 CAD part at {quality}.": "已依 {quality} 重新細分 1 個 CAD 零件。", + "Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.": "已依 {quality} 重新細分 1 個 CAD 零件:三角形從 {before} 個變為 {after} 個。", + "Re-tessellated {parts} CAD parts at {quality}.": "已依 {quality} 重新細分 {parts} 個 CAD 零件。", + "Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.": "已依 {quality} 重新細分 {parts} 個 CAD 零件:三角形從 {before} 個變為 {after} 個。", + "Re-tessellating": "正在重新細分", + "Read the status again": "重新讀取狀態", + "Reading the published record": "正在讀取已發佈的記錄", + "Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.": "以另一種品質重建從 STEP 或 IGES 匯入的零件網格,作為一個復原步驟。", + "STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.": "STEP 和 IGES 檔案由 FormCAD 的核心工作程式開啟。這是一個獨立的程式,FormShot 會下載一次,逐個檔案檢查,並保存在你的快取資料夾中。其他模型格式不需要它。", + "STEP and IGES files need the CAD worker, and none is published for this computer.": "STEP 和 IGES 檔案需要 CAD 工作程式,但沒有適用於此電腦的發佈版本。", + "STEP and IGES files need the CAD worker, which is not installed yet.": "STEP 和 IGES 檔案需要 CAD 工作程式,但尚未安裝。", + "Selected CAD parts": "所選 CAD 零件", + "Source": "來源", + "The CAD worker is installed.": "CAD 工作程式已安裝。", + "The CAD worker is installed. You can import this file now.": "CAD 工作程式已安裝。現在可以匯入此檔案。", + "The CAD worker that opens STEP and IGES files, and the default CAD quality.": "用於開啟 STEP 和 IGES 檔案的 CAD 工作程式,以及預設 CAD 品質。", + "The FormShot service is not reachable.": "無法連線到 FormShot 服務。", + "The download failed: {reason}": "下載失敗:{reason}", + "The download was cancelled. Nothing was installed.": "下載已取消,未安裝任何內容。", + "The engine gives no estimate; finer qualities take longer and make more triangles.": "引擎不提供估算值;品質越精細,耗時越長,三角形也越多。", + "The parts could not be read: {reason}": "無法讀取這些零件:{reason}", + "The service cannot stop a download once it has started.": "下載開始後,服務無法停止。", + "The service refused the request from this window.": "服務拒絕了來自此視窗的要求。", + "The status could not be read: {reason}": "無法讀取狀態:{reason}", + "The worker did not answer: {reason}": "工作程式沒有回應:{reason}", + "This computer": "此電腦", + "This engine cannot re-tessellate CAD parts.": "此引擎無法重新細分 CAD 零件。", + "Triangles now": "目前三角形數", + "Try Again": "重試", + "Unknown": "未知", + "Unpacking": "正在解壓縮", + "Version": "版本", + "degrees": "度", + "no reason was given": "未提供原因", + "{done} of {total}": "{done} / {total}", + "{n} files": "{n} 個檔案", + "{tag}, OpenCascade {occt}, protocol {protocol}": "{tag},OpenCascade {occt},通訊協定 {protocol}", + "{tag}, {size} unpacked, checked file by file": "{tag},解壓縮後 {size},已逐個檔案檢查", + "{tag}: none for this computer": "{tag}:沒有適用於此電腦的版本", + "{tag}: {files} files, {size} unpacked": "{tag}:{files} 個檔案,解壓縮後 {size}" +} diff --git a/frontend/src/i18n/modules/gpuview/cs.json b/frontend/src/i18n/modules/gpuview/cs.json index 9bf14fd7..6448aa9a 100644 --- a/frontend/src/i18n/modules/gpuview/cs.json +++ b/frontend/src/i18n/modules/gpuview/cs.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Streamované snímky (WebGPU vypnuto)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Texturu {name} nelze použít ({reason}); její materiál zobrazuje náhradu", "The GPU engine refuses this work: {reason}": "Engine GPU tuto práci odmítá: {reason}", "The GPU path tracer could not start: {reason}": "Path tracer na GPU se nepodařilo spustit: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "Path tracer na GPU se nespustil do {seconds} s; okno zobrazuje streamované snímky", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU nenašlo žádný použitelný adaptér", "WebGPU in the window": "WebGPU v okně", "WebGPU in the window is not available": "WebGPU v okně není k dispozici", - "WebGPU in the window is turned off": "WebGPU v okně je vypnuto" + "WebGPU in the window is turned off": "WebGPU v okně je vypnuto", + "{count} textures could not be used; their materials show the fallback": "Textury ({count}) nelze použít; jejich materiály zobrazují náhradu" } diff --git a/frontend/src/i18n/modules/gpuview/da.json b/frontend/src/i18n/modules/gpuview/da.json index d6dd7d2d..060f1b4d 100644 --- a/frontend/src/i18n/modules/gpuview/da.json +++ b/frontend/src/i18n/modules/gpuview/da.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Streamede billeder (WebGPU slået fra)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Teksturen {name} kunne ikke bruges ({reason}); dens materiale viser reserveløsningen", "The GPU engine refuses this work: {reason}": "GPU-motoren afviser dette arbejde: {reason}", "The GPU path tracer could not start: {reason}": "GPU-path traceren kunne ikke starte: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU-path traceren startede ikke inden for {seconds} s; vinduet viser streamede billeder", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU fandt ingen brugbar adapter", "WebGPU in the window": "WebGPU i vinduet", "WebGPU in the window is not available": "WebGPU i vinduet er ikke tilgængelig", - "WebGPU in the window is turned off": "WebGPU i vinduet er slået fra" + "WebGPU in the window is turned off": "WebGPU i vinduet er slået fra", + "{count} textures could not be used; their materials show the fallback": "{count} teksturer kunne ikke bruges; deres materialer viser reserveløsningen" } diff --git a/frontend/src/i18n/modules/gpuview/de.json b/frontend/src/i18n/modules/gpuview/de.json index b0f80e2b..6af8280e 100644 --- a/frontend/src/i18n/modules/gpuview/de.json +++ b/frontend/src/i18n/modules/gpuview/de.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Gestreamte Frames (WebGPU aus)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Textur {name} konnte nicht verwendet werden ({reason}); ihr Material zeigt den Ersatz", "The GPU engine refuses this work: {reason}": "Die GPU-Engine lehnt diese Arbeit ab: {reason}", "The GPU path tracer could not start: {reason}": "Der GPU-Path-Tracer konnte nicht starten: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "Der GPU-Path-Tracer ist nicht innerhalb von {seconds} s gestartet; das Fenster zeigt gestreamte Frames", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU hat keinen nutzbaren Adapter gefunden", "WebGPU in the window": "WebGPU im Fenster", "WebGPU in the window is not available": "WebGPU im Fenster ist nicht verfügbar", - "WebGPU in the window is turned off": "WebGPU im Fenster ist ausgeschaltet" + "WebGPU in the window is turned off": "WebGPU im Fenster ist ausgeschaltet", + "{count} textures could not be used; their materials show the fallback": "{count} Texturen konnten nicht verwendet werden; ihre Materialien zeigen den Ersatz" } diff --git a/frontend/src/i18n/modules/gpuview/es.json b/frontend/src/i18n/modules/gpuview/es.json index 27c3a7b3..5fd67441 100644 --- a/frontend/src/i18n/modules/gpuview/es.json +++ b/frontend/src/i18n/modules/gpuview/es.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Fotogramas en streaming (WebGPU desactivado)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "No se pudo usar la textura {name} ({reason}); su material muestra el sustituto", "The GPU engine refuses this work: {reason}": "El motor GPU rechaza este trabajo: {reason}", "The GPU path tracer could not start: {reason}": "El path tracer de GPU no pudo iniciarse: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "El path tracer de GPU no se inició en {seconds} s; la ventana muestra fotogramas en streaming", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU no encontró ningún adaptador utilizable", "WebGPU in the window": "WebGPU en la ventana", "WebGPU in the window is not available": "WebGPU en la ventana no está disponible", - "WebGPU in the window is turned off": "WebGPU en la ventana está desactivado" + "WebGPU in the window is turned off": "WebGPU en la ventana está desactivado", + "{count} textures could not be used; their materials show the fallback": "No se pudieron usar {count} texturas; sus materiales muestran el sustituto" } diff --git a/frontend/src/i18n/modules/gpuview/fi.json b/frontend/src/i18n/modules/gpuview/fi.json index 2e71029e..42ba4072 100644 --- a/frontend/src/i18n/modules/gpuview/fi.json +++ b/frontend/src/i18n/modules/gpuview/fi.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Suoratoistetut kuvat (WebGPU pois käytöstä)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Tekstuuria {name} ei voitu käyttää ({reason}); sen materiaali näyttää varavaihtoehdon", "The GPU engine refuses this work: {reason}": "GPU-moottori kieltäytyy tästä työstä: {reason}", "The GPU path tracer could not start: {reason}": "GPU-path traceria ei voitu käynnistää: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU-path tracer ei käynnistynyt {seconds} sekunnissa; ikkuna näyttää suoratoistetut kuvat", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU ei löytänyt käyttökelpoista sovitinta", "WebGPU in the window": "WebGPU ikkunassa", "WebGPU in the window is not available": "WebGPU ikkunassa ei ole käytettävissä", - "WebGPU in the window is turned off": "WebGPU ikkunassa on poistettu käytöstä" + "WebGPU in the window is turned off": "WebGPU ikkunassa on poistettu käytöstä", + "{count} textures could not be used; their materials show the fallback": "{count} tekstuuria ei voitu käyttää; niiden materiaalit näyttävät varavaihtoehdon" } diff --git a/frontend/src/i18n/modules/gpuview/fr.json b/frontend/src/i18n/modules/gpuview/fr.json index 46b1a3f7..bf6845a9 100644 --- a/frontend/src/i18n/modules/gpuview/fr.json +++ b/frontend/src/i18n/modules/gpuview/fr.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Images diffusées en flux (WebGPU désactivé)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "La texture {name} n'a pas pu être utilisée ({reason}) ; son matériau affiche le remplacement", "The GPU engine refuses this work: {reason}": "Le moteur GPU refuse ce travail : {reason}", "The GPU path tracer could not start: {reason}": "Le path tracer GPU n'a pas pu démarrer : {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "Le path tracer GPU n'a pas démarré en {seconds} s ; la fenêtre affiche des images diffusées en flux", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU n'a trouvé aucun adaptateur utilisable", "WebGPU in the window": "WebGPU dans la fenêtre", "WebGPU in the window is not available": "WebGPU dans la fenêtre n'est pas disponible", - "WebGPU in the window is turned off": "WebGPU dans la fenêtre est désactivé" + "WebGPU in the window is turned off": "WebGPU dans la fenêtre est désactivé", + "{count} textures could not be used; their materials show the fallback": "{count} textures n'ont pas pu être utilisées ; leurs matériaux affichent le remplacement" } diff --git a/frontend/src/i18n/modules/gpuview/hu.json b/frontend/src/i18n/modules/gpuview/hu.json index 949b80c0..dd067dd4 100644 --- a/frontend/src/i18n/modules/gpuview/hu.json +++ b/frontend/src/i18n/modules/gpuview/hu.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Streamelt képkockák (WebGPU kikapcsolva)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "A(z) {name} textúra nem használható ({reason}); az anyaga a tartalékot mutatja", "The GPU engine refuses this work: {reason}": "A GPU-s motor visszautasítja ezt a munkát: {reason}", "The GPU path tracer could not start: {reason}": "A GPU-s path tracer nem tudott elindulni: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "A GPU-s path tracer {seconds} mp alatt sem indult el; az ablak streamelt képkockákat mutat", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "A WebGPU nem talált használható adaptert", "WebGPU in the window": "WebGPU az ablakban", "WebGPU in the window is not available": "A WebGPU az ablakban nem érhető el", - "WebGPU in the window is turned off": "A WebGPU az ablakban ki van kapcsolva" + "WebGPU in the window is turned off": "A WebGPU az ablakban ki van kapcsolva", + "{count} textures could not be used; their materials show the fallback": "{count} textúra nem használható; az anyagaik a tartalékot mutatják" } diff --git a/frontend/src/i18n/modules/gpuview/id.json b/frontend/src/i18n/modules/gpuview/id.json index 7e0785ed..a279c58e 100644 --- a/frontend/src/i18n/modules/gpuview/id.json +++ b/frontend/src/i18n/modules/gpuview/id.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Frame streaming (WebGPU mati)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Tekstur {name} tidak dapat dipakai ({reason}); materialnya menampilkan cadangan", "The GPU engine refuses this work: {reason}": "Mesin GPU menolak pekerjaan ini: {reason}", "The GPU path tracer could not start: {reason}": "Path tracer GPU tidak dapat dimulai: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "Path tracer GPU tidak mulai dalam {seconds} dtk; jendela menampilkan frame streaming", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU tidak menemukan adaptor yang dapat dipakai", "WebGPU in the window": "WebGPU di jendela", "WebGPU in the window is not available": "WebGPU di jendela tidak tersedia", - "WebGPU in the window is turned off": "WebGPU di jendela dimatikan" + "WebGPU in the window is turned off": "WebGPU di jendela dimatikan", + "{count} textures could not be used; their materials show the fallback": "{count} tekstur tidak dapat dipakai; material-nya menampilkan cadangan" } diff --git a/frontend/src/i18n/modules/gpuview/it.json b/frontend/src/i18n/modules/gpuview/it.json index 7046a57b..63dadd81 100644 --- a/frontend/src/i18n/modules/gpuview/it.json +++ b/frontend/src/i18n/modules/gpuview/it.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Fotogrammi in streaming (WebGPU disattivato)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Impossibile usare la texture {name} ({reason}); il suo materiale mostra il ripiego", "The GPU engine refuses this work: {reason}": "Il motore GPU rifiuta questo lavoro: {reason}", "The GPU path tracer could not start: {reason}": "Impossibile avviare il path tracer GPU: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "Il path tracer GPU non si è avviato entro {seconds} s; la finestra mostra i fotogrammi in streaming", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU non ha trovato alcun adattatore utilizzabile", "WebGPU in the window": "WebGPU nella finestra", "WebGPU in the window is not available": "WebGPU nella finestra non è disponibile", - "WebGPU in the window is turned off": "WebGPU nella finestra è disattivato" + "WebGPU in the window is turned off": "WebGPU nella finestra è disattivato", + "{count} textures could not be used; their materials show the fallback": "Impossibile usare {count} texture; i loro materiali mostrano il ripiego" } diff --git a/frontend/src/i18n/modules/gpuview/ja.json b/frontend/src/i18n/modules/gpuview/ja.json index 970c5d3a..48c40922 100644 --- a/frontend/src/i18n/modules/gpuview/ja.json +++ b/frontend/src/i18n/modules/gpuview/ja.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "ストリーミングフレーム(WebGPU オフ)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "テクスチャ {name} を使用できませんでした ({reason})。このマテリアルは代替表示になります", "The GPU engine refuses this work: {reason}": "GPU エンジンがこの処理を拒否しました:{reason}", "The GPU path tracer could not start: {reason}": "GPU パストレーサーを開始できませんでした:{reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU パストレーサーが {seconds} 秒以内に開始しなかったため、ウィンドウにはストリーミングフレームを表示しています", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU で使用できるアダプターが見つかりませんでした", "WebGPU in the window": "ウィンドウ内の WebGPU", "WebGPU in the window is not available": "ウィンドウ内の WebGPU は利用できません", - "WebGPU in the window is turned off": "ウィンドウ内の WebGPU はオフです" + "WebGPU in the window is turned off": "ウィンドウ内の WebGPU はオフです", + "{count} textures could not be used; their materials show the fallback": "{count} 個のテクスチャを使用できませんでした。該当するマテリアルは代替表示になります" } diff --git a/frontend/src/i18n/modules/gpuview/ko.json b/frontend/src/i18n/modules/gpuview/ko.json index b228c6cc..5ef8b2ae 100644 --- a/frontend/src/i18n/modules/gpuview/ko.json +++ b/frontend/src/i18n/modules/gpuview/ko.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "스트리밍 프레임 (WebGPU 꺼짐)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "텍스처 {name}을(를) 사용할 수 없습니다({reason}). 해당 머티리얼은 대체 표시를 사용합니다", "The GPU engine refuses this work: {reason}": "GPU 엔진이 이 작업을 거부했습니다: {reason}", "The GPU path tracer could not start: {reason}": "GPU 패스 트레이서를 시작할 수 없습니다: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU 패스 트레이서가 {seconds}초 안에 시작되지 않아 창에 스트리밍 프레임을 표시합니다", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU에서 사용할 수 있는 어댑터를 찾지 못했습니다", "WebGPU in the window": "창 안의 WebGPU", "WebGPU in the window is not available": "창 안의 WebGPU를 사용할 수 없습니다", - "WebGPU in the window is turned off": "창 안의 WebGPU가 꺼져 있습니다" + "WebGPU in the window is turned off": "창 안의 WebGPU가 꺼져 있습니다", + "{count} textures could not be used; their materials show the fallback": "텍스처 {count}개를 사용할 수 없습니다. 해당 머티리얼은 대체 표시를 사용합니다" } diff --git a/frontend/src/i18n/modules/gpuview/nb.json b/frontend/src/i18n/modules/gpuview/nb.json index 11db6767..f9081bed 100644 --- a/frontend/src/i18n/modules/gpuview/nb.json +++ b/frontend/src/i18n/modules/gpuview/nb.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Strømmede bilder (WebGPU av)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Teksturen {name} kunne ikke brukes ({reason}); materialet dens viser reserveløsningen", "The GPU engine refuses this work: {reason}": "GPU-motoren avviser dette arbeidet: {reason}", "The GPU path tracer could not start: {reason}": "GPU-path traceren kunne ikke starte: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU-path traceren startet ikke innen {seconds} s; vinduet viser strømmede bilder", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU fant ingen brukbar adapter", "WebGPU in the window": "WebGPU i vinduet", "WebGPU in the window is not available": "WebGPU i vinduet er ikke tilgjengelig", - "WebGPU in the window is turned off": "WebGPU i vinduet er slått av" + "WebGPU in the window is turned off": "WebGPU i vinduet er slått av", + "{count} textures could not be used; their materials show the fallback": "{count} teksturer kunne ikke brukes; materialene deres viser reserveløsningen" } diff --git a/frontend/src/i18n/modules/gpuview/nl.json b/frontend/src/i18n/modules/gpuview/nl.json index 49af4feb..ed8283f5 100644 --- a/frontend/src/i18n/modules/gpuview/nl.json +++ b/frontend/src/i18n/modules/gpuview/nl.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Gestreamde frames (WebGPU uit)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Textuur {name} kon niet worden gebruikt ({reason}); het materiaal toont de terugval", "The GPU engine refuses this work: {reason}": "De GPU-engine weigert dit werk: {reason}", "The GPU path tracer could not start: {reason}": "De GPU-path tracer kon niet starten: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "De GPU-path tracer startte niet binnen {seconds} s; het venster toont gestreamde frames", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU vond geen bruikbare adapter", "WebGPU in the window": "WebGPU in het venster", "WebGPU in the window is not available": "WebGPU in het venster is niet beschikbaar", - "WebGPU in the window is turned off": "WebGPU in het venster is uitgeschakeld" + "WebGPU in the window is turned off": "WebGPU in het venster is uitgeschakeld", + "{count} textures could not be used; their materials show the fallback": "{count} texturen konden niet worden gebruikt; hun materialen tonen de terugval" } diff --git a/frontend/src/i18n/modules/gpuview/pl.json b/frontend/src/i18n/modules/gpuview/pl.json index aefe13f9..a5c71e87 100644 --- a/frontend/src/i18n/modules/gpuview/pl.json +++ b/frontend/src/i18n/modules/gpuview/pl.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Klatki strumieniowane (WebGPU wyłączony)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Nie można użyć tekstury {name} ({reason}); jej materiał pokazuje zastępnik", "The GPU engine refuses this work: {reason}": "Silnik GPU odrzuca to zadanie: {reason}", "The GPU path tracer could not start: {reason}": "Nie udało się uruchomić path tracera GPU: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "Path tracer GPU nie uruchomił się w ciągu {seconds} s; okno pokazuje klatki strumieniowane", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU nie znalazł użytecznego adaptera", "WebGPU in the window": "WebGPU w oknie", "WebGPU in the window is not available": "WebGPU w oknie jest niedostępny", - "WebGPU in the window is turned off": "WebGPU w oknie jest wyłączony" + "WebGPU in the window is turned off": "WebGPU w oknie jest wyłączony", + "{count} textures could not be used; their materials show the fallback": "Nie można użyć tekstur: {count}; ich materiały pokazują zastępnik" } diff --git a/frontend/src/i18n/modules/gpuview/pt-BR.json b/frontend/src/i18n/modules/gpuview/pt-BR.json index 892bdc85..ff778f56 100644 --- a/frontend/src/i18n/modules/gpuview/pt-BR.json +++ b/frontend/src/i18n/modules/gpuview/pt-BR.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Quadros transmitidos (WebGPU desativado)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "A textura {name} não pôde ser usada ({reason}); seu material mostra o substituto", "The GPU engine refuses this work: {reason}": "O motor de GPU recusa este trabalho: {reason}", "The GPU path tracer could not start: {reason}": "O path tracer de GPU não pôde iniciar: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "O path tracer de GPU não iniciou em {seconds} s; a janela mostra quadros transmitidos", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "O WebGPU não encontrou nenhum adaptador utilizável", "WebGPU in the window": "WebGPU na janela", "WebGPU in the window is not available": "O WebGPU na janela não está disponível", - "WebGPU in the window is turned off": "O WebGPU na janela está desativado" + "WebGPU in the window is turned off": "O WebGPU na janela está desativado", + "{count} textures could not be used; their materials show the fallback": "{count} texturas não puderam ser usadas; seus materiais mostram o substituto" } diff --git a/frontend/src/i18n/modules/gpuview/ru.json b/frontend/src/i18n/modules/gpuview/ru.json index 592d2ef0..6a7c1142 100644 --- a/frontend/src/i18n/modules/gpuview/ru.json +++ b/frontend/src/i18n/modules/gpuview/ru.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Потоковые кадры (WebGPU выключен)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Не удалось использовать текстуру {name} ({reason}); её материал показывает запасной вариант", "The GPU engine refuses this work: {reason}": "GPU-движок отказывается от этой задачи: {reason}", "The GPU path tracer could not start: {reason}": "Не удалось запустить GPU-трассировку путей: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU-трассировка путей не запустилась за {seconds} с; окно показывает потоковые кадры", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU не нашёл подходящего адаптера", "WebGPU in the window": "WebGPU в окне", "WebGPU in the window is not available": "WebGPU в окне недоступен", - "WebGPU in the window is turned off": "WebGPU в окне выключен" + "WebGPU in the window is turned off": "WebGPU в окне выключен", + "{count} textures could not be used; their materials show the fallback": "Не удалось использовать текстуры ({count}); их материалы показывают запасной вариант" } diff --git a/frontend/src/i18n/modules/gpuview/strings.json b/frontend/src/i18n/modules/gpuview/strings.json index 42402270..6f4fbd2f 100644 --- a/frontend/src/i18n/modules/gpuview/strings.json +++ b/frontend/src/i18n/modules/gpuview/strings.json @@ -1,5 +1,6 @@ [ "Streamed frames (WebGPU off)", + "Texture {name} could not be used ({reason}); its material shows the fallback", "The GPU engine refuses this work: {reason}", "The GPU path tracer could not start: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames", @@ -15,5 +16,6 @@ "WebGPU in the window", "WebGPU in the window failed earlier in this session: {reason}", "WebGPU in the window is not available", - "WebGPU in the window is turned off" + "WebGPU in the window is turned off", + "{count} textures could not be used; their materials show the fallback" ] diff --git a/frontend/src/i18n/modules/gpuview/sv.json b/frontend/src/i18n/modules/gpuview/sv.json index 14542f28..f520dea4 100644 --- a/frontend/src/i18n/modules/gpuview/sv.json +++ b/frontend/src/i18n/modules/gpuview/sv.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Strömmade bildrutor (WebGPU av)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Texturen {name} kunde inte användas ({reason}); dess material visar reservlösningen", "The GPU engine refuses this work: {reason}": "GPU-motorn avvisar det här arbetet: {reason}", "The GPU path tracer could not start: {reason}": "GPU-path tracern kunde inte starta: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU-path tracern startade inte inom {seconds} s; fönstret visar strömmade bildrutor", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU hittade ingen användbar adapter", "WebGPU in the window": "WebGPU i fönstret", "WebGPU in the window is not available": "WebGPU i fönstret är inte tillgängligt", - "WebGPU in the window is turned off": "WebGPU i fönstret är avstängt" + "WebGPU in the window is turned off": "WebGPU i fönstret är avstängt", + "{count} textures could not be used; their materials show the fallback": "{count} texturer kunde inte användas; deras material visar reservlösningen" } diff --git a/frontend/src/i18n/modules/gpuview/th.json b/frontend/src/i18n/modules/gpuview/th.json index 320daaff..ffc3e5a1 100644 --- a/frontend/src/i18n/modules/gpuview/th.json +++ b/frontend/src/i18n/modules/gpuview/th.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "เฟรมแบบสตรีม (WebGPU ปิดอยู่)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "ไม่สามารถใช้เท็กซ์เจอร์ {name} ได้ ({reason}) แมทีเรียลของเท็กซ์เจอร์นี้จึงแสดงแบบสำรอง", "The GPU engine refuses this work: {reason}": "เอนจิน GPU ปฏิเสธงานนี้: {reason}", "The GPU path tracer could not start: {reason}": "พาธเทรเซอร์ GPU เริ่มทำงานไม่ได้: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "พาธเทรเซอร์ GPU ไม่เริ่มทำงานภายใน {seconds} วินาที หน้าต่างจึงแสดงเฟรมแบบสตรีม", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU ไม่พบอะแดปเตอร์ที่ใช้งานได้", "WebGPU in the window": "WebGPU ในหน้าต่าง", "WebGPU in the window is not available": "WebGPU ในหน้าต่างไม่พร้อมใช้งาน", - "WebGPU in the window is turned off": "WebGPU ในหน้าต่างถูกปิดอยู่" + "WebGPU in the window is turned off": "WebGPU ในหน้าต่างถูกปิดอยู่", + "{count} textures could not be used; their materials show the fallback": "ไม่สามารถใช้เท็กซ์เจอร์ {count} รายการได้ แมทีเรียลของเท็กซ์เจอร์เหล่านั้นจึงแสดงแบบสำรอง" } diff --git a/frontend/src/i18n/modules/gpuview/tr.json b/frontend/src/i18n/modules/gpuview/tr.json index 4b631760..3c84365e 100644 --- a/frontend/src/i18n/modules/gpuview/tr.json +++ b/frontend/src/i18n/modules/gpuview/tr.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Akıtılan kareler (WebGPU kapalı)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "{name} dokusu kullanılamadı ({reason}); malzemesi yedek görünümü gösteriyor", "The GPU engine refuses this work: {reason}": "GPU motoru bu işi reddediyor: {reason}", "The GPU path tracer could not start: {reason}": "GPU path tracer başlatılamadı: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU path tracer {seconds} sn içinde başlamadı; pencere akıtılan kareleri gösteriyor", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU kullanılabilir bir bağdaştırıcı bulamadı", "WebGPU in the window": "Penceredeki WebGPU", "WebGPU in the window is not available": "Penceredeki WebGPU kullanılamıyor", - "WebGPU in the window is turned off": "Penceredeki WebGPU kapalı" + "WebGPU in the window is turned off": "Penceredeki WebGPU kapalı", + "{count} textures could not be used; their materials show the fallback": "{count} doku kullanılamadı; malzemeleri yedek görünümü gösteriyor" } diff --git a/frontend/src/i18n/modules/gpuview/uk.json b/frontend/src/i18n/modules/gpuview/uk.json index c9099661..3ad6598c 100644 --- a/frontend/src/i18n/modules/gpuview/uk.json +++ b/frontend/src/i18n/modules/gpuview/uk.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Потокові кадри (WebGPU вимкнено)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Не вдалося використати текстуру {name} ({reason}); її матеріал показує запасний варіант", "The GPU engine refuses this work: {reason}": "GPU-рушій відмовляється від цієї роботи: {reason}", "The GPU path tracer could not start: {reason}": "GPU path tracer не вдалося запустити: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU path tracer не запустився за {seconds} с; вікно показує потокові кадри", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU не знайшов придатного адаптера", "WebGPU in the window": "WebGPU у вікні", "WebGPU in the window is not available": "WebGPU у вікні недоступний", - "WebGPU in the window is turned off": "WebGPU у вікні вимкнено" + "WebGPU in the window is turned off": "WebGPU у вікні вимкнено", + "{count} textures could not be used; their materials show the fallback": "Не вдалося використати текстури ({count}); їхні матеріали показують запасний варіант" } diff --git a/frontend/src/i18n/modules/gpuview/vi.json b/frontend/src/i18n/modules/gpuview/vi.json index 8f4b2bf9..3b8e7881 100644 --- a/frontend/src/i18n/modules/gpuview/vi.json +++ b/frontend/src/i18n/modules/gpuview/vi.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "Khung hình truyền trực tuyến (WebGPU tắt)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "Không thể dùng kết cấu {name} ({reason}); vật liệu của nó hiển thị bản dự phòng", "The GPU engine refuses this work: {reason}": "Công cụ GPU từ chối tác vụ này: {reason}", "The GPU path tracer could not start: {reason}": "Không thể khởi động path tracer GPU: {reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "Path tracer GPU không khởi động trong {seconds} giây; cửa sổ hiển thị khung hình truyền trực tuyến", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU không tìm thấy bộ điều hợp nào dùng được", "WebGPU in the window": "WebGPU trong cửa sổ", "WebGPU in the window is not available": "WebGPU trong cửa sổ không khả dụng", - "WebGPU in the window is turned off": "WebGPU trong cửa sổ đang tắt" + "WebGPU in the window is turned off": "WebGPU trong cửa sổ đang tắt", + "{count} textures could not be used; their materials show the fallback": "Không thể dùng {count} kết cấu; vật liệu của chúng hiển thị bản dự phòng" } diff --git a/frontend/src/i18n/modules/gpuview/zh-CN.json b/frontend/src/i18n/modules/gpuview/zh-CN.json index ba7d76f5..49b33f5e 100644 --- a/frontend/src/i18n/modules/gpuview/zh-CN.json +++ b/frontend/src/i18n/modules/gpuview/zh-CN.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "流式画面(WebGPU 已关闭)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "纹理 {name} 无法使用({reason});其材质显示备用效果", "The GPU engine refuses this work: {reason}": "GPU 引擎拒绝此任务:{reason}", "The GPU path tracer could not start: {reason}": "GPU 路径追踪器无法启动:{reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU 路径追踪器未能在 {seconds} 秒内启动;窗口显示流式画面", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU 未找到可用的适配器", "WebGPU in the window": "窗口内的 WebGPU", "WebGPU in the window is not available": "窗口内的 WebGPU 不可用", - "WebGPU in the window is turned off": "窗口内的 WebGPU 已关闭" + "WebGPU in the window is turned off": "窗口内的 WebGPU 已关闭", + "{count} textures could not be used; their materials show the fallback": "有 {count} 个纹理无法使用;它们的材质显示备用效果" } diff --git a/frontend/src/i18n/modules/gpuview/zh-TW.json b/frontend/src/i18n/modules/gpuview/zh-TW.json index 4fc08951..718f27af 100644 --- a/frontend/src/i18n/modules/gpuview/zh-TW.json +++ b/frontend/src/i18n/modules/gpuview/zh-TW.json @@ -1,5 +1,6 @@ { "Streamed frames (WebGPU off)": "串流畫面(WebGPU 已關閉)", + "Texture {name} could not be used ({reason}); its material shows the fallback": "紋理 {name} 無法使用({reason});其材質顯示備用效果", "The GPU engine refuses this work: {reason}": "GPU 引擎拒絕此工作:{reason}", "The GPU path tracer could not start: {reason}": "GPU 路徑追蹤器無法啟動:{reason}", "The GPU path tracer did not start within {seconds} s; the window shows streamed frames": "GPU 路徑追蹤器未能在 {seconds} 秒內啟動;視窗顯示串流畫面", @@ -15,5 +16,6 @@ "WebGPU found no usable adapter": "WebGPU 找不到可用的介面卡", "WebGPU in the window": "視窗內的 WebGPU", "WebGPU in the window is not available": "視窗內的 WebGPU 無法使用", - "WebGPU in the window is turned off": "視窗內的 WebGPU 已關閉" + "WebGPU in the window is turned off": "視窗內的 WebGPU 已關閉", + "{count} textures could not be used; their materials show the fallback": "有 {count} 個紋理無法使用;它們的材質顯示備用效果" } diff --git a/frontend/src/i18n/modules/graph/cs.json b/frontend/src/i18n/modules/graph/cs.json new file mode 100644 index 00000000..16158981 --- /dev/null +++ b/frontend/src/i18n/modules/graph/cs.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Graf může obsahovat nejvýše {n} uzlů.", + "A node cannot feed itself.": "Uzel nemůže napájet sám sebe.", + "A {from} output cannot feed a {to} input.": "Výstup typu {from} nelze připojit ke vstupu typu {to}.", + "ACEScg": "ACEScg", + "Add": "Přidat", + "Add a node": "Přidat uzel", + "Add a node at the pointer": "Přidat uzel na místo ukazatele", + "Add an image to a node": "Přidat obrázek k uzlu", + "Add image": "Přidat obrázek", + "Add image...": "Přidat obrázek...", + "Adding images needs the desktop app or a service that stores uploads.": "Přidávání obrázků vyžaduje desktopovou aplikaci nebo službu, která ukládá nahrané soubory.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Pásy", + "Base color": "Základní barva", + "Base diffuse roughness": "Základní drsnost difuze", + "Base metalness": "Základní kovovost", + "Base weight": "Základní váha", + "Bilinear": "Bilineární", + "Box": "Kvádrová", + "Brushed": "Broušený", + "Bump": "Bump", + "C": "C", + "Cell edge": "Okraj buňky", + "Change a node setting": "Změnit nastavení uzlu", + "Change a node value": "Změnit hodnotu uzlu", + "Chebyshev": "Čebyševova", + "Checker": "Šachovnice", + "Clamp": "Oříznutí", + "Click to add a stop": "Kliknutím přidáte bod", + "Close the node editor": "Zavřít editor uzlů", + "Coat color": "Barva laku", + "Coat ior": "IOR laku", + "Coat roughness": "Drsnost laku", + "Coat weight": "Váha laku", + "colour": "barva", + "Colour 1": "Barva 1", + "Colour 2": "Barva 2", + "Colour and maths": "Barva a matematika", + "Colour ramp": "Barevná rampa", + "Colour space": "Barevný prostor", + "Connect": "Připojit", + "Connect an input to an output.": "Připojte vstup k výstupu.", + "Connect an output to an input.": "Připojte výstup ke vstupu.", + "Connect or disconnect": "Připojit nebo odpojit", + "Connect or disconnect the focused node": "Připojit nebo odpojit zaměřený uzel", + "Constant": "Konstanta", + "Copied {n} nodes.": "Zkopírováno uzlů: {n}.", + "Copy the selected nodes": "Kopírovat vybrané uzly", + "Cut the selected nodes": "Vyjmout vybrané uzly", + "Cylindrical": "Válcová", + "Data": "Data", + "Delete stop": "Smazat bod", + "Delete the selected nodes": "Smazat vybrané uzly", + "Density": "Hustota", + "Detail": "Detail", + "Disconnect": "Odpojit", + "Displacement": "Displacement", + "Distance": "Vzdálenost", + "Distortion": "Zkreslení", + "Divide": "Dělení", + "Duplicate the selected nodes": "Duplikovat vybrané uzly", + "Edit the focused node; Escape returns": "Upravit zaměřený uzel; Escape se vrátí zpět", + "Emission color": "Barva emise", + "Euclidean": "Euklidovská", + "Factor": "Faktor", + "Fallback": "Záložní hodnota", + "Feature": "Prvek", + "Filter": "Filtrování", + "Flakes": "Vločky", + "Flip green": "Převrátit zelenou", + "Fractal noise": "Fraktálový šum", + "Frame all nodes": "Zarámovat všechny uzly", + "Fuzz color": "Barva chmýří", + "Fuzz roughness": "Drsnost chmýří", + "Fuzz weight": "Váha chmýří", + "Gain": "Zesílení", + "Geometry opacity": "Neprůhlednost geometrie", + "Go back to the last graph the engine accepted": "Vrátit se k poslednímu grafu, který engine přijal", + "Gradient": "Přechod", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Podržením a tažením posouváte pohled; posouvá ho také tažení prostředním tlačítkem a posun dvěma prsty", + "Image texture": "Obrazová textura", + "Images": "Obrázky", + "Inputs": "Vstupy", + "Interpolation": "Interpolace", + "Invert": "Invertovat", + "Lacunarity": "Lakunarita", + "Length": "Délka", + "Lerp": "Lerp", + "Linear": "Lineární", + "Manhattan": "Manhattan", + "Mapping": "Mapování", + "Marble": "Mramor", + "Mask": "Maska", + "Material output": "Výstup materiálu", + "Math": "Matematika", + "Maximum": "Maximum", + "Metric": "Metrika", + "Minimum": "Minimum", + "Mirror": "Zrcadlení", + "Mix": "Mix", + "Move focus to the nearest node": "Přesunout zaměření na nejbližší uzel", + "Move the selected nodes": "Přesunout vybrané uzly", + "Multiply": "Násobení", + "Nearest": "Nejbližší", + "Nearest point": "Nejbližší bod", + "Node canvas": "Plátno uzlů", + "Node editor": "Editor uzlů", + "Node editor keys": "Klávesy editoru uzlů", + "Node editor: {name}": "Editor uzlů: {name}", + "Noise": "Šum", + "normal": "normála", + "Normal map": "Normálová mapa", + "Not applied: {reason}. The material keeps its last working graph.": "Nepoužito: {reason}. Materiál si ponechá svůj poslední funkční graf.", + "Nothing matches": "Nic neodpovídá", + "Number": "Číslo", + "number": "číslo", + "Octaves": "Oktávy", + "Offset X": "Posun X", + "Offset Y": "Posun Y", + "Operation": "Operace", + "Paste nodes, also into another material": "Vložit uzly, i do jiného materiálu", + "Patterns": "Vzory", + "Phase": "Fáze", + "Planar": "Planární", + "Position": "Pozice", + "Power": "Mocnina", + "Profile": "Profil", + "Projection": "Projekce", + "Quadratic": "Kvadratická", + "Radial": "Radiální", + "Randomness": "Náhodnost", + "Repeat": "Opakování", + "Result": "Výsledek", + "Revert": "Vrátit zpět", + "Rings": "Kroužky", + "Saw": "Pila", + "Scale X": "Měřítko X", + "Scale Y": "Měřítko Y", + "Second nearest": "Druhý nejbližší", + "Seed": "Seed", + "Select every node": "Vybrat všechny uzly", + "Shape": "Tvar", + "Show these keys": "Zobrazit tyto klávesy", + "Sine": "Sinus", + "Space bar": "Mezerník", + "Specular color": "Barva lesku", + "Specular ior": "IOR lesku", + "Specular roughness": "Drsnost lesku", + "Specular roughness anisotropy": "Anizotropie drsnosti lesku", + "Specular weight": "Váha lesku", + "Spherical": "Kulová", + "Spread": "Rozptyl", + "sRGB": "sRGB", + "Stop colour": "Barva bodu", + "Stop position": "Pozice bodu", + "Stop {n} at {pos}": "Bod {n} na pozici {pos}", + "Stops": "Body", + "Strength": "Síla", + "Subtract": "Odečítání", + "Surface": "Povrch", + "That link would make a loop.": "Toto propojení by vytvořilo smyčku.", + "The engine did not add the image.": "Engine obrázek nepřidal.", + "The image could not be stored ({status})": "Obrázek se nepodařilo uložit ({status})", + "The material was removed, so the node editor closed.": "Materiál byl odstraněn, proto se editor uzlů zavřel.", + "The node editor could not open: {reason}": "Editor uzlů se nepodařilo otevřít: {reason}", + "Transmission color": "Barva propustnosti", + "Transmission weight": "Váha propustnosti", + "Triangle": "Trojúhelník", + "Trilinear": "Trilineární", + "Type": "Typ", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Zpět a Znovu používají klávesy aplikace, Mod+Z a Shift+Mod+Z.", + "UV": "UV", + "Value": "Hodnota", + "Vector": "Vektor", + "vector": "vektor", + "Veins": "Žilky", + "Voronoi": "Voronoi", + "Wave": "Vlna", + "Wrap": "Zalamování", + "Zoom in": "Přiblížit", + "Zoom out": "Oddálit", + "Zoom to 100%": "Zvětšit na 100 %", + "{kind} node {id}": "Uzel {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} uzlů, {links} propojení", + "{socket} input, linked from {from}": "Vstup {socket}, propojený z {from}", + "{socket} input, {type}": "Vstup {socket}, {type}", + "{socket} output, {type}": "Výstup {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/da.json b/frontend/src/i18n/modules/graph/da.json new file mode 100644 index 00000000..e1006544 --- /dev/null +++ b/frontend/src/i18n/modules/graph/da.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "En graf rummer højst {n} nodes.", + "A node cannot feed itself.": "En node kan ikke fodre sig selv.", + "A {from} output cannot feed a {to} input.": "Et {from}-output kan ikke fodre et {to}-input.", + "ACEScg": "ACEScg", + "Add": "Læg til", + "Add a node": "Tilføj en node", + "Add a node at the pointer": "Tilføj en node ved markøren", + "Add an image to a node": "Tilføj et billede til en node", + "Add image": "Tilføj billede", + "Add image...": "Tilføj billede...", + "Adding images needs the desktop app or a service that stores uploads.": "Tilføjelse af billeder kræver desktop-appen eller en tjeneste, der gemmer uploads.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Bånd", + "Base color": "Basisfarve", + "Base diffuse roughness": "Diffus basisruhed", + "Base metalness": "Basis-metalness", + "Base weight": "Basisvægt", + "Bilinear": "Bilineær", + "Box": "Boks", + "Brushed": "Børstet", + "Bump": "Bump", + "C": "C", + "Cell edge": "Cellekant", + "Change a node setting": "Ændr en nodeindstilling", + "Change a node value": "Ændr en nodeværdi", + "Chebyshev": "Chebyshev", + "Checker": "Skakbræt", + "Clamp": "Begræns", + "Click to add a stop": "Klik for at tilføje et stop", + "Close the node editor": "Luk nodeeditoren", + "Coat color": "Coatingfarve", + "Coat ior": "Coating-IOR", + "Coat roughness": "Coatingruhed", + "Coat weight": "Coatingvægt", + "colour": "farve", + "Colour 1": "Farve 1", + "Colour 2": "Farve 2", + "Colour and maths": "Farve og matematik", + "Colour ramp": "Farverampe", + "Colour space": "Farverum", + "Connect": "Forbind", + "Connect an input to an output.": "Forbind et input med et output.", + "Connect an output to an input.": "Forbind et output med et input.", + "Connect or disconnect": "Forbind eller afbryd", + "Connect or disconnect the focused node": "Forbind eller afbryd noden med fokus", + "Constant": "Konstant", + "Copied {n} nodes.": "Kopierede {n} nodes.", + "Copy the selected nodes": "Kopiér de valgte nodes", + "Cut the selected nodes": "Klip de valgte nodes", + "Cylindrical": "Cylindrisk", + "Data": "Data", + "Delete stop": "Slet stop", + "Delete the selected nodes": "Slet de valgte nodes", + "Density": "Tæthed", + "Detail": "Detalje", + "Disconnect": "Afbryd", + "Displacement": "Displacement", + "Distance": "Afstand", + "Distortion": "Forvrængning", + "Divide": "Divider", + "Duplicate the selected nodes": "Dupliker de valgte nodes", + "Edit the focused node; Escape returns": "Redigér noden med fokus; Escape vender tilbage", + "Emission color": "Emissionsfarve", + "Euclidean": "Euklidisk", + "Factor": "Faktor", + "Fallback": "Reserveværdi", + "Feature": "Egenskab", + "Filter": "Filter", + "Flakes": "Flager", + "Flip green": "Vend grøn", + "Fractal noise": "Fraktal støj", + "Frame all nodes": "Indram alle nodes", + "Fuzz color": "Fuzz-farve", + "Fuzz roughness": "Fuzz-ruhed", + "Fuzz weight": "Fuzz-vægt", + "Gain": "Forstærkning", + "Geometry opacity": "Geometriopacitet", + "Go back to the last graph the engine accepted": "Gå tilbage til den seneste graf, som motoren accepterede", + "Gradient": "Gradient", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Hold og træk for at panorere; træk med midterknappen og rul med to fingre panorerer også", + "Image texture": "Billedtekstur", + "Images": "Billeder", + "Inputs": "Input", + "Interpolation": "Interpolation", + "Invert": "Inverter", + "Lacunarity": "Lakunaritet", + "Length": "Længde", + "Lerp": "Lerp", + "Linear": "Lineær", + "Manhattan": "Manhattan", + "Mapping": "Mapping", + "Marble": "Marmor", + "Mask": "Maske", + "Material output": "Materialeoutput", + "Math": "Matematik", + "Maximum": "Maksimum", + "Metric": "Metrik", + "Minimum": "Minimum", + "Mirror": "Spejl", + "Mix": "Bland", + "Move focus to the nearest node": "Flyt fokus til den nærmeste node", + "Move the selected nodes": "Flyt de valgte nodes", + "Multiply": "Multiplicer", + "Nearest": "Nærmeste", + "Nearest point": "Nærmeste punkt", + "Node canvas": "Nodecanvas", + "Node editor": "Nodeeditor", + "Node editor keys": "Taster i nodeeditoren", + "Node editor: {name}": "Nodeeditor: {name}", + "Noise": "Støj", + "normal": "normal", + "Normal map": "Normal map", + "Not applied: {reason}. The material keeps its last working graph.": "Ikke anvendt: {reason}. Materialet beholder sin seneste fungerende graf.", + "Nothing matches": "Intet passer", + "Number": "Tal", + "number": "tal", + "Octaves": "Oktaver", + "Offset X": "Forskydning X", + "Offset Y": "Forskydning Y", + "Operation": "Operation", + "Paste nodes, also into another material": "Indsæt nodes, også i et andet materiale", + "Patterns": "Mønstre", + "Phase": "Fase", + "Planar": "Plan", + "Position": "Position", + "Power": "Potens", + "Profile": "Profil", + "Projection": "Projektion", + "Quadratic": "Kvadratisk", + "Radial": "Radial", + "Randomness": "Tilfældighed", + "Repeat": "Gentag", + "Result": "Resultat", + "Revert": "Gendan", + "Rings": "Ringe", + "Saw": "Savtak", + "Scale X": "Skalering X", + "Scale Y": "Skalering Y", + "Second nearest": "Næstnærmeste", + "Seed": "Seed", + "Select every node": "Vælg alle nodes", + "Shape": "Form", + "Show these keys": "Vis disse taster", + "Sine": "Sinus", + "Space bar": "Mellemrumstast", + "Specular color": "Spekulær farve", + "Specular ior": "Spekulær IOR", + "Specular roughness": "Spekulær ruhed", + "Specular roughness anisotropy": "Anisotropi for spekulær ruhed", + "Specular weight": "Spekulær vægt", + "Spherical": "Sfærisk", + "Spread": "Spredning", + "sRGB": "sRGB", + "Stop colour": "Stopfarve", + "Stop position": "Stopposition", + "Stop {n} at {pos}": "Stop {n} ved {pos}", + "Stops": "Stop", + "Strength": "Styrke", + "Subtract": "Subtraher", + "Surface": "Overflade", + "That link would make a loop.": "Den kobling ville skabe en løkke.", + "The engine did not add the image.": "Motoren tilføjede ikke billedet.", + "The image could not be stored ({status})": "Billedet kunne ikke gemmes ({status})", + "The material was removed, so the node editor closed.": "Materialet blev fjernet, så nodeeditoren blev lukket.", + "The node editor could not open: {reason}": "Nodeeditoren kunne ikke åbnes: {reason}", + "Transmission color": "Transmissionsfarve", + "Transmission weight": "Transmissionsvægt", + "Triangle": "Trekant", + "Trilinear": "Trilineær", + "Type": "Type", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Fortryd og gentag bruger appens taster, Mod+Z og Shift+Mod+Z.", + "UV": "UV", + "Value": "Værdi", + "Vector": "Vektor", + "vector": "vektor", + "Veins": "Årer", + "Voronoi": "Voronoi", + "Wave": "Bølge", + "Wrap": "Wrap", + "Zoom in": "Zoom ind", + "Zoom out": "Zoom ud", + "Zoom to 100%": "Zoom til 100%", + "{kind} node {id}": "{kind}-node {id}", + "{nodes} nodes, {links} links": "{nodes} nodes, {links} forbindelser", + "{socket} input, linked from {from}": "{socket}-input, koblet fra {from}", + "{socket} input, {type}": "{socket}-input, {type}", + "{socket} output, {type}": "{socket}-output, {type}" +} diff --git a/frontend/src/i18n/modules/graph/de.json b/frontend/src/i18n/modules/graph/de.json new file mode 100644 index 00000000..ec53efef --- /dev/null +++ b/frontend/src/i18n/modules/graph/de.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Ein Graph enthält höchstens {n} Knoten.", + "A node cannot feed itself.": "Ein Knoten kann sich nicht selbst speisen.", + "A {from} output cannot feed a {to} input.": "Ein Ausgang vom Typ {from} kann keinen Eingang vom Typ {to} speisen.", + "ACEScg": "ACEScg", + "Add": "Addieren", + "Add a node": "Knoten hinzufügen", + "Add a node at the pointer": "Knoten am Zeiger hinzufügen", + "Add an image to a node": "Einem Knoten ein Bild hinzufügen", + "Add image": "Bild hinzufügen", + "Add image...": "Bild hinzufügen ...", + "Adding images needs the desktop app or a service that stores uploads.": "Zum Hinzufügen von Bildern ist die Desktop-App oder ein Dienst nötig, der Uploads speichert.", + "Alpha": "Alpha", + "B": "B", + "Bands": "Bänder", + "Base color": "Basisfarbe", + "Base diffuse roughness": "Diffuse Basisrauheit", + "Base metalness": "Basis-Metallizität", + "Base weight": "Basisgewicht", + "Bilinear": "Bilinear", + "Box": "Box", + "Brushed": "Gebürstet", + "Bump": "Bump", + "C": "C", + "Cell edge": "Zellkante", + "Change a node setting": "Knoteneinstellung ändern", + "Change a node value": "Knotenwert ändern", + "Chebyshev": "Tschebyscheff", + "Checker": "Schachbrett", + "Clamp": "Begrenzen", + "Click to add a stop": "Klicken, um einen Stopp hinzuzufügen", + "Close the node editor": "Knoteneditor schließen", + "Coat color": "Klarlackfarbe", + "Coat ior": "Klarlack-IOR", + "Coat roughness": "Klarlack-Rauheit", + "Coat weight": "Klarlackgewicht", + "colour": "Farbe", + "Colour 1": "Farbe 1", + "Colour 2": "Farbe 2", + "Colour and maths": "Farbe und Mathematik", + "Colour ramp": "Farbverlauf", + "Colour space": "Farbraum", + "Connect": "Verbinden", + "Connect an input to an output.": "Verbinde einen Eingang mit einem Ausgang.", + "Connect an output to an input.": "Verbinde einen Ausgang mit einem Eingang.", + "Connect or disconnect": "Verbinden oder trennen", + "Connect or disconnect the focused node": "Den fokussierten Knoten verbinden oder trennen", + "Constant": "Konstante", + "Copied {n} nodes.": "{n} Knoten kopiert.", + "Copy the selected nodes": "Ausgewählte Knoten kopieren", + "Cut the selected nodes": "Ausgewählte Knoten ausschneiden", + "Cylindrical": "Zylindrisch", + "Data": "Daten", + "Delete stop": "Stopp löschen", + "Delete the selected nodes": "Ausgewählte Knoten löschen", + "Density": "Dichte", + "Detail": "Detail", + "Disconnect": "Trennen", + "Displacement": "Displacement", + "Distance": "Abstand", + "Distortion": "Verzerrung", + "Divide": "Dividieren", + "Duplicate the selected nodes": "Ausgewählte Knoten duplizieren", + "Edit the focused node; Escape returns": "Den fokussierten Knoten bearbeiten; mit Escape zurück", + "Emission color": "Emissionsfarbe", + "Euclidean": "Euklidisch", + "Factor": "Faktor", + "Fallback": "Ersatzwert", + "Feature": "Merkmal", + "Filter": "Filter", + "Flakes": "Flocken", + "Flip green": "Grün invertieren", + "Fractal noise": "Fraktales Rauschen", + "Frame all nodes": "Alle Knoten einpassen", + "Fuzz color": "Flaumfarbe", + "Fuzz roughness": "Flaum-Rauheit", + "Fuzz weight": "Flaumgewicht", + "Gain": "Gain", + "Geometry opacity": "Geometrie-Deckkraft", + "Go back to the last graph the engine accepted": "Zum letzten Graph zurückkehren, den die Engine akzeptiert hat", + "Gradient": "Verlauf", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Halten und ziehen zum Verschieben; Ziehen mit der mittleren Taste und Zwei-Finger-Scrollen verschieben ebenfalls", + "Image texture": "Bildtextur", + "Images": "Bilder", + "Inputs": "Eingänge", + "Interpolation": "Interpolation", + "Invert": "Invertieren", + "Lacunarity": "Lakunarität", + "Length": "Länge", + "Lerp": "Lerp", + "Linear": "Linear", + "Manhattan": "Manhattan", + "Mapping": "Mapping", + "Marble": "Marmor", + "Mask": "Maske", + "Material output": "Materialausgabe", + "Math": "Mathematik", + "Maximum": "Maximum", + "Metric": "Metrik", + "Minimum": "Minimum", + "Mirror": "Spiegel", + "Mix": "Mischen", + "Move focus to the nearest node": "Fokus zum nächsten Knoten verschieben", + "Move the selected nodes": "Ausgewählte Knoten verschieben", + "Multiply": "Multiplizieren", + "Nearest": "Nächster Nachbar", + "Nearest point": "Nächster Punkt", + "Node canvas": "Knotenfläche", + "Node editor": "Knoteneditor", + "Node editor keys": "Tasten des Knoteneditors", + "Node editor: {name}": "Knoteneditor: {name}", + "Noise": "Rauschen", + "normal": "Normale", + "Normal map": "Normal-Map", + "Not applied: {reason}. The material keeps its last working graph.": "Nicht angewendet: {reason}. Das Material behält seinen letzten funktionierenden Graph.", + "Nothing matches": "Keine Treffer", + "Number": "Zahl", + "number": "Zahl", + "Octaves": "Oktaven", + "Offset X": "Versatz X", + "Offset Y": "Versatz Y", + "Operation": "Operation", + "Paste nodes, also into another material": "Knoten einfügen, auch in ein anderes Material", + "Patterns": "Muster", + "Phase": "Phase", + "Planar": "Planar", + "Position": "Position", + "Power": "Potenz", + "Profile": "Profil", + "Projection": "Projektion", + "Quadratic": "Quadratisch", + "Radial": "Radial", + "Randomness": "Zufälligkeit", + "Repeat": "Wiederholen", + "Result": "Ergebnis", + "Revert": "Zurücksetzen", + "Rings": "Ringe", + "Saw": "Sägezahn", + "Scale X": "Skalierung X", + "Scale Y": "Skalierung Y", + "Second nearest": "Zweitnächster", + "Seed": "Startwert", + "Select every node": "Alle Knoten auswählen", + "Shape": "Form", + "Show these keys": "Diese Tasten anzeigen", + "Sine": "Sinus", + "Space bar": "Leertaste", + "Specular color": "Spekularfarbe", + "Specular ior": "Specular-IOR", + "Specular roughness": "Specular-Rauheit", + "Specular roughness anisotropy": "Anisotropie der Specular-Rauheit", + "Specular weight": "Spekulargewicht", + "Spherical": "Sphärisch", + "Spread": "Streuung", + "sRGB": "sRGB", + "Stop colour": "Stoppfarbe", + "Stop position": "Stoppposition", + "Stop {n} at {pos}": "Stopp {n} bei {pos}", + "Stops": "Stopps", + "Strength": "Stärke", + "Subtract": "Subtrahieren", + "Surface": "Oberfläche", + "That link would make a loop.": "Diese Verbindung würde eine Schleife erzeugen.", + "The engine did not add the image.": "Die Engine hat das Bild nicht hinzugefügt.", + "The image could not be stored ({status})": "Das Bild konnte nicht gespeichert werden ({status})", + "The material was removed, so the node editor closed.": "Das Material wurde entfernt, daher wurde der Knoteneditor geschlossen.", + "The node editor could not open: {reason}": "Der Knoteneditor konnte nicht geöffnet werden: {reason}", + "Transmission color": "Transmissionsfarbe", + "Transmission weight": "Transmissionsgewicht", + "Triangle": "Dreieck", + "Trilinear": "Trilinear", + "Type": "Typ", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Rückgängig und Wiederholen nutzen die Tasten der App, Mod+Z und Umschalt+Mod+Z.", + "UV": "UV", + "Value": "Wert", + "Vector": "Vektor", + "vector": "Vektor", + "Veins": "Adern", + "Voronoi": "Voronoi", + "Wave": "Welle", + "Wrap": "Randverhalten", + "Zoom in": "Vergrößern", + "Zoom out": "Verkleinern", + "Zoom to 100%": "Auf 100 % zoomen", + "{kind} node {id}": "{kind}-Knoten {id}", + "{nodes} nodes, {links} links": "{nodes} Knoten, {links} Verbindungen", + "{socket} input, linked from {from}": "Eingang {socket}, verbunden mit {from}", + "{socket} input, {type}": "Eingang {socket}, {type}", + "{socket} output, {type}": "Ausgang {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/es-MX.json b/frontend/src/i18n/modules/graph/es-MX.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/graph/es-MX.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/graph/es.json b/frontend/src/i18n/modules/graph/es.json new file mode 100644 index 00000000..901b402c --- /dev/null +++ b/frontend/src/i18n/modules/graph/es.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Un grafo contiene como máximo {n} nodos.", + "A node cannot feed itself.": "Un nodo no puede alimentarse a sí mismo.", + "A {from} output cannot feed a {to} input.": "Una salida de tipo {from} no puede alimentar una entrada de tipo {to}.", + "ACEScg": "ACEScg", + "Add": "Sumar", + "Add a node": "Añadir un nodo", + "Add a node at the pointer": "Añadir un nodo en el puntero", + "Add an image to a node": "Añadir una imagen a un nodo", + "Add image": "Añadir imagen", + "Add image...": "Añadir imagen...", + "Adding images needs the desktop app or a service that stores uploads.": "Para añadir imágenes hace falta la app de escritorio o un servicio que guarde las subidas.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Bandas", + "Base color": "Color base", + "Base diffuse roughness": "Rugosidad difusa base", + "Base metalness": "Metalicidad base", + "Base weight": "Peso base", + "Bilinear": "Bilineal", + "Box": "Cúbica", + "Brushed": "Cepillado", + "Bump": "Bump", + "C": "C", + "Cell edge": "Borde de celda", + "Change a node setting": "Cambiar un ajuste del nodo", + "Change a node value": "Cambiar un valor del nodo", + "Chebyshev": "Chebyshev", + "Checker": "Damero", + "Clamp": "Extender", + "Click to add a stop": "Haz clic para añadir una parada", + "Close the node editor": "Cerrar el editor de nodos", + "Coat color": "Color del barniz", + "Coat ior": "IOR del barniz", + "Coat roughness": "Rugosidad del barniz", + "Coat weight": "Peso del barniz", + "colour": "color", + "Colour 1": "Color 1", + "Colour 2": "Color 2", + "Colour and maths": "Color y matemáticas", + "Colour ramp": "Rampa de color", + "Colour space": "Espacio de color", + "Connect": "Conectar", + "Connect an input to an output.": "Conecta una entrada a una salida.", + "Connect an output to an input.": "Conecta una salida a una entrada.", + "Connect or disconnect": "Conectar o desconectar", + "Connect or disconnect the focused node": "Conectar o desconectar el nodo enfocado", + "Constant": "Constante", + "Copied {n} nodes.": "Se copiaron {n} nodos.", + "Copy the selected nodes": "Copiar los nodos seleccionados", + "Cut the selected nodes": "Cortar los nodos seleccionados", + "Cylindrical": "Cilíndrica", + "Data": "Datos", + "Delete stop": "Eliminar parada", + "Delete the selected nodes": "Eliminar los nodos seleccionados", + "Density": "Densidad", + "Detail": "Detalle", + "Disconnect": "Desconectar", + "Displacement": "Desplazamiento", + "Distance": "Distancia", + "Distortion": "Distorsión", + "Divide": "Dividir", + "Duplicate the selected nodes": "Duplicar los nodos seleccionados", + "Edit the focused node; Escape returns": "Editar el nodo enfocado; Escape para volver", + "Emission color": "Color de emisión", + "Euclidean": "Euclídea", + "Factor": "Factor", + "Fallback": "Valor de reserva", + "Feature": "Característica", + "Filter": "Filtro", + "Flakes": "Escamas", + "Flip green": "Invertir el verde", + "Fractal noise": "Ruido fractal", + "Frame all nodes": "Encuadrar todos los nodos", + "Fuzz color": "Color de la pelusa", + "Fuzz roughness": "Rugosidad de la pelusa", + "Fuzz weight": "Peso de la pelusa", + "Gain": "Ganancia", + "Geometry opacity": "Opacidad de la geometría", + "Go back to the last graph the engine accepted": "Volver al último grafo que aceptó el motor", + "Gradient": "Degradado", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Mantén pulsado y arrastra para desplazar la vista; el arrastre con el botón central y el desplazamiento con dos dedos también la desplazan", + "Image texture": "Textura de imagen", + "Images": "Imágenes", + "Inputs": "Entradas", + "Interpolation": "Interpolación", + "Invert": "Invertir", + "Lacunarity": "Lacunaridad", + "Length": "Longitud", + "Lerp": "Lerp", + "Linear": "Lineal", + "Manhattan": "Manhattan", + "Mapping": "Mapeo", + "Marble": "Mármol", + "Mask": "Máscara", + "Material output": "Salida del material", + "Math": "Matemáticas", + "Maximum": "Máximo", + "Metric": "Métrica", + "Minimum": "Mínimo", + "Mirror": "Espejo", + "Mix": "Mezclar", + "Move focus to the nearest node": "Mover el foco al nodo más cercano", + "Move the selected nodes": "Mover los nodos seleccionados", + "Multiply": "Multiplicar", + "Nearest": "Más cercano", + "Nearest point": "Punto más cercano", + "Node canvas": "Lienzo de nodos", + "Node editor": "Editor de nodos", + "Node editor keys": "Teclas del editor de nodos", + "Node editor: {name}": "Editor de nodos: {name}", + "Noise": "Ruido", + "normal": "normal", + "Normal map": "Mapa de normales", + "Not applied: {reason}. The material keeps its last working graph.": "No se aplicó: {reason}. El material conserva su último grafo que funcionaba.", + "Nothing matches": "Sin coincidencias", + "Number": "Número", + "number": "número", + "Octaves": "Octavas", + "Offset X": "Desfase X", + "Offset Y": "Desfase Y", + "Operation": "Operación", + "Paste nodes, also into another material": "Pegar nodos, también en otro material", + "Patterns": "Patrones", + "Phase": "Fase", + "Planar": "Plana", + "Position": "Posición", + "Power": "Potencia", + "Profile": "Perfil", + "Projection": "Proyección", + "Quadratic": "Cuadrática", + "Radial": "Radial", + "Randomness": "Aleatoriedad", + "Repeat": "Repetir", + "Result": "Resultado", + "Revert": "Revertir", + "Rings": "Anillos", + "Saw": "Diente de sierra", + "Scale X": "Escala X", + "Scale Y": "Escala Y", + "Second nearest": "Segundo más cercano", + "Seed": "Semilla", + "Select every node": "Seleccionar todos los nodos", + "Shape": "Forma", + "Show these keys": "Mostrar estas teclas", + "Sine": "Senoidal", + "Space bar": "Barra espaciadora", + "Specular color": "Color especular", + "Specular ior": "IOR especular", + "Specular roughness": "Rugosidad especular", + "Specular roughness anisotropy": "Anisotropía de la rugosidad especular", + "Specular weight": "Peso especular", + "Spherical": "Esférica", + "Spread": "Extensión", + "sRGB": "sRGB", + "Stop colour": "Color de la parada", + "Stop position": "Posición de la parada", + "Stop {n} at {pos}": "Parada {n} en {pos}", + "Stops": "Paradas", + "Strength": "Intensidad", + "Subtract": "Restar", + "Surface": "Superficie", + "That link would make a loop.": "Ese enlace crearía un bucle.", + "The engine did not add the image.": "El motor no añadió la imagen.", + "The image could not be stored ({status})": "No se pudo guardar la imagen ({status})", + "The material was removed, so the node editor closed.": "Se eliminó el material, así que el editor de nodos se cerró.", + "The node editor could not open: {reason}": "No se pudo abrir el editor de nodos: {reason}", + "Transmission color": "Color de transmisión", + "Transmission weight": "Peso de transmisión", + "Triangle": "Triangular", + "Trilinear": "Trilineal", + "Type": "Tipo", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Deshacer y rehacer usan las teclas de la app, Mod+Z y Mayús+Mod+Z.", + "UV": "UV", + "Value": "Valor", + "Vector": "Vector", + "vector": "vector", + "Veins": "Vetas", + "Voronoi": "Voronoi", + "Wave": "Onda", + "Wrap": "Modo de repetición", + "Zoom in": "Acercar", + "Zoom out": "Alejar", + "Zoom to 100%": "Zoom al 100 %", + "{kind} node {id}": "Nodo {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} nodos, {links} enlaces", + "{socket} input, linked from {from}": "Entrada {socket}, enlazada desde {from}", + "{socket} input, {type}": "Entrada {socket}, {type}", + "{socket} output, {type}": "Salida {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/fi.json b/frontend/src/i18n/modules/graph/fi.json new file mode 100644 index 00000000..21e4361e --- /dev/null +++ b/frontend/src/i18n/modules/graph/fi.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Graafissa voi olla enintään {n} solmua.", + "A node cannot feed itself.": "Solmu ei voi syöttää itseään.", + "A {from} output cannot feed a {to} input.": "Lähtö tyyppiä {from} ei voi syöttää tuloa tyyppiä {to}.", + "ACEScg": "ACEScg", + "Add": "Lisää", + "Add a node": "Lisää solmu", + "Add a node at the pointer": "Lisää solmu osoittimen kohtaan", + "Add an image to a node": "Lisää kuva solmuun", + "Add image": "Lisää kuva", + "Add image...": "Lisää kuva...", + "Adding images needs the desktop app or a service that stores uploads.": "Kuvien lisääminen vaatii työpöytäsovelluksen tai palvelun, joka tallentaa lähetykset.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Raidat", + "Base color": "Perusväri", + "Base diffuse roughness": "Perusdiffuusin karheus", + "Base metalness": "Perusmetallisuus", + "Base weight": "Peruspaino", + "Bilinear": "Bilineaarinen", + "Box": "Laatikko", + "Brushed": "Harjattu", + "Bump": "Bump", + "C": "C", + "Cell edge": "Solun reuna", + "Change a node setting": "Muuta solmun asetusta", + "Change a node value": "Muuta solmun arvoa", + "Chebyshev": "Tšebyšov", + "Checker": "Shakkiruutu", + "Clamp": "Rajaus", + "Click to add a stop": "Lisää piste napsauttamalla", + "Close the node editor": "Sulje solmueditori", + "Coat color": "Pinnoitteen väri", + "Coat ior": "Pinnoitteen IOR", + "Coat roughness": "Pinnoitteen karheus", + "Coat weight": "Pinnoitteen paino", + "colour": "väri", + "Colour 1": "Väri 1", + "Colour 2": "Väri 2", + "Colour and maths": "Väri ja matematiikka", + "Colour ramp": "Väriliuku", + "Colour space": "Väriavaruus", + "Connect": "Yhdistä", + "Connect an input to an output.": "Yhdistä tulo lähtöön.", + "Connect an output to an input.": "Yhdistä lähtö tuloon.", + "Connect or disconnect": "Yhdistä tai katkaise", + "Connect or disconnect the focused node": "Yhdistä tai katkaise kohdistettu solmu", + "Constant": "Vakio", + "Copied {n} nodes.": "{n} solmua kopioitu.", + "Copy the selected nodes": "Kopioi valitut solmut", + "Cut the selected nodes": "Leikkaa valitut solmut", + "Cylindrical": "Sylinterimäinen", + "Data": "Data", + "Delete stop": "Poista piste", + "Delete the selected nodes": "Poista valitut solmut", + "Density": "Tiheys", + "Detail": "Yksityiskohdat", + "Disconnect": "Katkaise", + "Displacement": "Siirtymä", + "Distance": "Etäisyys", + "Distortion": "Vääristymä", + "Divide": "Jaa", + "Duplicate the selected nodes": "Monista valitut solmut", + "Edit the focused node; Escape returns": "Muokkaa kohdistettua solmua; Escape palaa takaisin", + "Emission color": "Emissioväri", + "Euclidean": "Euklidinen", + "Factor": "Kerroin", + "Fallback": "Varaarvo", + "Feature": "Piirre", + "Filter": "Suodatus", + "Flakes": "Hiutaleet", + "Flip green": "Käännä vihreä", + "Fractal noise": "Fraktaalikohina", + "Frame all nodes": "Rajaa kaikki solmut näkyviin", + "Fuzz color": "Nukan väri", + "Fuzz roughness": "Nukan karheus", + "Fuzz weight": "Nukan paino", + "Gain": "Vahvistus", + "Geometry opacity": "Geometrian peittävyys", + "Go back to the last graph the engine accepted": "Palaa viimeisimpään graafiin, jonka moottori hyväksyi", + "Gradient": "Liukuväri", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Pidä pohjassa ja vedä panoroidaksesi; myös keskipainikkeella vetäminen ja kahden sormen vieritys panoroivat", + "Image texture": "Kuvatekstuuri", + "Images": "Kuvat", + "Inputs": "Tulot", + "Interpolation": "Interpolointi", + "Invert": "Käännä", + "Lacunarity": "Lakunariteetti", + "Length": "Pituus", + "Lerp": "Lerp", + "Linear": "Lineaarinen", + "Manhattan": "Manhattan", + "Mapping": "Kartoitus", + "Marble": "Marmori", + "Mask": "Maski", + "Material output": "Materiaalin lähtö", + "Math": "Matematiikka", + "Maximum": "Maksimi", + "Metric": "Mittari", + "Minimum": "Minimi", + "Mirror": "Peilaus", + "Mix": "Sekoita", + "Move focus to the nearest node": "Siirrä kohdistus lähimpään solmuun", + "Move the selected nodes": "Siirrä valitut solmut", + "Multiply": "Kerro", + "Nearest": "Lähin", + "Nearest point": "Lähin piste", + "Node canvas": "Solmukangas", + "Node editor": "Solmueditori", + "Node editor keys": "Solmueditorin näppäimet", + "Node editor: {name}": "Solmueditori: {name}", + "Noise": "Kohina", + "normal": "normaali", + "Normal map": "Normaalikartta", + "Not applied: {reason}. The material keeps its last working graph.": "Ei otettu käyttöön: {reason}. Materiaali säilyttää viimeisimmän toimivan graafinsa.", + "Nothing matches": "Mikään ei täsmää", + "Number": "Luku", + "number": "luku", + "Octaves": "Oktaavit", + "Offset X": "Siirto X", + "Offset Y": "Siirto Y", + "Operation": "Toiminto", + "Paste nodes, also into another material": "Liitä solmut, myös toiseen materiaaliin", + "Patterns": "Kuviot", + "Phase": "Vaihe", + "Planar": "Tasomainen", + "Position": "Sijainti", + "Power": "Potenssi", + "Profile": "Profiili", + "Projection": "Projektio", + "Quadratic": "Neliöllinen", + "Radial": "Säteittäinen", + "Randomness": "Satunnaisuus", + "Repeat": "Toisto", + "Result": "Tulos", + "Revert": "Palauta", + "Rings": "Renkaat", + "Saw": "Saha", + "Scale X": "Skaalaus X", + "Scale Y": "Skaalaus Y", + "Second nearest": "Toiseksi lähin", + "Seed": "Siemen", + "Select every node": "Valitse kaikki solmut", + "Shape": "Muoto", + "Show these keys": "Näytä nämä näppäimet", + "Sine": "Sini", + "Space bar": "Välilyönti", + "Specular color": "Kiillon väri", + "Specular ior": "Kiillon IOR", + "Specular roughness": "Kiillon karheus", + "Specular roughness anisotropy": "Kiillon karheuden anisotropia", + "Specular weight": "Kiillon paino", + "Spherical": "Pallomainen", + "Spread": "Leviäminen", + "sRGB": "sRGB", + "Stop colour": "Pisteen väri", + "Stop position": "Pisteen sijainti", + "Stop {n} at {pos}": "Piste {n} kohdassa {pos}", + "Stops": "Pisteet", + "Strength": "Voimakkuus", + "Subtract": "Vähennä", + "Surface": "Pinta", + "That link would make a loop.": "Tuo yhteys muodostaisi silmukan.", + "The engine did not add the image.": "Moottori ei lisännyt kuvaa.", + "The image could not be stored ({status})": "Kuvaa ei voitu tallentaa ({status})", + "The material was removed, so the node editor closed.": "Materiaali poistettiin, joten solmueditori sulkeutui.", + "The node editor could not open: {reason}": "Solmueditoria ei voitu avata: {reason}", + "Transmission color": "Läpäisyn väri", + "Transmission weight": "Läpäisyn paino", + "Triangle": "Kolmio", + "Trilinear": "Trilineaarinen", + "Type": "Tyyppi", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Kumoa ja Tee uudelleen käyttävät sovelluksen näppäimiä, Mod+Z ja Shift+Mod+Z.", + "UV": "UV", + "Value": "Arvo", + "Vector": "Vektori", + "vector": "vektori", + "Veins": "Suonet", + "Voronoi": "Voronoi", + "Wave": "Aalto", + "Wrap": "Kääre", + "Zoom in": "Lähennä", + "Zoom out": "Loitonna", + "Zoom to 100%": "Zoomaa 100 %:iin", + "{kind} node {id}": "Solmu {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} solmua, {links} yhteyttä", + "{socket} input, linked from {from}": "Tulo {socket}, yhdistetty kohteesta {from}", + "{socket} input, {type}": "Tulo {socket}, {type}", + "{socket} output, {type}": "Lähtö {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/fr-CA.json b/frontend/src/i18n/modules/graph/fr-CA.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/graph/fr-CA.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/graph/fr.json b/frontend/src/i18n/modules/graph/fr.json new file mode 100644 index 00000000..d85834a7 --- /dev/null +++ b/frontend/src/i18n/modules/graph/fr.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Un graphe contient au plus {n} nœuds.", + "A node cannot feed itself.": "Un nœud ne peut pas s'alimenter lui-même.", + "A {from} output cannot feed a {to} input.": "Une sortie de type {from} ne peut pas alimenter une entrée de type {to}.", + "ACEScg": "ACEScg", + "Add": "Additionner", + "Add a node": "Ajouter un nœud", + "Add a node at the pointer": "Ajouter un nœud au pointeur", + "Add an image to a node": "Ajouter une image à un nœud", + "Add image": "Ajouter une image", + "Add image...": "Ajouter une image...", + "Adding images needs the desktop app or a service that stores uploads.": "Pour ajouter des images, il faut l'application de bureau ou un service qui conserve les téléversements.", + "Alpha": "Alpha", + "B": "B", + "Bands": "Bandes", + "Base color": "Couleur de base", + "Base diffuse roughness": "Rugosité diffuse de base", + "Base metalness": "Métallicité de base", + "Base weight": "Poids de base", + "Bilinear": "Bilinéaire", + "Box": "Cubique", + "Brushed": "Brossé", + "Bump": "Bump", + "C": "C", + "Cell edge": "Arête de cellule", + "Change a node setting": "Modifier un réglage de nœud", + "Change a node value": "Modifier une valeur de nœud", + "Chebyshev": "Tchebychev", + "Checker": "Damier", + "Clamp": "Étendre", + "Click to add a stop": "Cliquez pour ajouter un marqueur", + "Close the node editor": "Fermer l'éditeur de nœuds", + "Coat color": "Couleur du vernis", + "Coat ior": "IOR du vernis", + "Coat roughness": "Rugosité du vernis", + "Coat weight": "Poids du vernis", + "colour": "couleur", + "Colour 1": "Couleur 1", + "Colour 2": "Couleur 2", + "Colour and maths": "Couleur et maths", + "Colour ramp": "Rampe de couleurs", + "Colour space": "Espace colorimétrique", + "Connect": "Connecter", + "Connect an input to an output.": "Connectez une entrée à une sortie.", + "Connect an output to an input.": "Connectez une sortie à une entrée.", + "Connect or disconnect": "Connecter ou déconnecter", + "Connect or disconnect the focused node": "Connecter ou déconnecter le nœud ciblé", + "Constant": "Constante", + "Copied {n} nodes.": "{n} nœuds copiés.", + "Copy the selected nodes": "Copier les nœuds sélectionnés", + "Cut the selected nodes": "Couper les nœuds sélectionnés", + "Cylindrical": "Cylindrique", + "Data": "Données", + "Delete stop": "Supprimer le marqueur", + "Delete the selected nodes": "Supprimer les nœuds sélectionnés", + "Density": "Densité", + "Detail": "Détail", + "Disconnect": "Déconnecter", + "Displacement": "Déplacement", + "Distance": "Distance", + "Distortion": "Distorsion", + "Divide": "Diviser", + "Duplicate the selected nodes": "Dupliquer les nœuds sélectionnés", + "Edit the focused node; Escape returns": "Modifier le nœud ciblé ; Échap pour revenir", + "Emission color": "Couleur d'émission", + "Euclidean": "Euclidienne", + "Factor": "Facteur", + "Fallback": "Valeur de repli", + "Feature": "Caractéristique", + "Filter": "Filtre", + "Flakes": "Paillettes", + "Flip green": "Inverser le vert", + "Fractal noise": "Bruit fractal", + "Frame all nodes": "Cadrer tous les nœuds", + "Fuzz color": "Couleur du duvet", + "Fuzz roughness": "Rugosité du duvet", + "Fuzz weight": "Poids du duvet", + "Gain": "Gain", + "Geometry opacity": "Opacité de la géométrie", + "Go back to the last graph the engine accepted": "Revenir au dernier graphe accepté par le moteur", + "Gradient": "Dégradé", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Maintenez et faites glisser pour déplacer la vue ; le glissement avec le bouton central et le défilement à deux doigts la déplacent aussi", + "Image texture": "Texture d'image", + "Images": "Images", + "Inputs": "Entrées", + "Interpolation": "Interpolation", + "Invert": "Inverser", + "Lacunarity": "Lacunarité", + "Length": "Longueur", + "Lerp": "Lerp", + "Linear": "Linéaire", + "Manhattan": "Manhattan", + "Mapping": "Mappage", + "Marble": "Marbre", + "Mask": "Masque", + "Material output": "Sortie du matériau", + "Math": "Maths", + "Maximum": "Maximum", + "Metric": "Métrique", + "Minimum": "Minimum", + "Mirror": "Miroir", + "Mix": "Mélanger", + "Move focus to the nearest node": "Déplacer le focus vers le nœud le plus proche", + "Move the selected nodes": "Déplacer les nœuds sélectionnés", + "Multiply": "Multiplier", + "Nearest": "Plus proche voisin", + "Nearest point": "Point le plus proche", + "Node canvas": "Canevas de nœuds", + "Node editor": "Éditeur de nœuds", + "Node editor keys": "Touches de l'éditeur de nœuds", + "Node editor: {name}": "Éditeur de nœuds : {name}", + "Noise": "Bruit", + "normal": "normale", + "Normal map": "Normal map", + "Not applied: {reason}. The material keeps its last working graph.": "Non appliqué : {reason}. Le matériau conserve son dernier graphe fonctionnel.", + "Nothing matches": "Aucune correspondance", + "Number": "Nombre", + "number": "nombre", + "Octaves": "Octaves", + "Offset X": "Décalage X", + "Offset Y": "Décalage Y", + "Operation": "Opération", + "Paste nodes, also into another material": "Coller des nœuds, y compris dans un autre matériau", + "Patterns": "Motifs", + "Phase": "Phase", + "Planar": "Planaire", + "Position": "Position", + "Power": "Puissance", + "Profile": "Profil", + "Projection": "Projection", + "Quadratic": "Quadratique", + "Radial": "Radial", + "Randomness": "Aléa", + "Repeat": "Répéter", + "Result": "Résultat", + "Revert": "Rétablir", + "Rings": "Anneaux", + "Saw": "Dents de scie", + "Scale X": "Échelle X", + "Scale Y": "Échelle Y", + "Second nearest": "Deuxième plus proche", + "Seed": "Graine", + "Select every node": "Sélectionner tous les nœuds", + "Shape": "Forme", + "Show these keys": "Afficher ces touches", + "Sine": "Sinusoïde", + "Space bar": "Barre d'espace", + "Specular color": "Couleur spéculaire", + "Specular ior": "IOR spéculaire", + "Specular roughness": "Rugosité spéculaire", + "Specular roughness anisotropy": "Anisotropie de la rugosité spéculaire", + "Specular weight": "Poids spéculaire", + "Spherical": "Sphérique", + "Spread": "Étalement", + "sRGB": "sRGB", + "Stop colour": "Couleur du marqueur", + "Stop position": "Position du marqueur", + "Stop {n} at {pos}": "Marqueur {n} à {pos}", + "Stops": "Marqueurs", + "Strength": "Intensité", + "Subtract": "Soustraire", + "Surface": "Surface", + "That link would make a loop.": "Ce lien créerait une boucle.", + "The engine did not add the image.": "Le moteur n'a pas ajouté l'image.", + "The image could not be stored ({status})": "L'image n'a pas pu être enregistrée ({status})", + "The material was removed, so the node editor closed.": "Le matériau a été supprimé, l'éditeur de nœuds s'est donc fermé.", + "The node editor could not open: {reason}": "Impossible d'ouvrir l'éditeur de nœuds : {reason}", + "Transmission color": "Couleur de transmission", + "Transmission weight": "Poids de transmission", + "Triangle": "Triangle", + "Trilinear": "Trilinéaire", + "Type": "Type", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Annuler et rétablir utilisent les touches de l'application, Mod+Z et Maj+Mod+Z.", + "UV": "UV", + "Value": "Valeur", + "Vector": "Vecteur", + "vector": "vecteur", + "Veins": "Veines", + "Voronoi": "Voronoï", + "Wave": "Onde", + "Wrap": "Mode de répétition", + "Zoom in": "Zoom avant", + "Zoom out": "Zoom arrière", + "Zoom to 100%": "Zoom à 100 %", + "{kind} node {id}": "Nœud {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} nœuds, {links} liens", + "{socket} input, linked from {from}": "Entrée {socket}, liée à {from}", + "{socket} input, {type}": "Entrée {socket}, {type}", + "{socket} output, {type}": "Sortie {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/hu.json b/frontend/src/i18n/modules/graph/hu.json new file mode 100644 index 00000000..95e929cd --- /dev/null +++ b/frontend/src/i18n/modules/graph/hu.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Egy gráf legfeljebb {n} csomópontot tartalmazhat.", + "A node cannot feed itself.": "Egy csomópont nem táplálhatja önmagát.", + "A {from} output cannot feed a {to} input.": "{from} típusú kimenet nem csatlakoztatható {to} típusú bemenetre.", + "ACEScg": "ACEScg", + "Add": "Hozzáadás", + "Add a node": "Csomópont hozzáadása", + "Add a node at the pointer": "Csomópont hozzáadása a mutatónál", + "Add an image to a node": "Kép hozzáadása a csomóponthoz", + "Add image": "Kép hozzáadása", + "Add image...": "Kép hozzáadása...", + "Adding images needs the desktop app or a service that stores uploads.": "A képek hozzáadásához az asztali alkalmazás vagy a feltöltéseket tároló szolgáltatás szükséges.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Sávok", + "Base color": "Alapszín", + "Base diffuse roughness": "Alap diffúz érdesség", + "Base metalness": "Alap fémesség", + "Base weight": "Alapsúly", + "Bilinear": "Bilineáris", + "Box": "Doboz", + "Brushed": "Szálcsiszolt", + "Bump": "Bump", + "C": "C", + "Cell edge": "Cellahatár", + "Change a node setting": "Csomópont beállításának módosítása", + "Change a node value": "Csomópont értékének módosítása", + "Chebyshev": "Csebisev", + "Checker": "Sakktábla", + "Clamp": "Rögzítés", + "Click to add a stop": "Kattintson pont hozzáadásához", + "Close the node editor": "Csomópontszerkesztő bezárása", + "Coat color": "Lakkréteg színe", + "Coat ior": "Lakkréteg IOR", + "Coat roughness": "Lakkréteg érdessége", + "Coat weight": "Lakkréteg súlya", + "colour": "szín", + "Colour 1": "Szín 1", + "Colour 2": "Szín 2", + "Colour and maths": "Szín és matematika", + "Colour ramp": "Színátmenet-sáv", + "Colour space": "Színtér", + "Connect": "Csatlakoztatás", + "Connect an input to an output.": "Csatlakoztasson egy bemenetet egy kimenethez.", + "Connect an output to an input.": "Csatlakoztasson egy kimenetet egy bemenethez.", + "Connect or disconnect": "Csatlakoztatás vagy leválasztás", + "Connect or disconnect the focused node": "A fókuszban lévő csomópont csatlakoztatása vagy leválasztása", + "Constant": "Konstans", + "Copied {n} nodes.": "{n} csomópont átmásolva.", + "Copy the selected nodes": "A kijelölt csomópontok másolása", + "Cut the selected nodes": "A kijelölt csomópontok kivágása", + "Cylindrical": "Henger", + "Data": "Adat", + "Delete stop": "Pont törlése", + "Delete the selected nodes": "A kijelölt csomópontok törlése", + "Density": "Sűrűség", + "Detail": "Részletesség", + "Disconnect": "Leválasztás", + "Displacement": "Elmozdítás", + "Distance": "Távolság", + "Distortion": "Torzítás", + "Divide": "Osztás", + "Duplicate the selected nodes": "A kijelölt csomópontok duplikálása", + "Edit the focused node; Escape returns": "A fókuszban lévő csomópont szerkesztése; az Escape visszalép", + "Emission color": "Emisszió színe", + "Euclidean": "Euklideszi", + "Factor": "Tényező", + "Fallback": "Tartalékérték", + "Feature": "Jellemző", + "Filter": "Szűrés", + "Flakes": "Pelyhek", + "Flip green": "Zöld megfordítása", + "Fractal noise": "Fraktálzaj", + "Frame all nodes": "Az összes csomópont kadrírozása", + "Fuzz color": "Pihe színe", + "Fuzz roughness": "Pihe érdessége", + "Fuzz weight": "Pihe súlya", + "Gain": "Erősítés", + "Geometry opacity": "Geometria átlátszatlansága", + "Go back to the last graph the engine accepted": "Visszatérés az utolsó gráfhoz, amelyet a motor elfogadott", + "Gradient": "Színátmenet", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Tartsa lenyomva és húzza a pásztázáshoz; a középső gombbal húzás és a kétujjas görgetés is pásztáz", + "Image texture": "Képtextúra", + "Images": "Képek", + "Inputs": "Bemenetek", + "Interpolation": "Interpoláció", + "Invert": "Invertálás", + "Lacunarity": "Lakunaritás", + "Length": "Hossz", + "Lerp": "Lerp", + "Linear": "Lineáris", + "Manhattan": "Manhattan", + "Mapping": "Leképezés", + "Marble": "Márvány", + "Mask": "Maszk", + "Material output": "Anyag kimenete", + "Math": "Matematika", + "Maximum": "Maximum", + "Metric": "Metrika", + "Minimum": "Minimum", + "Mirror": "Tükrözés", + "Mix": "Keverés", + "Move focus to the nearest node": "A fókusz áthelyezése a legközelebbi csomópontra", + "Move the selected nodes": "A kijelölt csomópontok áthelyezése", + "Multiply": "Szorzás", + "Nearest": "Legközelebbi", + "Nearest point": "Legközelebbi pont", + "Node canvas": "Csomópont-vászon", + "Node editor": "Csomópontszerkesztő", + "Node editor keys": "A csomópontszerkesztő billentyűi", + "Node editor: {name}": "Csomópontszerkesztő: {name}", + "Noise": "Zaj", + "normal": "normál", + "Normal map": "Normáltérkép", + "Not applied: {reason}. The material keeps its last working graph.": "Nem lett alkalmazva: {reason}. Az anyag megtartja az utolsó működő gráfját.", + "Nothing matches": "Nincs találat", + "Number": "Szám", + "number": "szám", + "Octaves": "Oktávok", + "Offset X": "Eltolás X", + "Offset Y": "Eltolás Y", + "Operation": "Művelet", + "Paste nodes, also into another material": "Csomópontok beillesztése, akár másik anyagba is", + "Patterns": "Minták", + "Phase": "Fázis", + "Planar": "Síkbeli", + "Position": "Pozíció", + "Power": "Hatvány", + "Profile": "Profil", + "Projection": "Vetítés", + "Quadratic": "Négyzetes", + "Radial": "Radiális", + "Randomness": "Véletlenszerűség", + "Repeat": "Ismétlés", + "Result": "Eredmény", + "Revert": "Visszaállítás", + "Rings": "Gyűrűk", + "Saw": "Fűrész", + "Scale X": "Méretezés X", + "Scale Y": "Méretezés Y", + "Second nearest": "Második legközelebbi", + "Seed": "Mag", + "Select every node": "Az összes csomópont kijelölése", + "Shape": "Alak", + "Show these keys": "Ezen billentyűk megjelenítése", + "Sine": "Szinusz", + "Space bar": "Szóköz", + "Specular color": "Spekuláris szín", + "Specular ior": "Spekuláris IOR", + "Specular roughness": "Spekuláris érdesség", + "Specular roughness anisotropy": "Spekuláris érdesség anizotrópiája", + "Specular weight": "Spekuláris súly", + "Spherical": "Gömb", + "Spread": "Szórás", + "sRGB": "sRGB", + "Stop colour": "Pont színe", + "Stop position": "Pont pozíciója", + "Stop {n} at {pos}": "{n}. pont: {pos}", + "Stops": "Pontok", + "Strength": "Erősség", + "Subtract": "Kivonás", + "Surface": "Felület", + "That link would make a loop.": "Ez a kapcsolat hurkot hozna létre.", + "The engine did not add the image.": "A motor nem adta hozzá a képet.", + "The image could not be stored ({status})": "A képet nem sikerült eltárolni ({status})", + "The material was removed, so the node editor closed.": "Az anyag el lett távolítva, ezért a csomópontszerkesztő bezárult.", + "The node editor could not open: {reason}": "A csomópontszerkesztőt nem sikerült megnyitni: {reason}", + "Transmission color": "Áteresztés színe", + "Transmission weight": "Áteresztés súlya", + "Triangle": "Háromszög", + "Trilinear": "Trilineáris", + "Type": "Típus", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "A Visszavonás és az Újra az alkalmazás billentyűit használja: Mod+Z és Shift+Mod+Z.", + "UV": "UV", + "Value": "Érték", + "Vector": "Vektor", + "vector": "vektor", + "Veins": "Erek", + "Voronoi": "Voronoi", + "Wave": "Hullám", + "Wrap": "Burkolás", + "Zoom in": "Nagyítás", + "Zoom out": "Kicsinyítés", + "Zoom to 100%": "Nagyítás 100%-ra", + "{kind} node {id}": "{kind} csomópont {id}", + "{nodes} nodes, {links} links": "{nodes} csomópont, {links} kapcsolat", + "{socket} input, linked from {from}": "{socket} bemenet, csatlakoztatva innen: {from}", + "{socket} input, {type}": "{socket} bemenet, {type}", + "{socket} output, {type}": "{socket} kimenet, {type}" +} diff --git a/frontend/src/i18n/modules/graph/id.json b/frontend/src/i18n/modules/graph/id.json new file mode 100644 index 00000000..9089d95f --- /dev/null +++ b/frontend/src/i18n/modules/graph/id.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Graf menampung paling banyak {n} node.", + "A node cannot feed itself.": "Sebuah node tidak dapat mengisi dirinya sendiri.", + "A {from} output cannot feed a {to} input.": "Output {from} tidak dapat mengisi input {to}.", + "ACEScg": "ACEScg", + "Add": "Tambah", + "Add a node": "Tambah node", + "Add a node at the pointer": "Tambah node di penunjuk", + "Add an image to a node": "Tambah gambar ke node", + "Add image": "Tambah gambar", + "Add image...": "Tambah gambar...", + "Adding images needs the desktop app or a service that stores uploads.": "Menambah gambar memerlukan aplikasi desktop atau layanan yang menyimpan unggahan.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Pita", + "Base color": "Warna dasar", + "Base diffuse roughness": "Roughness diffuse dasar", + "Base metalness": "Metalness dasar", + "Base weight": "Bobot dasar", + "Bilinear": "Bilinear", + "Box": "Kotak", + "Brushed": "Sikat", + "Bump": "Bump", + "C": "C", + "Cell edge": "Tepi sel", + "Change a node setting": "Ubah pengaturan node", + "Change a node value": "Ubah nilai node", + "Chebyshev": "Chebyshev", + "Checker": "Kotak-kotak", + "Clamp": "Jepit", + "Click to add a stop": "Klik untuk menambah titik henti", + "Close the node editor": "Tutup editor node", + "Coat color": "Warna coat", + "Coat ior": "IOR coat", + "Coat roughness": "Roughness coat", + "Coat weight": "Bobot coat", + "colour": "warna", + "Colour 1": "Warna 1", + "Colour 2": "Warna 2", + "Colour and maths": "Warna dan matematika", + "Colour ramp": "Ramp warna", + "Colour space": "Ruang warna", + "Connect": "Hubungkan", + "Connect an input to an output.": "Hubungkan input ke output.", + "Connect an output to an input.": "Hubungkan output ke input.", + "Connect or disconnect": "Hubungkan atau putuskan", + "Connect or disconnect the focused node": "Hubungkan atau putuskan node yang difokuskan", + "Constant": "Konstan", + "Copied {n} nodes.": "{n} node disalin.", + "Copy the selected nodes": "Salin node terpilih", + "Cut the selected nodes": "Potong node terpilih", + "Cylindrical": "Silinder", + "Data": "Data", + "Delete stop": "Hapus titik henti", + "Delete the selected nodes": "Hapus node terpilih", + "Density": "Kerapatan", + "Detail": "Detail", + "Disconnect": "Putuskan", + "Displacement": "Displacement", + "Distance": "Jarak", + "Distortion": "Distorsi", + "Divide": "Bagi", + "Duplicate the selected nodes": "Duplikat node terpilih", + "Edit the focused node; Escape returns": "Sunting node yang difokuskan; Escape untuk kembali", + "Emission color": "Warna emisi", + "Euclidean": "Euclidean", + "Factor": "Faktor", + "Fallback": "Cadangan", + "Feature": "Fitur", + "Filter": "Filter", + "Flakes": "Serpihan", + "Flip green": "Balik hijau", + "Fractal noise": "Noise fraktal", + "Frame all nodes": "Bingkai semua node", + "Fuzz color": "Warna fuzz", + "Fuzz roughness": "Roughness fuzz", + "Fuzz weight": "Bobot fuzz", + "Gain": "Gain", + "Geometry opacity": "Opasitas geometri", + "Go back to the last graph the engine accepted": "Kembali ke graf terakhir yang diterima mesin", + "Gradient": "Gradien", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Tahan dan seret untuk menggeser; seret tombol tengah dan gulir dua jari juga menggeser", + "Image texture": "Tekstur gambar", + "Images": "Gambar", + "Inputs": "Input", + "Interpolation": "Interpolasi", + "Invert": "Balikkan", + "Lacunarity": "Lacunarity", + "Length": "Panjang", + "Lerp": "Lerp", + "Linear": "Linear", + "Manhattan": "Manhattan", + "Mapping": "Pemetaan", + "Marble": "Marmer", + "Mask": "Mask", + "Material output": "Output material", + "Math": "Matematika", + "Maximum": "Maksimum", + "Metric": "Metrik", + "Minimum": "Minimum", + "Mirror": "Cermin", + "Mix": "Campur", + "Move focus to the nearest node": "Pindahkan fokus ke node terdekat", + "Move the selected nodes": "Pindahkan node terpilih", + "Multiply": "Kali", + "Nearest": "Terdekat", + "Nearest point": "Titik terdekat", + "Node canvas": "Kanvas node", + "Node editor": "Editor node", + "Node editor keys": "Tombol editor node", + "Node editor: {name}": "Editor node: {name}", + "Noise": "Noise", + "normal": "normal", + "Normal map": "Normal map", + "Not applied: {reason}. The material keeps its last working graph.": "Tidak diterapkan: {reason}. Material mempertahankan graf terakhirnya yang berfungsi.", + "Nothing matches": "Tidak ada yang cocok", + "Number": "Angka", + "number": "angka", + "Octaves": "Oktaf", + "Offset X": "Offset X", + "Offset Y": "Offset Y", + "Operation": "Operasi", + "Paste nodes, also into another material": "Tempel node, juga ke material lain", + "Patterns": "Pola", + "Phase": "Fase", + "Planar": "Planar", + "Position": "Posisi", + "Power": "Pangkat", + "Profile": "Profil", + "Projection": "Proyeksi", + "Quadratic": "Kuadratik", + "Radial": "Radial", + "Randomness": "Keacakan", + "Repeat": "Ulangi", + "Result": "Hasil", + "Revert": "Kembalikan", + "Rings": "Cincin", + "Saw": "Gigi gergaji", + "Scale X": "Skala X", + "Scale Y": "Skala Y", + "Second nearest": "Terdekat kedua", + "Seed": "Seed", + "Select every node": "Pilih semua node", + "Shape": "Bentuk", + "Show these keys": "Tampilkan tombol ini", + "Sine": "Sinus", + "Space bar": "Spasi", + "Specular color": "Warna specular", + "Specular ior": "IOR specular", + "Specular roughness": "Roughness specular", + "Specular roughness anisotropy": "Anisotropi roughness specular", + "Specular weight": "Bobot specular", + "Spherical": "Bola", + "Spread": "Sebaran", + "sRGB": "sRGB", + "Stop colour": "Warna titik henti", + "Stop position": "Posisi titik henti", + "Stop {n} at {pos}": "Titik henti {n} di {pos}", + "Stops": "Titik henti", + "Strength": "Kekuatan", + "Subtract": "Kurangi", + "Surface": "Permukaan", + "That link would make a loop.": "Tautan itu akan membentuk putaran.", + "The engine did not add the image.": "Mesin tidak menambahkan gambar.", + "The image could not be stored ({status})": "Gambar tidak dapat disimpan ({status})", + "The material was removed, so the node editor closed.": "Material dihapus, sehingga editor node ditutup.", + "The node editor could not open: {reason}": "Editor node tidak dapat dibuka: {reason}", + "Transmission color": "Warna transmisi", + "Transmission weight": "Bobot transmisi", + "Triangle": "Segitiga", + "Trilinear": "Trilinear", + "Type": "Tipe", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Urungkan dan ulangi memakai tombol aplikasi, Mod+Z dan Shift+Mod+Z.", + "UV": "UV", + "Value": "Nilai", + "Vector": "Vektor", + "vector": "vektor", + "Veins": "Urat", + "Voronoi": "Voronoi", + "Wave": "Gelombang", + "Wrap": "Bungkus", + "Zoom in": "Perbesar", + "Zoom out": "Perkecil", + "Zoom to 100%": "Zoom ke 100%", + "{kind} node {id}": "Node {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} node, {links} tautan", + "{socket} input, linked from {from}": "Input {socket}, tertaut dari {from}", + "{socket} input, {type}": "Input {socket}, {type}", + "{socket} output, {type}": "Output {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/it.json b/frontend/src/i18n/modules/graph/it.json new file mode 100644 index 00000000..80157d4b --- /dev/null +++ b/frontend/src/i18n/modules/graph/it.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Un grafo contiene al massimo {n} nodi.", + "A node cannot feed itself.": "Un nodo non può alimentare se stesso.", + "A {from} output cannot feed a {to} input.": "Un'uscita di tipo {from} non può alimentare un ingresso di tipo {to}.", + "ACEScg": "ACEScg", + "Add": "Somma", + "Add a node": "Aggiungi un nodo", + "Add a node at the pointer": "Aggiungi un nodo al puntatore", + "Add an image to a node": "Aggiungi un'immagine a un nodo", + "Add image": "Aggiungi immagine", + "Add image...": "Aggiungi immagine...", + "Adding images needs the desktop app or a service that stores uploads.": "Per aggiungere immagini serve l'app desktop o un servizio che archivi i caricamenti.", + "Alpha": "Alpha", + "B": "B", + "Bands": "Bande", + "Base color": "Colore di base", + "Base diffuse roughness": "Rugosità diffusa di base", + "Base metalness": "Metallicità di base", + "Base weight": "Peso di base", + "Bilinear": "Bilineare", + "Box": "Box", + "Brushed": "Spazzolato", + "Bump": "Bump", + "C": "C", + "Cell edge": "Bordo della cella", + "Change a node setting": "Cambia un'impostazione del nodo", + "Change a node value": "Cambia un valore del nodo", + "Chebyshev": "Chebyshev", + "Checker": "Scacchiera", + "Clamp": "Estendi", + "Click to add a stop": "Fai clic per aggiungere un punto", + "Close the node editor": "Chiudi l'editor di nodi", + "Coat color": "Colore della vernice", + "Coat ior": "IOR della vernice", + "Coat roughness": "Rugosità della vernice", + "Coat weight": "Peso della vernice", + "colour": "colore", + "Colour 1": "Colore 1", + "Colour 2": "Colore 2", + "Colour and maths": "Colore e matematica", + "Colour ramp": "Rampa di colore", + "Colour space": "Spazio colore", + "Connect": "Collega", + "Connect an input to an output.": "Collega un ingresso a un'uscita.", + "Connect an output to an input.": "Collega un'uscita a un ingresso.", + "Connect or disconnect": "Collega o scollega", + "Connect or disconnect the focused node": "Collega o scollega il nodo in focus", + "Constant": "Costante", + "Copied {n} nodes.": "{n} nodi copiati.", + "Copy the selected nodes": "Copia i nodi selezionati", + "Cut the selected nodes": "Taglia i nodi selezionati", + "Cylindrical": "Cilindrica", + "Data": "Dati", + "Delete stop": "Elimina punto", + "Delete the selected nodes": "Elimina i nodi selezionati", + "Density": "Densità", + "Detail": "Dettaglio", + "Disconnect": "Scollega", + "Displacement": "Displacement", + "Distance": "Distanza", + "Distortion": "Distorsione", + "Divide": "Dividi", + "Duplicate the selected nodes": "Duplica i nodi selezionati", + "Edit the focused node; Escape returns": "Modifica il nodo in focus; Esc per tornare indietro", + "Emission color": "Colore di emissione", + "Euclidean": "Euclidea", + "Factor": "Fattore", + "Fallback": "Valore di riserva", + "Feature": "Caratteristica", + "Filter": "Filtro", + "Flakes": "Scaglie", + "Flip green": "Inverti il verde", + "Fractal noise": "Rumore frattale", + "Frame all nodes": "Inquadra tutti i nodi", + "Fuzz color": "Colore della peluria", + "Fuzz roughness": "Rugosità della peluria", + "Fuzz weight": "Peso della peluria", + "Gain": "Guadagno", + "Geometry opacity": "Opacità della geometria", + "Go back to the last graph the engine accepted": "Torna all'ultimo grafo accettato dal motore", + "Gradient": "Gradiente", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Tieni premuto e trascina per spostare la vista; anche il trascinamento con il tasto centrale e lo scorrimento con due dita la spostano", + "Image texture": "Texture immagine", + "Images": "Immagini", + "Inputs": "Ingressi", + "Interpolation": "Interpolazione", + "Invert": "Inverti", + "Lacunarity": "Lacunarità", + "Length": "Lunghezza", + "Lerp": "Lerp", + "Linear": "Lineare", + "Manhattan": "Manhattan", + "Mapping": "Mappatura", + "Marble": "Marmo", + "Mask": "Maschera", + "Material output": "Uscita materiale", + "Math": "Matematica", + "Maximum": "Massimo", + "Metric": "Metrica", + "Minimum": "Minimo", + "Mirror": "Specchio", + "Mix": "Mescola", + "Move focus to the nearest node": "Sposta il focus sul nodo più vicino", + "Move the selected nodes": "Sposta i nodi selezionati", + "Multiply": "Moltiplica", + "Nearest": "Più vicino", + "Nearest point": "Punto più vicino", + "Node canvas": "Area dei nodi", + "Node editor": "Editor di nodi", + "Node editor keys": "Tasti dell'editor di nodi", + "Node editor: {name}": "Editor di nodi: {name}", + "Noise": "Rumore", + "normal": "normale", + "Normal map": "Mappa normale", + "Not applied: {reason}. The material keeps its last working graph.": "Non applicato: {reason}. Il materiale mantiene il suo ultimo grafo funzionante.", + "Nothing matches": "Nessuna corrispondenza", + "Number": "Numero", + "number": "numero", + "Octaves": "Ottave", + "Offset X": "Spostamento X", + "Offset Y": "Spostamento Y", + "Operation": "Operazione", + "Paste nodes, also into another material": "Incolla i nodi, anche in un altro materiale", + "Patterns": "Motivi", + "Phase": "Fase", + "Planar": "Planare", + "Position": "Posizione", + "Power": "Potenza", + "Profile": "Profilo", + "Projection": "Proiezione", + "Quadratic": "Quadratica", + "Radial": "Radiale", + "Randomness": "Casualità", + "Repeat": "Ripeti", + "Result": "Risultato", + "Revert": "Ripristina", + "Rings": "Anelli", + "Saw": "Dente di sega", + "Scale X": "Scala X", + "Scale Y": "Scala Y", + "Second nearest": "Secondo più vicino", + "Seed": "Seme", + "Select every node": "Seleziona tutti i nodi", + "Shape": "Forma", + "Show these keys": "Mostra questi tasti", + "Sine": "Sinusoidale", + "Space bar": "Barra spaziatrice", + "Specular color": "Colore speculare", + "Specular ior": "IOR speculare", + "Specular roughness": "Rugosità speculare", + "Specular roughness anisotropy": "Anisotropia della rugosità speculare", + "Specular weight": "Peso speculare", + "Spherical": "Sferica", + "Spread": "Diffusione", + "sRGB": "sRGB", + "Stop colour": "Colore del punto", + "Stop position": "Posizione del punto", + "Stop {n} at {pos}": "Punto {n} a {pos}", + "Stops": "Punti", + "Strength": "Intensità", + "Subtract": "Sottrai", + "Surface": "Superficie", + "That link would make a loop.": "Questo collegamento creerebbe un ciclo.", + "The engine did not add the image.": "Il motore non ha aggiunto l'immagine.", + "The image could not be stored ({status})": "Impossibile archiviare l'immagine ({status})", + "The material was removed, so the node editor closed.": "Il materiale è stato rimosso, quindi l'editor di nodi si è chiuso.", + "The node editor could not open: {reason}": "Impossibile aprire l'editor di nodi: {reason}", + "Transmission color": "Colore di trasmissione", + "Transmission weight": "Peso di trasmissione", + "Triangle": "Triangolare", + "Trilinear": "Trilineare", + "Type": "Tipo", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Annulla e ripeti usano i tasti dell'app, Mod+Z e Maiusc+Mod+Z.", + "UV": "UV", + "Value": "Valore", + "Vector": "Vettore", + "vector": "vettore", + "Veins": "Venature", + "Voronoi": "Voronoi", + "Wave": "Onda", + "Wrap": "Modalità di ripetizione", + "Zoom in": "Ingrandisci", + "Zoom out": "Riduci", + "Zoom to 100%": "Zoom al 100%", + "{kind} node {id}": "Nodo {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} nodi, {links} collegamenti", + "{socket} input, linked from {from}": "Ingresso {socket}, collegato a {from}", + "{socket} input, {type}": "Ingresso {socket}, {type}", + "{socket} output, {type}": "Uscita {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/ja.json b/frontend/src/i18n/modules/graph/ja.json new file mode 100644 index 00000000..908e3064 --- /dev/null +++ b/frontend/src/i18n/modules/graph/ja.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "1 つのグラフに置けるノードは最大 {n} 個です。", + "A node cannot feed itself.": "ノードは自分自身に接続できません。", + "A {from} output cannot feed a {to} input.": "{from} の出力は {to} の入力に接続できません。", + "ACEScg": "ACEScg", + "Add": "加算", + "Add a node": "ノードを追加", + "Add a node at the pointer": "ポインタの位置にノードを追加", + "Add an image to a node": "ノードに画像を追加", + "Add image": "画像を追加", + "Add image...": "画像を追加...", + "Adding images needs the desktop app or a service that stores uploads.": "画像の追加には、デスクトップアプリか、アップロードを保存するサービスが必要です。", + "Alpha": "アルファ", + "B": "B", + "Bands": "バンド", + "Base color": "ベースカラー", + "Base diffuse roughness": "ベースディフューズラフネス", + "Base metalness": "ベースメタルネス", + "Base weight": "ベースウェイト", + "Bilinear": "バイリニア", + "Box": "ボックス", + "Brushed": "ブラッシュド", + "Bump": "バンプ", + "C": "C", + "Cell edge": "セルの境界", + "Change a node setting": "ノードの設定を変更", + "Change a node value": "ノードの値を変更", + "Chebyshev": "チェビシェフ", + "Checker": "チェッカー", + "Clamp": "クランプ", + "Click to add a stop": "クリックしてストップを追加", + "Close the node editor": "ノードエディタを閉じる", + "Coat color": "コートカラー", + "Coat ior": "コート IOR", + "Coat roughness": "コートラフネス", + "Coat weight": "コートウェイト", + "colour": "カラー", + "Colour 1": "カラー 1", + "Colour 2": "カラー 2", + "Colour and maths": "カラーと演算", + "Colour ramp": "カラーランプ", + "Colour space": "カラースペース", + "Connect": "接続", + "Connect an input to an output.": "入力を出力に接続します。", + "Connect an output to an input.": "出力を入力に接続します。", + "Connect or disconnect": "接続または切断", + "Connect or disconnect the focused node": "フォーカス中のノードを接続または切断", + "Constant": "定数", + "Copied {n} nodes.": "{n} 個のノードをコピーしました。", + "Copy the selected nodes": "選択したノードをコピー", + "Cut the selected nodes": "選択したノードを切り取り", + "Cylindrical": "円筒", + "Data": "データ", + "Delete stop": "ストップを削除", + "Delete the selected nodes": "選択したノードを削除", + "Density": "密度", + "Detail": "ディテール", + "Disconnect": "切断", + "Displacement": "ディスプレイスメント", + "Distance": "距離", + "Distortion": "ディストーション", + "Divide": "除算", + "Duplicate the selected nodes": "選択したノードを複製", + "Edit the focused node; Escape returns": "フォーカス中のノードを編集します。Escape で戻ります", + "Emission color": "エミッションカラー", + "Euclidean": "ユークリッド", + "Factor": "係数", + "Fallback": "フォールバック", + "Feature": "フィーチャー", + "Filter": "フィルタ", + "Flakes": "フレーク", + "Flip green": "グリーンを反転", + "Fractal noise": "フラクタルノイズ", + "Frame all nodes": "すべてのノードにフレーミング", + "Fuzz color": "ファズカラー", + "Fuzz roughness": "ファズラフネス", + "Fuzz weight": "ファズウェイト", + "Gain": "ゲイン", + "Geometry opacity": "ジオメトリの不透明度", + "Go back to the last graph the engine accepted": "エンジンが最後に受け付けたグラフに戻す", + "Gradient": "グラデーション", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "押したままドラッグでパン。中ボタンのドラッグや 2 本指スクロールでもパンできます", + "Image texture": "画像テクスチャ", + "Images": "画像", + "Inputs": "入力", + "Interpolation": "補間", + "Invert": "反転", + "Lacunarity": "ラクナリティ", + "Length": "長さ", + "Lerp": "線形補間", + "Linear": "リニア", + "Manhattan": "マンハッタン", + "Mapping": "マッピング", + "Marble": "大理石", + "Mask": "マスク", + "Material output": "マテリアル出力", + "Math": "演算", + "Maximum": "最大", + "Metric": "メトリック", + "Minimum": "最小", + "Mirror": "ミラー", + "Mix": "ミックス", + "Move focus to the nearest node": "最も近いノードにフォーカスを移動", + "Move the selected nodes": "選択したノードを移動", + "Multiply": "乗算", + "Nearest": "ニアレスト", + "Nearest point": "最近接点", + "Node canvas": "ノードキャンバス", + "Node editor": "ノードエディタ", + "Node editor keys": "ノードエディタのキー", + "Node editor: {name}": "ノードエディタ: {name}", + "Noise": "ノイズ", + "normal": "ノーマル", + "Normal map": "ノーマルマップ", + "Not applied: {reason}. The material keeps its last working graph.": "適用されませんでした: {reason}。マテリアルは最後に動作したグラフを保持します。", + "Nothing matches": "一致するものがありません", + "Number": "数値", + "number": "数値", + "Octaves": "オクターブ", + "Offset X": "オフセット X", + "Offset Y": "オフセット Y", + "Operation": "演算", + "Paste nodes, also into another material": "ノードを貼り付け (別のマテリアルにも可能)", + "Patterns": "パターン", + "Phase": "フェーズ", + "Planar": "平面", + "Position": "位置", + "Power": "べき乗", + "Profile": "プロファイル", + "Projection": "投影", + "Quadratic": "2 次", + "Radial": "放射", + "Randomness": "ランダムネス", + "Repeat": "リピート", + "Result": "結果", + "Revert": "元に戻す", + "Rings": "リング", + "Saw": "ノコギリ波", + "Scale X": "スケール X", + "Scale Y": "スケール Y", + "Second nearest": "2 番目に近い点", + "Seed": "シード", + "Select every node": "すべてのノードを選択", + "Shape": "形状", + "Show these keys": "これらのキーを表示", + "Sine": "サイン波", + "Space bar": "スペースキー", + "Specular color": "スペキュラカラー", + "Specular ior": "スペキュラ IOR", + "Specular roughness": "スペキュララフネス", + "Specular roughness anisotropy": "スペキュララフネス異方性", + "Specular weight": "スペキュラウェイト", + "Spherical": "球面", + "Spread": "広がり", + "sRGB": "sRGB", + "Stop colour": "ストップのカラー", + "Stop position": "ストップの位置", + "Stop {n} at {pos}": "ストップ {n} ({pos})", + "Stops": "ストップ", + "Strength": "強さ", + "Subtract": "減算", + "Surface": "サーフェス", + "That link would make a loop.": "このリンクはループになります。", + "The engine did not add the image.": "エンジンが画像を追加しませんでした。", + "The image could not be stored ({status})": "画像を保存できませんでした ({status})", + "The material was removed, so the node editor closed.": "マテリアルが削除されたため、ノードエディタを閉じました。", + "The node editor could not open: {reason}": "ノードエディタを開けませんでした: {reason}", + "Transmission color": "トランスミッションカラー", + "Transmission weight": "トランスミッションウェイト", + "Triangle": "三角波", + "Trilinear": "トライリニア", + "Type": "タイプ", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "アンドゥとリドゥにはアプリのキー、Mod+Z と Shift+Mod+Z を使います。", + "UV": "UV", + "Value": "値", + "Vector": "ベクトル", + "vector": "ベクトル", + "Veins": "ベイン", + "Voronoi": "ボロノイ", + "Wave": "ウェーブ", + "Wrap": "ラップ", + "Zoom in": "拡大", + "Zoom out": "縮小", + "Zoom to 100%": "100% に拡大縮小", + "{kind} node {id}": "{kind} ノード {id}", + "{nodes} nodes, {links} links": "ノード {nodes} 個、リンク {links} 本", + "{socket} input, linked from {from}": "{socket} 入力、{from} からリンク", + "{socket} input, {type}": "{socket} 入力、{type}", + "{socket} output, {type}": "{socket} 出力、{type}" +} diff --git a/frontend/src/i18n/modules/graph/ko.json b/frontend/src/i18n/modules/graph/ko.json new file mode 100644 index 00000000..557a55ad --- /dev/null +++ b/frontend/src/i18n/modules/graph/ko.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "그래프 하나에는 노드를 최대 {n}개까지 둘 수 있습니다.", + "A node cannot feed itself.": "노드는 자기 자신에 연결할 수 없습니다.", + "A {from} output cannot feed a {to} input.": "{from} 출력은 {to} 입력에 연결할 수 없습니다.", + "ACEScg": "ACEScg", + "Add": "더하기", + "Add a node": "노드 추가", + "Add a node at the pointer": "포인터 위치에 노드 추가", + "Add an image to a node": "노드에 이미지 추가", + "Add image": "이미지 추가", + "Add image...": "이미지 추가...", + "Adding images needs the desktop app or a service that stores uploads.": "이미지를 추가하려면 데스크톱 앱이나 업로드를 저장하는 서비스가 필요합니다.", + "Alpha": "알파", + "B": "B", + "Bands": "밴드", + "Base color": "베이스 컬러", + "Base diffuse roughness": "베이스 디퓨즈 러프니스", + "Base metalness": "베이스 메탈니스", + "Base weight": "베이스 가중치", + "Bilinear": "바이리니어", + "Box": "박스", + "Brushed": "브러시드", + "Bump": "범프", + "C": "C", + "Cell edge": "셀 가장자리", + "Change a node setting": "노드 설정 변경", + "Change a node value": "노드 값 변경", + "Chebyshev": "체비쇼프", + "Checker": "체커", + "Clamp": "클램프", + "Click to add a stop": "클릭하여 스톱 추가", + "Close the node editor": "노드 편집기 닫기", + "Coat color": "코트 색상", + "Coat ior": "코트 IOR", + "Coat roughness": "코트 러프니스", + "Coat weight": "코트 가중치", + "colour": "색상", + "Colour 1": "색상 1", + "Colour 2": "색상 2", + "Colour and maths": "색상 및 수학", + "Colour ramp": "컬러 램프", + "Colour space": "색 공간", + "Connect": "연결", + "Connect an input to an output.": "입력을 출력에 연결합니다.", + "Connect an output to an input.": "출력을 입력에 연결합니다.", + "Connect or disconnect": "연결 또는 연결 해제", + "Connect or disconnect the focused node": "포커스된 노드를 연결하거나 연결 해제", + "Constant": "상수", + "Copied {n} nodes.": "노드 {n}개를 복사했습니다.", + "Copy the selected nodes": "선택한 노드 복사", + "Cut the selected nodes": "선택한 노드 잘라내기", + "Cylindrical": "원통형", + "Data": "데이터", + "Delete stop": "스톱 삭제", + "Delete the selected nodes": "선택한 노드 삭제", + "Density": "밀도", + "Detail": "디테일", + "Disconnect": "연결 해제", + "Displacement": "디스플레이스먼트", + "Distance": "거리", + "Distortion": "왜곡", + "Divide": "나누기", + "Duplicate the selected nodes": "선택한 노드 복제", + "Edit the focused node; Escape returns": "포커스된 노드를 편집합니다. Escape를 누르면 돌아갑니다", + "Emission color": "발광 색상", + "Euclidean": "유클리드", + "Factor": "계수", + "Fallback": "대체값", + "Feature": "피처", + "Filter": "필터", + "Flakes": "플레이크", + "Flip green": "그린 반전", + "Fractal noise": "프랙탈 노이즈", + "Frame all nodes": "모든 노드 맞춤", + "Fuzz color": "퍼즈 색상", + "Fuzz roughness": "퍼즈 러프니스", + "Fuzz weight": "퍼즈 가중치", + "Gain": "게인", + "Geometry opacity": "지오메트리 불투명도", + "Go back to the last graph the engine accepted": "엔진이 마지막으로 받아들인 그래프로 되돌리기", + "Gradient": "그레이디언트", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "누른 채 드래그하여 이동합니다. 가운데 버튼 드래그와 두 손가락 스크롤로도 이동할 수 있습니다", + "Image texture": "이미지 텍스처", + "Images": "이미지", + "Inputs": "입력", + "Interpolation": "보간", + "Invert": "반전", + "Lacunarity": "공극성", + "Length": "길이", + "Lerp": "선형 보간", + "Linear": "리니어", + "Manhattan": "맨해튼", + "Mapping": "매핑", + "Marble": "대리석", + "Mask": "마스크", + "Material output": "머티리얼 출력", + "Math": "수학", + "Maximum": "최대", + "Metric": "메트릭", + "Minimum": "최소", + "Mirror": "미러", + "Mix": "믹스", + "Move focus to the nearest node": "가장 가까운 노드로 포커스 이동", + "Move the selected nodes": "선택한 노드 이동", + "Multiply": "곱하기", + "Nearest": "최근접", + "Nearest point": "최근접점", + "Node canvas": "노드 캔버스", + "Node editor": "노드 편집기", + "Node editor keys": "노드 편집기 키", + "Node editor: {name}": "노드 편집기: {name}", + "Noise": "노이즈", + "normal": "노멀", + "Normal map": "노멀 맵", + "Not applied: {reason}. The material keeps its last working graph.": "적용되지 않음: {reason}. 머티리얼은 마지막으로 작동한 그래프를 유지합니다.", + "Nothing matches": "일치하는 항목이 없습니다", + "Number": "숫자", + "number": "숫자", + "Octaves": "옥타브", + "Offset X": "오프셋 X", + "Offset Y": "오프셋 Y", + "Operation": "연산", + "Paste nodes, also into another material": "노드 붙여넣기(다른 머티리얼에도 가능)", + "Patterns": "패턴", + "Phase": "위상", + "Planar": "평면", + "Position": "위치", + "Power": "거듭제곱", + "Profile": "프로파일", + "Projection": "투영", + "Quadratic": "이차", + "Radial": "방사형", + "Randomness": "무작위성", + "Repeat": "반복", + "Result": "결과", + "Revert": "되돌리기", + "Rings": "링", + "Saw": "톱니파", + "Scale X": "스케일 X", + "Scale Y": "스케일 Y", + "Second nearest": "두 번째로 가까운 점", + "Seed": "시드", + "Select every node": "모든 노드 선택", + "Shape": "모양", + "Show these keys": "이 키 표시", + "Sine": "사인파", + "Space bar": "스페이스 바", + "Specular color": "스페큘러 색상", + "Specular ior": "스페큘러 IOR", + "Specular roughness": "스페큘러 러프니스", + "Specular roughness anisotropy": "스페큘러 러프니스 이방성", + "Specular weight": "스페큘러 가중치", + "Spherical": "구형", + "Spread": "퍼짐", + "sRGB": "sRGB", + "Stop colour": "스톱 색상", + "Stop position": "스톱 위치", + "Stop {n} at {pos}": "스톱 {n}({pos})", + "Stops": "스톱", + "Strength": "강도", + "Subtract": "빼기", + "Surface": "서피스", + "That link would make a loop.": "이 링크는 루프가 됩니다.", + "The engine did not add the image.": "엔진이 이미지를 추가하지 않았습니다.", + "The image could not be stored ({status})": "이미지를 저장하지 못했습니다 ({status})", + "The material was removed, so the node editor closed.": "머티리얼이 제거되어 노드 편집기를 닫았습니다.", + "The node editor could not open: {reason}": "노드 편집기를 열지 못했습니다: {reason}", + "Transmission color": "트랜스미션 색상", + "Transmission weight": "트랜스미션 가중치", + "Triangle": "삼각파", + "Trilinear": "트라이리니어", + "Type": "유형", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "실행 취소와 다시 실행에는 앱 키인 Mod+Z와 Shift+Mod+Z를 사용합니다.", + "UV": "UV", + "Value": "값", + "Vector": "벡터", + "vector": "벡터", + "Veins": "베인", + "Voronoi": "보로노이", + "Wave": "웨이브", + "Wrap": "래핑", + "Zoom in": "확대", + "Zoom out": "축소", + "Zoom to 100%": "100%로 확대/축소", + "{kind} node {id}": "{kind} 노드 {id}", + "{nodes} nodes, {links} links": "노드 {nodes}개, 링크 {links}개", + "{socket} input, linked from {from}": "{socket} 입력, {from}에서 연결됨", + "{socket} input, {type}": "{socket} 입력, {type}", + "{socket} output, {type}": "{socket} 출력, {type}" +} diff --git a/frontend/src/i18n/modules/graph/nb.json b/frontend/src/i18n/modules/graph/nb.json new file mode 100644 index 00000000..f4f282d2 --- /dev/null +++ b/frontend/src/i18n/modules/graph/nb.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "En graf rommer høyst {n} noder.", + "A node cannot feed itself.": "En node kan ikke mate seg selv.", + "A {from} output cannot feed a {to} input.": "En {from}-utgang kan ikke mate en {to}-inngang.", + "ACEScg": "ACEScg", + "Add": "Legg til", + "Add a node": "Legg til en node", + "Add a node at the pointer": "Legg til en node ved pekeren", + "Add an image to a node": "Legg til et bilde i en node", + "Add image": "Legg til bilde", + "Add image...": "Legg til bilde...", + "Adding images needs the desktop app or a service that stores uploads.": "Å legge til bilder krever skrivebordsappen eller en tjeneste som lagrer opplastinger.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Bånd", + "Base color": "Basisfarge", + "Base diffuse roughness": "Diffus basisruhet", + "Base metalness": "Basis-metalness", + "Base weight": "Basisvekt", + "Bilinear": "Bilineær", + "Box": "Boks", + "Brushed": "Børstet", + "Bump": "Bump", + "C": "C", + "Cell edge": "Cellekant", + "Change a node setting": "Endre en nodeinnstilling", + "Change a node value": "Endre en nodeverdi", + "Chebyshev": "Chebyshev", + "Checker": "Sjakkbrett", + "Clamp": "Begrens", + "Click to add a stop": "Klikk for å legge til et stopp", + "Close the node editor": "Lukk nodeeditoren", + "Coat color": "Coatingfarge", + "Coat ior": "Coating-IOR", + "Coat roughness": "Coatingruhet", + "Coat weight": "Coatingvekt", + "colour": "farge", + "Colour 1": "Farge 1", + "Colour 2": "Farge 2", + "Colour and maths": "Farge og matematikk", + "Colour ramp": "Fargerampe", + "Colour space": "Fargerom", + "Connect": "Koble til", + "Connect an input to an output.": "Koble en inngang til en utgang.", + "Connect an output to an input.": "Koble en utgang til en inngang.", + "Connect or disconnect": "Koble til eller fra", + "Connect or disconnect the focused node": "Koble noden med fokus til eller fra", + "Constant": "Konstant", + "Copied {n} nodes.": "Kopierte {n} noder.", + "Copy the selected nodes": "Kopier de valgte nodene", + "Cut the selected nodes": "Klipp ut de valgte nodene", + "Cylindrical": "Sylindrisk", + "Data": "Data", + "Delete stop": "Slett stopp", + "Delete the selected nodes": "Slett de valgte nodene", + "Density": "Tetthet", + "Detail": "Detalj", + "Disconnect": "Koble fra", + "Displacement": "Displacement", + "Distance": "Avstand", + "Distortion": "Forvrengning", + "Divide": "Divider", + "Duplicate the selected nodes": "Dupliser de valgte nodene", + "Edit the focused node; Escape returns": "Rediger noden med fokus; Escape går tilbake", + "Emission color": "Emisjonsfarge", + "Euclidean": "Euklidsk", + "Factor": "Faktor", + "Fallback": "Reserveverdi", + "Feature": "Egenskap", + "Filter": "Filter", + "Flakes": "Flak", + "Flip green": "Snu grønn", + "Fractal noise": "Fraktal støy", + "Frame all nodes": "Ramm inn alle nodene", + "Fuzz color": "Fuzz-farge", + "Fuzz roughness": "Fuzz-ruhet", + "Fuzz weight": "Fuzz-vekt", + "Gain": "Forsterkning", + "Geometry opacity": "Geometriopasitet", + "Go back to the last graph the engine accepted": "Gå tilbake til den siste grafen motoren godtok", + "Gradient": "Gradient", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Hold og dra for å panorere; dra med midtknappen og rulling med to fingre panorerer også", + "Image texture": "Bildetekstur", + "Images": "Bilder", + "Inputs": "Innganger", + "Interpolation": "Interpolering", + "Invert": "Inverter", + "Lacunarity": "Lakunaritet", + "Length": "Lengde", + "Lerp": "Lerp", + "Linear": "Lineær", + "Manhattan": "Manhattan", + "Mapping": "Mapping", + "Marble": "Marmor", + "Mask": "Maske", + "Material output": "Materialutgang", + "Math": "Matematikk", + "Maximum": "Maksimum", + "Metric": "Metrikk", + "Minimum": "Minimum", + "Mirror": "Speil", + "Mix": "Bland", + "Move focus to the nearest node": "Flytt fokus til nærmeste node", + "Move the selected nodes": "Flytt de valgte nodene", + "Multiply": "Multipliser", + "Nearest": "Nærmeste", + "Nearest point": "Nærmeste punkt", + "Node canvas": "Nodecanvas", + "Node editor": "Nodeeditor", + "Node editor keys": "Taster i nodeeditoren", + "Node editor: {name}": "Nodeeditor: {name}", + "Noise": "Støy", + "normal": "normal", + "Normal map": "Normal map", + "Not applied: {reason}. The material keeps its last working graph.": "Ikke brukt: {reason}. Materialet beholder den siste fungerende grafen sin.", + "Nothing matches": "Ingenting samsvarer", + "Number": "Tall", + "number": "tall", + "Octaves": "Oktaver", + "Offset X": "Forskyvning X", + "Offset Y": "Forskyvning Y", + "Operation": "Operasjon", + "Paste nodes, also into another material": "Lim inn noder, også i et annet materiale", + "Patterns": "Mønstre", + "Phase": "Fase", + "Planar": "Plan", + "Position": "Posisjon", + "Power": "Potens", + "Profile": "Profil", + "Projection": "Projeksjon", + "Quadratic": "Kvadratisk", + "Radial": "Radiell", + "Randomness": "Tilfeldighet", + "Repeat": "Gjenta", + "Result": "Resultat", + "Revert": "Gjenopprett", + "Rings": "Ringer", + "Saw": "Sagtann", + "Scale X": "Skala X", + "Scale Y": "Skala Y", + "Second nearest": "Nest nærmeste", + "Seed": "Seed", + "Select every node": "Velg alle nodene", + "Shape": "Form", + "Show these keys": "Vis disse tastene", + "Sine": "Sinus", + "Space bar": "Mellomromstasten", + "Specular color": "Spekulær farge", + "Specular ior": "Spekulær IOR", + "Specular roughness": "Spekulær ruhet", + "Specular roughness anisotropy": "Anisotropi for spekulær ruhet", + "Specular weight": "Spekulær vekt", + "Spherical": "Sfærisk", + "Spread": "Spredning", + "sRGB": "sRGB", + "Stop colour": "Stoppfarge", + "Stop position": "Stoppposisjon", + "Stop {n} at {pos}": "Stopp {n} ved {pos}", + "Stops": "Stopp", + "Strength": "Styrke", + "Subtract": "Subtraher", + "Surface": "Overflate", + "That link would make a loop.": "Den koblingen ville laget en løkke.", + "The engine did not add the image.": "Motoren la ikke til bildet.", + "The image could not be stored ({status})": "Bildet kunne ikke lagres ({status})", + "The material was removed, so the node editor closed.": "Materialet ble fjernet, så nodeeditoren ble lukket.", + "The node editor could not open: {reason}": "Nodeeditoren kunne ikke åpnes: {reason}", + "Transmission color": "Transmisjonsfarge", + "Transmission weight": "Transmisjonsvekt", + "Triangle": "Trekant", + "Trilinear": "Trilineær", + "Type": "Type", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Angre og gjør om bruker tastene i appen, Mod+Z og Shift+Mod+Z.", + "UV": "UV", + "Value": "Verdi", + "Vector": "Vektor", + "vector": "vektor", + "Veins": "Årer", + "Voronoi": "Voronoi", + "Wave": "Bølge", + "Wrap": "Wrap", + "Zoom in": "Zoom inn", + "Zoom out": "Zoom ut", + "Zoom to 100%": "Zoom til 100%", + "{kind} node {id}": "{kind}-node {id}", + "{nodes} nodes, {links} links": "{nodes} noder, {links} koblinger", + "{socket} input, linked from {from}": "{socket}-inngang, koblet fra {from}", + "{socket} input, {type}": "{socket}-inngang, {type}", + "{socket} output, {type}": "{socket}-utgang, {type}" +} diff --git a/frontend/src/i18n/modules/graph/nl.json b/frontend/src/i18n/modules/graph/nl.json new file mode 100644 index 00000000..8fced7c0 --- /dev/null +++ b/frontend/src/i18n/modules/graph/nl.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Een graaf bevat maximaal {n} nodes.", + "A node cannot feed itself.": "Een node kan zichzelf niet voeden.", + "A {from} output cannot feed a {to} input.": "Een {from}-uitvoer kan geen {to}-invoer voeden.", + "ACEScg": "ACEScg", + "Add": "Toevoegen", + "Add a node": "Een node toevoegen", + "Add a node at the pointer": "Een node toevoegen bij de aanwijzer", + "Add an image to a node": "Een afbeelding aan een node toevoegen", + "Add image": "Afbeelding toevoegen", + "Add image...": "Afbeelding toevoegen...", + "Adding images needs the desktop app or a service that stores uploads.": "Afbeeldingen toevoegen vereist de desktop-app of een service die uploads opslaat.", + "Alpha": "Alpha", + "B": "B", + "Bands": "Banden", + "Base color": "Basiskleur", + "Base diffuse roughness": "Diffuse basisruwheid", + "Base metalness": "Basis-metalness", + "Base weight": "Basisgewicht", + "Bilinear": "Bilineair", + "Box": "Box", + "Brushed": "Geborsteld", + "Bump": "Bump", + "C": "C", + "Cell edge": "Celrand", + "Change a node setting": "Een node-instelling wijzigen", + "Change a node value": "Een node-waarde wijzigen", + "Chebyshev": "Chebyshev", + "Checker": "Dambord", + "Clamp": "Begrenzen", + "Click to add a stop": "Klik om een stop toe te voegen", + "Close the node editor": "De node-editor sluiten", + "Coat color": "Coatingkleur", + "Coat ior": "Coating-IOR", + "Coat roughness": "Coatingruwheid", + "Coat weight": "Coatinggewicht", + "colour": "kleur", + "Colour 1": "Kleur 1", + "Colour 2": "Kleur 2", + "Colour and maths": "Kleur en wiskunde", + "Colour ramp": "Kleurovergang", + "Colour space": "Kleurruimte", + "Connect": "Verbinden", + "Connect an input to an output.": "Verbind een invoer met een uitvoer.", + "Connect an output to an input.": "Verbind een uitvoer met een invoer.", + "Connect or disconnect": "Verbinden of loskoppelen", + "Connect or disconnect the focused node": "De node met focus verbinden of loskoppelen", + "Constant": "Constante", + "Copied {n} nodes.": "{n} nodes gekopieerd.", + "Copy the selected nodes": "De geselecteerde nodes kopiëren", + "Cut the selected nodes": "De geselecteerde nodes knippen", + "Cylindrical": "Cilindrisch", + "Data": "Data", + "Delete stop": "Stop verwijderen", + "Delete the selected nodes": "De geselecteerde nodes verwijderen", + "Density": "Dichtheid", + "Detail": "Detail", + "Disconnect": "Loskoppelen", + "Displacement": "Displacement", + "Distance": "Afstand", + "Distortion": "Vervorming", + "Divide": "Delen", + "Duplicate the selected nodes": "De geselecteerde nodes dupliceren", + "Edit the focused node; Escape returns": "De node met focus bewerken; Escape keert terug", + "Emission color": "Emissiekleur", + "Euclidean": "Euclidisch", + "Factor": "Factor", + "Fallback": "Terugvalwaarde", + "Feature": "Kenmerk", + "Filter": "Filter", + "Flakes": "Vlokjes", + "Flip green": "Groen omkeren", + "Fractal noise": "Fractale ruis", + "Frame all nodes": "Alle nodes in beeld brengen", + "Fuzz color": "Fuzz-kleur", + "Fuzz roughness": "Fuzz-ruwheid", + "Fuzz weight": "Fuzz-gewicht", + "Gain": "Versterking", + "Geometry opacity": "Geometriedekking", + "Go back to the last graph the engine accepted": "Terug naar de laatste graaf die de engine accepteerde", + "Gradient": "Verloop", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Houd ingedrukt en sleep om te pannen; slepen met de middelste knop en scrollen met twee vingers pant ook", + "Image texture": "Afbeeldingstekstuur", + "Images": "Afbeeldingen", + "Inputs": "Invoeren", + "Interpolation": "Interpolatie", + "Invert": "Omkeren", + "Lacunarity": "Lacunariteit", + "Length": "Lengte", + "Lerp": "Lerp", + "Linear": "Lineair", + "Manhattan": "Manhattan", + "Mapping": "Mapping", + "Marble": "Marmer", + "Mask": "Masker", + "Material output": "Materiaaluitvoer", + "Math": "Wiskunde", + "Maximum": "Maximum", + "Metric": "Metriek", + "Minimum": "Minimum", + "Mirror": "Spiegelen", + "Mix": "Mengen", + "Move focus to the nearest node": "De focus naar de dichtstbijzijnde node verplaatsen", + "Move the selected nodes": "De geselecteerde nodes verplaatsen", + "Multiply": "Vermenigvuldigen", + "Nearest": "Dichtstbijzijnde", + "Nearest point": "Dichtstbijzijnde punt", + "Node canvas": "Nodecanvas", + "Node editor": "Node-editor", + "Node editor keys": "Toetsen van de node-editor", + "Node editor: {name}": "Node-editor: {name}", + "Noise": "Ruis", + "normal": "normaal", + "Normal map": "Normal map", + "Not applied: {reason}. The material keeps its last working graph.": "Niet toegepast: {reason}. Het materiaal behoudt zijn laatste werkende graaf.", + "Nothing matches": "Niets komt overeen", + "Number": "Getal", + "number": "getal", + "Octaves": "Octaven", + "Offset X": "Verschuiving X", + "Offset Y": "Verschuiving Y", + "Operation": "Bewerking", + "Paste nodes, also into another material": "Nodes plakken, ook in een ander materiaal", + "Patterns": "Patronen", + "Phase": "Fase", + "Planar": "Vlak", + "Position": "Positie", + "Power": "Macht", + "Profile": "Profiel", + "Projection": "Projectie", + "Quadratic": "Kwadratisch", + "Radial": "Radiaal", + "Randomness": "Willekeurigheid", + "Repeat": "Herhalen", + "Result": "Resultaat", + "Revert": "Terugzetten", + "Rings": "Ringen", + "Saw": "Zaagtand", + "Scale X": "Schaal X", + "Scale Y": "Schaal Y", + "Second nearest": "Op een na dichtstbijzijnde", + "Seed": "Seed", + "Select every node": "Alle nodes selecteren", + "Shape": "Vorm", + "Show these keys": "Deze toetsen tonen", + "Sine": "Sinus", + "Space bar": "Spatiebalk", + "Specular color": "Speculaire kleur", + "Specular ior": "Speculaire IOR", + "Specular roughness": "Speculaire ruwheid", + "Specular roughness anisotropy": "Anisotropie van speculaire ruwheid", + "Specular weight": "Speculair gewicht", + "Spherical": "Sferisch", + "Spread": "Spreiding", + "sRGB": "sRGB", + "Stop colour": "Stopkleur", + "Stop position": "Stoppositie", + "Stop {n} at {pos}": "Stop {n} op {pos}", + "Stops": "Stops", + "Strength": "Sterkte", + "Subtract": "Aftrekken", + "Surface": "Oppervlak", + "That link would make a loop.": "Die koppeling zou een lus maken.", + "The engine did not add the image.": "De engine heeft de afbeelding niet toegevoegd.", + "The image could not be stored ({status})": "De afbeelding kon niet worden opgeslagen ({status})", + "The material was removed, so the node editor closed.": "Het materiaal is verwijderd, dus de node-editor is gesloten.", + "The node editor could not open: {reason}": "De node-editor kon niet worden geopend: {reason}", + "Transmission color": "Transmissiekleur", + "Transmission weight": "Transmissiegewicht", + "Triangle": "Driehoek", + "Trilinear": "Trilineair", + "Type": "Type", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Ongedaan maken en opnieuw uitvoeren gebruiken de toetsen van de app, Mod+Z en Shift+Mod+Z.", + "UV": "UV", + "Value": "Waarde", + "Vector": "Vector", + "vector": "vector", + "Veins": "Aders", + "Voronoi": "Voronoi", + "Wave": "Golf", + "Wrap": "Wrap", + "Zoom in": "Inzoomen", + "Zoom out": "Uitzoomen", + "Zoom to 100%": "Zoomen naar 100%", + "{kind} node {id}": "{kind}-node {id}", + "{nodes} nodes, {links} links": "{nodes} nodes, {links} koppelingen", + "{socket} input, linked from {from}": "{socket}-invoer, gekoppeld vanaf {from}", + "{socket} input, {type}": "{socket}-invoer, {type}", + "{socket} output, {type}": "{socket}-uitvoer, {type}" +} diff --git a/frontend/src/i18n/modules/graph/pl.json b/frontend/src/i18n/modules/graph/pl.json new file mode 100644 index 00000000..4961007f --- /dev/null +++ b/frontend/src/i18n/modules/graph/pl.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Graf może zawierać najwyżej {n} węzłów.", + "A node cannot feed itself.": "Węzeł nie może zasilać samego siebie.", + "A {from} output cannot feed a {to} input.": "Wyjście typu {from} nie może zasilać wejścia typu {to}.", + "ACEScg": "ACEScg", + "Add": "Dodaj", + "Add a node": "Dodaj węzeł", + "Add a node at the pointer": "Dodaj węzeł w miejscu wskaźnika", + "Add an image to a node": "Dodaj obraz do węzła", + "Add image": "Dodaj obraz", + "Add image...": "Dodaj obraz...", + "Adding images needs the desktop app or a service that stores uploads.": "Dodawanie obrazów wymaga aplikacji na komputer lub usługi, która przechowuje przesłane pliki.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Pasma", + "Base color": "Kolor bazowy", + "Base diffuse roughness": "Bazowa chropowatość rozproszenia", + "Base metalness": "Bazowa metaliczność", + "Base weight": "Waga bazowa", + "Bilinear": "Dwuliniowe", + "Box": "Skrzynkowa", + "Brushed": "Szczotkowany", + "Bump": "Bump", + "C": "C", + "Cell edge": "Krawędź komórki", + "Change a node setting": "Zmień ustawienie węzła", + "Change a node value": "Zmień wartość węzła", + "Chebyshev": "Czebyszewa", + "Checker": "Szachownica", + "Clamp": "Przycięcie", + "Click to add a stop": "Kliknij, aby dodać punkt", + "Close the node editor": "Zamknij edytor węzłów", + "Coat color": "Kolor powłoki", + "Coat ior": "IOR powłoki", + "Coat roughness": "Chropowatość powłoki", + "Coat weight": "Waga powłoki", + "colour": "kolor", + "Colour 1": "Kolor 1", + "Colour 2": "Kolor 2", + "Colour and maths": "Kolor i matematyka", + "Colour ramp": "Rampa kolorów", + "Colour space": "Przestrzeń barw", + "Connect": "Połącz", + "Connect an input to an output.": "Połącz wejście z wyjściem.", + "Connect an output to an input.": "Połącz wyjście z wejściem.", + "Connect or disconnect": "Połącz lub rozłącz", + "Connect or disconnect the focused node": "Połącz lub rozłącz wskazany węzeł", + "Constant": "Stała", + "Copied {n} nodes.": "Skopiowano węzły: {n}.", + "Copy the selected nodes": "Kopiuj zaznaczone węzły", + "Cut the selected nodes": "Wytnij zaznaczone węzły", + "Cylindrical": "Cylindryczna", + "Data": "Dane", + "Delete stop": "Usuń punkt", + "Delete the selected nodes": "Usuń zaznaczone węzły", + "Density": "Gęstość", + "Detail": "Szczegółowość", + "Disconnect": "Rozłącz", + "Displacement": "Przemieszczenie", + "Distance": "Odległość", + "Distortion": "Zniekształcenie", + "Divide": "Dzielenie", + "Duplicate the selected nodes": "Duplikuj zaznaczone węzły", + "Edit the focused node; Escape returns": "Edytuj wskazany węzeł; Escape wraca", + "Emission color": "Kolor emisji", + "Euclidean": "Euklidesowa", + "Factor": "Współczynnik", + "Fallback": "Wartość zastępcza", + "Feature": "Cecha", + "Filter": "Filtrowanie", + "Flakes": "Płatki", + "Flip green": "Odwróć zielony", + "Fractal noise": "Szum fraktalny", + "Frame all nodes": "Pokaż wszystkie węzły w kadrze", + "Fuzz color": "Kolor meszku", + "Fuzz roughness": "Chropowatość meszku", + "Fuzz weight": "Waga meszku", + "Gain": "Wzmocnienie", + "Geometry opacity": "Nieprzezroczystość geometrii", + "Go back to the last graph the engine accepted": "Wróć do ostatniego grafu zaakceptowanego przez silnik", + "Gradient": "Gradient", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Przytrzymaj i przeciągnij, aby przesuwać widok; przesuwa go też przeciąganie środkowym przyciskiem i przewijanie dwoma palcami", + "Image texture": "Tekstura obrazu", + "Images": "Obrazy", + "Inputs": "Wejścia", + "Interpolation": "Interpolacja", + "Invert": "Odwróć", + "Lacunarity": "Lakunarność", + "Length": "Długość", + "Lerp": "Lerp", + "Linear": "Liniowa", + "Manhattan": "Manhattan", + "Mapping": "Mapowanie", + "Marble": "Marmur", + "Mask": "Maska", + "Material output": "Wyjście materiału", + "Math": "Matematyka", + "Maximum": "Maksimum", + "Metric": "Metryka", + "Minimum": "Minimum", + "Mirror": "Odbicie lustrzane", + "Mix": "Mieszanie", + "Move focus to the nearest node": "Przenieś fokus na najbliższy węzeł", + "Move the selected nodes": "Przesuń zaznaczone węzły", + "Multiply": "Mnożenie", + "Nearest": "Najbliższy", + "Nearest point": "Najbliższy punkt", + "Node canvas": "Obszar roboczy węzłów", + "Node editor": "Edytor węzłów", + "Node editor keys": "Skróty edytora węzłów", + "Node editor: {name}": "Edytor węzłów: {name}", + "Noise": "Szum", + "normal": "normalna", + "Normal map": "Mapa normalnych", + "Not applied: {reason}. The material keeps its last working graph.": "Nie zastosowano: {reason}. Materiał zachowuje ostatni działający graf.", + "Nothing matches": "Nic nie pasuje", + "Number": "Liczba", + "number": "liczba", + "Octaves": "Oktawy", + "Offset X": "Przesunięcie X", + "Offset Y": "Przesunięcie Y", + "Operation": "Operacja", + "Paste nodes, also into another material": "Wklej węzły, także do innego materiału", + "Patterns": "Wzory", + "Phase": "Faza", + "Planar": "Płaska", + "Position": "Pozycja", + "Power": "Potęga", + "Profile": "Profil", + "Projection": "Projekcja", + "Quadratic": "Kwadratowa", + "Radial": "Promieniowa", + "Randomness": "Losowość", + "Repeat": "Powtarzanie", + "Result": "Wynik", + "Revert": "Cofnij zmiany", + "Rings": "Pierścienie", + "Saw": "Piła", + "Scale X": "Skala X", + "Scale Y": "Skala Y", + "Second nearest": "Drugi najbliższy", + "Seed": "Ziarno", + "Select every node": "Zaznacz wszystkie węzły", + "Shape": "Kształt", + "Show these keys": "Pokaż te skróty", + "Sine": "Sinus", + "Space bar": "Spacja", + "Specular color": "Kolor połysku", + "Specular ior": "IOR połysku", + "Specular roughness": "Chropowatość połysku", + "Specular roughness anisotropy": "Anizotropia chropowatości połysku", + "Specular weight": "Waga połysku", + "Spherical": "Sferyczna", + "Spread": "Rozrzut", + "sRGB": "sRGB", + "Stop colour": "Kolor punktu", + "Stop position": "Pozycja punktu", + "Stop {n} at {pos}": "Punkt {n} w pozycji {pos}", + "Stops": "Punkty", + "Strength": "Siła", + "Subtract": "Odejmowanie", + "Surface": "Powierzchnia", + "That link would make a loop.": "To połączenie utworzyłoby pętlę.", + "The engine did not add the image.": "Silnik nie dodał obrazu.", + "The image could not be stored ({status})": "Nie udało się zapisać obrazu ({status})", + "The material was removed, so the node editor closed.": "Materiał został usunięty, więc edytor węzłów się zamknął.", + "The node editor could not open: {reason}": "Nie udało się otworzyć edytora węzłów: {reason}", + "Transmission color": "Kolor transmisji", + "Transmission weight": "Waga transmisji", + "Triangle": "Trójkąt", + "Trilinear": "Trójliniowe", + "Type": "Typ", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Cofnij i Ponów używają skrótów aplikacji: Mod+Z i Shift+Mod+Z.", + "UV": "UV", + "Value": "Wartość", + "Vector": "Wektor", + "vector": "wektor", + "Veins": "Żyłki", + "Voronoi": "Voronoi", + "Wave": "Fala", + "Wrap": "Zawijanie", + "Zoom in": "Powiększ", + "Zoom out": "Pomniejsz", + "Zoom to 100%": "Powiększ do 100%", + "{kind} node {id}": "Węzeł {kind} {id}", + "{nodes} nodes, {links} links": "Węzły: {nodes}, połączenia: {links}", + "{socket} input, linked from {from}": "Wejście {socket}, połączone z {from}", + "{socket} input, {type}": "Wejście {socket}, {type}", + "{socket} output, {type}": "Wyjście {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/pt-BR.json b/frontend/src/i18n/modules/graph/pt-BR.json new file mode 100644 index 00000000..58fd6d80 --- /dev/null +++ b/frontend/src/i18n/modules/graph/pt-BR.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Um grafo comporta no máximo {n} nós.", + "A node cannot feed itself.": "Um nó não pode alimentar a si mesmo.", + "A {from} output cannot feed a {to} input.": "Uma saída {from} não pode alimentar uma entrada {to}.", + "ACEScg": "ACEScg", + "Add": "Somar", + "Add a node": "Adicionar um nó", + "Add a node at the pointer": "Adicionar um nó no ponteiro", + "Add an image to a node": "Adicionar uma imagem a um nó", + "Add image": "Adicionar imagem", + "Add image...": "Adicionar imagem...", + "Adding images needs the desktop app or a service that stores uploads.": "Adicionar imagens exige o app de desktop ou um serviço que armazene envios.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Faixas", + "Base color": "Cor base", + "Base diffuse roughness": "Rugosidade difusa base", + "Base metalness": "Metalicidade base", + "Base weight": "Peso base", + "Bilinear": "Bilinear", + "Box": "Caixa", + "Brushed": "Escovado", + "Bump": "Bump", + "C": "C", + "Cell edge": "Borda da célula", + "Change a node setting": "Alterar uma configuração do nó", + "Change a node value": "Alterar um valor do nó", + "Chebyshev": "Chebyshev", + "Checker": "Xadrez", + "Clamp": "Limitar", + "Click to add a stop": "Clique para adicionar uma parada", + "Close the node editor": "Fechar o editor de nós", + "Coat color": "Cor do verniz", + "Coat ior": "IOR do verniz", + "Coat roughness": "Rugosidade do verniz", + "Coat weight": "Peso do verniz", + "colour": "cor", + "Colour 1": "Cor 1", + "Colour 2": "Cor 2", + "Colour and maths": "Cor e matemática", + "Colour ramp": "Rampa de cores", + "Colour space": "Espaço de cor", + "Connect": "Conectar", + "Connect an input to an output.": "Conecte uma entrada a uma saída.", + "Connect an output to an input.": "Conecte uma saída a uma entrada.", + "Connect or disconnect": "Conectar ou desconectar", + "Connect or disconnect the focused node": "Conectar ou desconectar o nó em foco", + "Constant": "Constante", + "Copied {n} nodes.": "{n} nós copiados.", + "Copy the selected nodes": "Copiar os nós selecionados", + "Cut the selected nodes": "Recortar os nós selecionados", + "Cylindrical": "Cilíndrica", + "Data": "Dados", + "Delete stop": "Excluir parada", + "Delete the selected nodes": "Excluir os nós selecionados", + "Density": "Densidade", + "Detail": "Detalhe", + "Disconnect": "Desconectar", + "Displacement": "Deslocamento", + "Distance": "Distância", + "Distortion": "Distorção", + "Divide": "Dividir", + "Duplicate the selected nodes": "Duplicar os nós selecionados", + "Edit the focused node; Escape returns": "Editar o nó em foco; Escape volta", + "Emission color": "Cor de emissão", + "Euclidean": "Euclidiana", + "Factor": "Fator", + "Fallback": "Reserva", + "Feature": "Característica", + "Filter": "Filtro", + "Flakes": "Flocos", + "Flip green": "Inverter o verde", + "Fractal noise": "Ruído fractal", + "Frame all nodes": "Enquadrar todos os nós", + "Fuzz color": "Cor da felpa", + "Fuzz roughness": "Rugosidade da felpa", + "Fuzz weight": "Peso da felpa", + "Gain": "Ganho", + "Geometry opacity": "Opacidade da geometria", + "Go back to the last graph the engine accepted": "Voltar ao último grafo aceito pelo motor", + "Gradient": "Gradiente", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Segure e arraste para mover a vista; arrastar com o botão do meio e rolar com dois dedos também movem", + "Image texture": "Textura de imagem", + "Images": "Imagens", + "Inputs": "Entradas", + "Interpolation": "Interpolação", + "Invert": "Inverter", + "Lacunarity": "Lacunaridade", + "Length": "Comprimento", + "Lerp": "Lerp", + "Linear": "Linear", + "Manhattan": "Manhattan", + "Mapping": "Mapeamento", + "Marble": "Mármore", + "Mask": "Máscara", + "Material output": "Saída do material", + "Math": "Matemática", + "Maximum": "Máximo", + "Metric": "Métrica", + "Minimum": "Mínimo", + "Mirror": "Espelhar", + "Mix": "Misturar", + "Move focus to the nearest node": "Mover o foco para o nó mais próximo", + "Move the selected nodes": "Mover os nós selecionados", + "Multiply": "Multiplicar", + "Nearest": "Mais próximo", + "Nearest point": "Ponto mais próximo", + "Node canvas": "Tela de nós", + "Node editor": "Editor de nós", + "Node editor keys": "Teclas do editor de nós", + "Node editor: {name}": "Editor de nós: {name}", + "Noise": "Ruído", + "normal": "normal", + "Normal map": "Mapa de normais", + "Not applied: {reason}. The material keeps its last working graph.": "Não aplicado: {reason}. O material mantém o último grafo que funcionava.", + "Nothing matches": "Nada corresponde", + "Number": "Número", + "number": "número", + "Octaves": "Oitavas", + "Offset X": "Deslocamento X", + "Offset Y": "Deslocamento Y", + "Operation": "Operação", + "Paste nodes, also into another material": "Colar nós, inclusive em outro material", + "Patterns": "Padrões", + "Phase": "Fase", + "Planar": "Plana", + "Position": "Posição", + "Power": "Potência", + "Profile": "Perfil", + "Projection": "Projeção", + "Quadratic": "Quadrática", + "Radial": "Radial", + "Randomness": "Aleatoriedade", + "Repeat": "Repetir", + "Result": "Resultado", + "Revert": "Reverter", + "Rings": "Anéis", + "Saw": "Serra", + "Scale X": "Escala X", + "Scale Y": "Escala Y", + "Second nearest": "Segundo mais próximo", + "Seed": "Semente", + "Select every node": "Selecionar todos os nós", + "Shape": "Forma", + "Show these keys": "Mostrar estas teclas", + "Sine": "Seno", + "Space bar": "Barra de espaço", + "Specular color": "Cor do especular", + "Specular ior": "IOR do especular", + "Specular roughness": "Rugosidade do especular", + "Specular roughness anisotropy": "Anisotropia da rugosidade do especular", + "Specular weight": "Peso do especular", + "Spherical": "Esférica", + "Spread": "Dispersão", + "sRGB": "sRGB", + "Stop colour": "Cor da parada", + "Stop position": "Posição da parada", + "Stop {n} at {pos}": "Parada {n} em {pos}", + "Stops": "Paradas", + "Strength": "Intensidade", + "Subtract": "Subtrair", + "Surface": "Superfície", + "That link would make a loop.": "Essa ligação criaria um laço.", + "The engine did not add the image.": "O motor não adicionou a imagem.", + "The image could not be stored ({status})": "Não foi possível armazenar a imagem ({status})", + "The material was removed, so the node editor closed.": "O material foi removido, então o editor de nós foi fechado.", + "The node editor could not open: {reason}": "Não foi possível abrir o editor de nós: {reason}", + "Transmission color": "Cor de transmissão", + "Transmission weight": "Peso de transmissão", + "Triangle": "Triangular", + "Trilinear": "Trilinear", + "Type": "Tipo", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Desfazer e refazer usam as teclas do app, Mod+Z e Shift+Mod+Z.", + "UV": "UV", + "Value": "Valor", + "Vector": "Vetor", + "vector": "vetor", + "Veins": "Veios", + "Voronoi": "Voronoi", + "Wave": "Onda", + "Wrap": "Envolvimento", + "Zoom in": "Aumentar o zoom", + "Zoom out": "Diminuir o zoom", + "Zoom to 100%": "Zoom em 100%", + "{kind} node {id}": "Nó {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} nós, {links} ligações", + "{socket} input, linked from {from}": "Entrada {socket}, ligada a partir de {from}", + "{socket} input, {type}": "Entrada {socket}, {type}", + "{socket} output, {type}": "Saída {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/ru.json b/frontend/src/i18n/modules/graph/ru.json new file mode 100644 index 00000000..ac615a9d --- /dev/null +++ b/frontend/src/i18n/modules/graph/ru.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Граф может содержать не более {n} узлов.", + "A node cannot feed itself.": "Узел не может питать сам себя.", + "A {from} output cannot feed a {to} input.": "Выход {from} не может питать вход {to}.", + "ACEScg": "ACEScg", + "Add": "Сложение", + "Add a node": "Добавить узел", + "Add a node at the pointer": "Добавить узел у курсора", + "Add an image to a node": "Добавить изображение в узел", + "Add image": "Добавить изображение", + "Add image...": "Добавить изображение...", + "Adding images needs the desktop app or a service that stores uploads.": "Для добавления изображений нужно настольное приложение или служба, сохраняющая загрузки.", + "Alpha": "Альфа", + "B": "B", + "Bands": "Полосы", + "Base color": "Базовый цвет", + "Base diffuse roughness": "Базовая диффузная шероховатость", + "Base metalness": "Базовая металличность", + "Base weight": "Базовый вес", + "Bilinear": "Билинейная", + "Box": "Куб", + "Brushed": "Шлифованный", + "Bump": "Бамп", + "C": "C", + "Cell edge": "Край ячейки", + "Change a node setting": "Изменить настройку узла", + "Change a node value": "Изменить значение узла", + "Chebyshev": "Чебышёва", + "Checker": "Шахматка", + "Clamp": "Ограничение", + "Click to add a stop": "Щёлкните, чтобы добавить опорную точку", + "Close the node editor": "Закрыть редактор узлов", + "Coat color": "Цвет покрытия", + "Coat ior": "IOR покрытия", + "Coat roughness": "Шероховатость покрытия", + "Coat weight": "Вес покрытия", + "colour": "цвет", + "Colour 1": "Цвет 1", + "Colour 2": "Цвет 2", + "Colour and maths": "Цвет и математика", + "Colour ramp": "Цветовая шкала", + "Colour space": "Цветовое пространство", + "Connect": "Соединить", + "Connect an input to an output.": "Соедините вход с выходом.", + "Connect an output to an input.": "Соедините выход со входом.", + "Connect or disconnect": "Соединить или разъединить", + "Connect or disconnect the focused node": "Соединить или разъединить узел в фокусе", + "Constant": "Константа", + "Copied {n} nodes.": "Скопировано узлов: {n}.", + "Copy the selected nodes": "Копировать выбранные узлы", + "Cut the selected nodes": "Вырезать выбранные узлы", + "Cylindrical": "Цилиндрическая", + "Data": "Данные", + "Delete stop": "Удалить опорную точку", + "Delete the selected nodes": "Удалить выбранные узлы", + "Density": "Плотность", + "Detail": "Детализация", + "Disconnect": "Разъединить", + "Displacement": "Смещение", + "Distance": "Расстояние", + "Distortion": "Искажение", + "Divide": "Деление", + "Duplicate the selected nodes": "Дублировать выбранные узлы", + "Edit the focused node; Escape returns": "Редактировать узел в фокусе; Escape возвращает назад", + "Emission color": "Цвет излучения", + "Euclidean": "Евклидова", + "Factor": "Коэффициент", + "Fallback": "Запасное значение", + "Feature": "Особенность", + "Filter": "Фильтр", + "Flakes": "Блёстки", + "Flip green": "Инвертировать зелёный", + "Fractal noise": "Фрактальный шум", + "Frame all nodes": "Показать все узлы", + "Fuzz color": "Цвет ворса", + "Fuzz roughness": "Шероховатость ворса", + "Fuzz weight": "Вес ворса", + "Gain": "Усиление", + "Geometry opacity": "Непрозрачность геометрии", + "Go back to the last graph the engine accepted": "Вернуться к последнему графу, принятому движком", + "Gradient": "Градиент", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Удерживайте и перетаскивайте для сдвига; сдвиг также работает средней кнопкой и прокруткой двумя пальцами", + "Image texture": "Текстура изображения", + "Images": "Изображения", + "Inputs": "Входы", + "Interpolation": "Интерполяция", + "Invert": "Инверсия", + "Lacunarity": "Лакунарность", + "Length": "Длина", + "Lerp": "Лерп", + "Linear": "Линейная", + "Manhattan": "Манхэттенская", + "Mapping": "Проецирование", + "Marble": "Мрамор", + "Mask": "Маска", + "Material output": "Выход материала", + "Math": "Математика", + "Maximum": "Максимум", + "Metric": "Метрика", + "Minimum": "Минимум", + "Mirror": "Зеркало", + "Mix": "Смешивание", + "Move focus to the nearest node": "Перевести фокус на ближайший узел", + "Move the selected nodes": "Переместить выбранные узлы", + "Multiply": "Умножение", + "Nearest": "Ближайший", + "Nearest point": "Ближайшая точка", + "Node canvas": "Полотно узлов", + "Node editor": "Редактор узлов", + "Node editor keys": "Клавиши редактора узлов", + "Node editor: {name}": "Редактор узлов: {name}", + "Noise": "Шум", + "normal": "нормаль", + "Normal map": "Карта нормалей", + "Not applied: {reason}. The material keeps its last working graph.": "Не применено: {reason}. Материал сохраняет последний рабочий граф.", + "Nothing matches": "Ничего не найдено", + "Number": "Число", + "number": "число", + "Octaves": "Октавы", + "Offset X": "Смещение по X", + "Offset Y": "Смещение по Y", + "Operation": "Операция", + "Paste nodes, also into another material": "Вставить узлы, в том числе в другой материал", + "Patterns": "Узоры", + "Phase": "Фаза", + "Planar": "Плоская", + "Position": "Положение", + "Power": "Степень", + "Profile": "Профиль", + "Projection": "Проекция", + "Quadratic": "Квадратичная", + "Radial": "Радиальная", + "Randomness": "Случайность", + "Repeat": "Повтор", + "Result": "Результат", + "Revert": "Вернуть", + "Rings": "Кольца", + "Saw": "Пила", + "Scale X": "Масштаб по X", + "Scale Y": "Масштаб по Y", + "Second nearest": "Вторая ближайшая", + "Seed": "Начальное значение", + "Select every node": "Выделить все узлы", + "Shape": "Форма", + "Show these keys": "Показать эти клавиши", + "Sine": "Синус", + "Space bar": "Пробел", + "Specular color": "Цвет бликов", + "Specular ior": "IOR бликов", + "Specular roughness": "Шероховатость бликов", + "Specular roughness anisotropy": "Анизотропия шероховатости бликов", + "Specular weight": "Вес бликов", + "Spherical": "Сферическая", + "Spread": "Разброс", + "sRGB": "sRGB", + "Stop colour": "Цвет опорной точки", + "Stop position": "Положение опорной точки", + "Stop {n} at {pos}": "Опорная точка {n} в позиции {pos}", + "Stops": "Опорные точки", + "Strength": "Сила", + "Subtract": "Вычитание", + "Surface": "Поверхность", + "That link would make a loop.": "Эта связь создаст цикл.", + "The engine did not add the image.": "Движок не добавил изображение.", + "The image could not be stored ({status})": "Не удалось сохранить изображение ({status})", + "The material was removed, so the node editor closed.": "Материал удалён, поэтому редактор узлов закрыт.", + "The node editor could not open: {reason}": "Не удалось открыть редактор узлов: {reason}", + "Transmission color": "Цвет пропускания", + "Transmission weight": "Вес пропускания", + "Triangle": "Треугольная", + "Trilinear": "Трилинейная", + "Type": "Тип", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Отмена и повтор используют клавиши приложения, Mod+Z и Shift+Mod+Z.", + "UV": "UV", + "Value": "Значение", + "Vector": "Вектор", + "vector": "вектор", + "Veins": "Прожилки", + "Voronoi": "Воронова", + "Wave": "Волна", + "Wrap": "Обёртывание", + "Zoom in": "Увеличить", + "Zoom out": "Уменьшить", + "Zoom to 100%": "Масштаб 100%", + "{kind} node {id}": "Узел {kind} {id}", + "{nodes} nodes, {links} links": "Узлов: {nodes}, связей: {links}", + "{socket} input, linked from {from}": "Вход {socket}, связан с {from}", + "{socket} input, {type}": "Вход {socket}, {type}", + "{socket} output, {type}": "Выход {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/strings.json b/frontend/src/i18n/modules/graph/strings.json new file mode 100644 index 00000000..e5a4d483 --- /dev/null +++ b/frontend/src/i18n/modules/graph/strings.json @@ -0,0 +1,191 @@ +[ + "A", + "A graph holds at most {n} nodes.", + "A node cannot feed itself.", + "A {from} output cannot feed a {to} input.", + "ACEScg", + "Add", + "Add a node", + "Add a node at the pointer", + "Add an image to a node", + "Add image", + "Add image...", + "Adding images needs the desktop app or a service that stores uploads.", + "Alpha", + "B", + "Bands", + "Base color", + "Base diffuse roughness", + "Base metalness", + "Base weight", + "Bilinear", + "Box", + "Brushed", + "Bump", + "C", + "Cell edge", + "Change a node setting", + "Change a node value", + "Chebyshev", + "Checker", + "Clamp", + "Click to add a stop", + "Close the node editor", + "Coat color", + "Coat ior", + "Coat roughness", + "Coat weight", + "colour", + "Colour 1", + "Colour 2", + "Colour and maths", + "Colour ramp", + "Colour space", + "Connect", + "Connect an input to an output.", + "Connect an output to an input.", + "Connect or disconnect", + "Connect or disconnect the focused node", + "Constant", + "Copied {n} nodes.", + "Copy the selected nodes", + "Cut the selected nodes", + "Cylindrical", + "Data", + "Delete stop", + "Delete the selected nodes", + "Density", + "Detail", + "Disconnect", + "Displacement", + "Distance", + "Distortion", + "Divide", + "Duplicate the selected nodes", + "Edit the focused node; Escape returns", + "Emission color", + "Euclidean", + "Factor", + "Fallback", + "Feature", + "Filter", + "Flakes", + "Flip green", + "Fractal noise", + "Frame all nodes", + "Fuzz color", + "Fuzz roughness", + "Fuzz weight", + "Gain", + "Geometry opacity", + "Go back to the last graph the engine accepted", + "Gradient", + "Hold and drag to pan; middle drag and two-finger scroll pan too", + "Image texture", + "Images", + "Inputs", + "Interpolation", + "Invert", + "Lacunarity", + "Length", + "Lerp", + "Linear", + "Manhattan", + "Mapping", + "Marble", + "Mask", + "Material output", + "Math", + "Maximum", + "Metric", + "Minimum", + "Mirror", + "Mix", + "Move focus to the nearest node", + "Move the selected nodes", + "Multiply", + "Nearest", + "Nearest point", + "Node canvas", + "Node editor", + "Node editor keys", + "Node editor: {name}", + "Noise", + "normal", + "Normal map", + "Not applied: {reason}. The material keeps its last working graph.", + "Nothing matches", + "Number", + "number", + "Octaves", + "Offset X", + "Offset Y", + "Operation", + "Paste nodes, also into another material", + "Patterns", + "Phase", + "Planar", + "Position", + "Power", + "Profile", + "Projection", + "Quadratic", + "Radial", + "Randomness", + "Repeat", + "Result", + "Revert", + "Rings", + "Saw", + "Scale X", + "Scale Y", + "Second nearest", + "Seed", + "Select every node", + "Shape", + "Show these keys", + "Sine", + "Space bar", + "Specular color", + "Specular ior", + "Specular roughness", + "Specular roughness anisotropy", + "Specular weight", + "Spherical", + "Spread", + "sRGB", + "Stop colour", + "Stop position", + "Stop {n} at {pos}", + "Stops", + "Strength", + "Subtract", + "Surface", + "That link would make a loop.", + "The engine did not add the image.", + "The image could not be stored ({status})", + "The material was removed, so the node editor closed.", + "The node editor could not open: {reason}", + "Transmission color", + "Transmission weight", + "Triangle", + "Trilinear", + "Type", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.", + "UV", + "Value", + "Vector", + "vector", + "Veins", + "Voronoi", + "Wave", + "Wrap", + "Zoom in", + "Zoom out", + "Zoom to 100%", + "{kind} node {id}", + "{nodes} nodes, {links} links", + "{socket} input, linked from {from}", + "{socket} input, {type}", + "{socket} output, {type}" +] diff --git a/frontend/src/i18n/modules/graph/sv.json b/frontend/src/i18n/modules/graph/sv.json new file mode 100644 index 00000000..3a0295cf --- /dev/null +++ b/frontend/src/i18n/modules/graph/sv.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "En graf rymmer högst {n} noder.", + "A node cannot feed itself.": "En nod kan inte mata sig själv.", + "A {from} output cannot feed a {to} input.": "En {from}-utgång kan inte mata en {to}-ingång.", + "ACEScg": "ACEScg", + "Add": "Addera", + "Add a node": "Lägg till en nod", + "Add a node at the pointer": "Lägg till en nod vid pekaren", + "Add an image to a node": "Lägg till en bild i en nod", + "Add image": "Lägg till bild", + "Add image...": "Lägg till bild...", + "Adding images needs the desktop app or a service that stores uploads.": "Att lägga till bilder kräver skrivbordsappen eller en tjänst som lagrar uppladdningar.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Band", + "Base color": "Basfärg", + "Base diffuse roughness": "Diffus basråhet", + "Base metalness": "Bas-metallighet", + "Base weight": "Basvikt", + "Bilinear": "Bilinjär", + "Box": "Box", + "Brushed": "Borstad", + "Bump": "Bump", + "C": "C", + "Cell edge": "Cellkant", + "Change a node setting": "Ändra en nodinställning", + "Change a node value": "Ändra ett nodvärde", + "Chebyshev": "Chebyshev", + "Checker": "Schackrutor", + "Clamp": "Begränsa", + "Click to add a stop": "Klicka för att lägga till ett stopp", + "Close the node editor": "Stäng nodredigeraren", + "Coat color": "Coatingfärg", + "Coat ior": "Coating-IOR", + "Coat roughness": "Coatingråhet", + "Coat weight": "Coatingvikt", + "colour": "färg", + "Colour 1": "Färg 1", + "Colour 2": "Färg 2", + "Colour and maths": "Färg och matematik", + "Colour ramp": "Färgramp", + "Colour space": "Färgrymd", + "Connect": "Anslut", + "Connect an input to an output.": "Anslut en ingång till en utgång.", + "Connect an output to an input.": "Anslut en utgång till en ingång.", + "Connect or disconnect": "Anslut eller koppla från", + "Connect or disconnect the focused node": "Anslut eller koppla från noden med fokus", + "Constant": "Konstant", + "Copied {n} nodes.": "Kopierade {n} noder.", + "Copy the selected nodes": "Kopiera de markerade noderna", + "Cut the selected nodes": "Klipp ut de markerade noderna", + "Cylindrical": "Cylindrisk", + "Data": "Data", + "Delete stop": "Ta bort stopp", + "Delete the selected nodes": "Radera de markerade noderna", + "Density": "Täthet", + "Detail": "Detalj", + "Disconnect": "Koppla från", + "Displacement": "Displacement", + "Distance": "Avstånd", + "Distortion": "Distorsion", + "Divide": "Dividera", + "Duplicate the selected nodes": "Duplicera de markerade noderna", + "Edit the focused node; Escape returns": "Redigera noden med fokus; Escape går tillbaka", + "Emission color": "Emissionsfärg", + "Euclidean": "Euklidisk", + "Factor": "Faktor", + "Fallback": "Reservvärde", + "Feature": "Egenskap", + "Filter": "Filter", + "Flakes": "Flingor", + "Flip green": "Vänd grönt", + "Fractal noise": "Fraktalt brus", + "Frame all nodes": "Rama in alla noder", + "Fuzz color": "Fuzz-färg", + "Fuzz roughness": "Fuzz-råhet", + "Fuzz weight": "Fuzz-vikt", + "Gain": "Förstärkning", + "Geometry opacity": "Geometriopacitet", + "Go back to the last graph the engine accepted": "Gå tillbaka till den senaste grafen som motorn godtog", + "Gradient": "Gradient", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Håll och dra för att panorera; dra med mittknappen och rulla med två fingrar panorerar också", + "Image texture": "Bildtextur", + "Images": "Bilder", + "Inputs": "Ingångar", + "Interpolation": "Interpolering", + "Invert": "Invertera", + "Lacunarity": "Lakunaritet", + "Length": "Längd", + "Lerp": "Lerp", + "Linear": "Linjär", + "Manhattan": "Manhattan", + "Mapping": "Mappning", + "Marble": "Marmor", + "Mask": "Mask", + "Material output": "Materialutgång", + "Math": "Matematik", + "Maximum": "Maximum", + "Metric": "Metrik", + "Minimum": "Minimum", + "Mirror": "Spegla", + "Mix": "Blanda", + "Move focus to the nearest node": "Flytta fokus till närmaste nod", + "Move the selected nodes": "Flytta de markerade noderna", + "Multiply": "Multiplicera", + "Nearest": "Närmaste", + "Nearest point": "Närmaste punkt", + "Node canvas": "Nodcanvas", + "Node editor": "Nodredigerare", + "Node editor keys": "Tangenter i nodredigeraren", + "Node editor: {name}": "Nodredigerare: {name}", + "Noise": "Brus", + "normal": "normal", + "Normal map": "Normal map", + "Not applied: {reason}. The material keeps its last working graph.": "Inte tillämpat: {reason}. Materialet behåller sin senaste fungerande graf.", + "Nothing matches": "Inget matchar", + "Number": "Tal", + "number": "tal", + "Octaves": "Oktaver", + "Offset X": "Förskjutning X", + "Offset Y": "Förskjutning Y", + "Operation": "Operation", + "Paste nodes, also into another material": "Klistra in noder, även i ett annat material", + "Patterns": "Mönster", + "Phase": "Fas", + "Planar": "Plan", + "Position": "Position", + "Power": "Upphöjt till", + "Profile": "Profil", + "Projection": "Projektion", + "Quadratic": "Kvadratisk", + "Radial": "Radiell", + "Randomness": "Slumpmässighet", + "Repeat": "Upprepa", + "Result": "Resultat", + "Revert": "Återställ", + "Rings": "Ringar", + "Saw": "Sågtand", + "Scale X": "Skala X", + "Scale Y": "Skala Y", + "Second nearest": "Näst närmaste", + "Seed": "Seed", + "Select every node": "Markera alla noder", + "Shape": "Form", + "Show these keys": "Visa de här tangenterna", + "Sine": "Sinus", + "Space bar": "Mellanslag", + "Specular color": "Spekulär färg", + "Specular ior": "Spekulär IOR", + "Specular roughness": "Spekulär råhet", + "Specular roughness anisotropy": "Anisotropi för spekulär råhet", + "Specular weight": "Spekulär vikt", + "Spherical": "Sfärisk", + "Spread": "Spridning", + "sRGB": "sRGB", + "Stop colour": "Stoppfärg", + "Stop position": "Stoppposition", + "Stop {n} at {pos}": "Stopp {n} vid {pos}", + "Stops": "Stopp", + "Strength": "Styrka", + "Subtract": "Subtrahera", + "Surface": "Yta", + "That link would make a loop.": "Den länken skulle skapa en slinga.", + "The engine did not add the image.": "Motorn lade inte till bilden.", + "The image could not be stored ({status})": "Bilden kunde inte lagras ({status})", + "The material was removed, so the node editor closed.": "Materialet togs bort, så nodredigeraren stängdes.", + "The node editor could not open: {reason}": "Nodredigeraren kunde inte öppnas: {reason}", + "Transmission color": "Transmissionsfärg", + "Transmission weight": "Transmissionsvikt", + "Triangle": "Triangel", + "Trilinear": "Trilinjär", + "Type": "Typ", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Ångra och gör om använder appens tangenter, Mod+Z och Shift+Mod+Z.", + "UV": "UV", + "Value": "Värde", + "Vector": "Vektor", + "vector": "vektor", + "Veins": "Ådror", + "Voronoi": "Voronoi", + "Wave": "Våg", + "Wrap": "Wrap", + "Zoom in": "Zooma in", + "Zoom out": "Zooma ut", + "Zoom to 100%": "Zooma till 100%", + "{kind} node {id}": "{kind}-nod {id}", + "{nodes} nodes, {links} links": "{nodes} noder, {links} länkar", + "{socket} input, linked from {from}": "{socket}-ingång, länkad från {from}", + "{socket} input, {type}": "{socket}-ingång, {type}", + "{socket} output, {type}": "{socket}-utgång, {type}" +} diff --git a/frontend/src/i18n/modules/graph/th.json b/frontend/src/i18n/modules/graph/th.json new file mode 100644 index 00000000..71d6a90a --- /dev/null +++ b/frontend/src/i18n/modules/graph/th.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "กราฟมีโหนดได้สูงสุด {n} โหนด", + "A node cannot feed itself.": "โหนดป้อนค่าให้ตัวเองไม่ได้", + "A {from} output cannot feed a {to} input.": "เอาต์พุต {from} ป้อนอินพุต {to} ไม่ได้", + "ACEScg": "ACEScg", + "Add": "บวก", + "Add a node": "เพิ่มโหนด", + "Add a node at the pointer": "เพิ่มโหนดที่ตำแหน่งตัวชี้", + "Add an image to a node": "เพิ่มรูปภาพให้โหนด", + "Add image": "เพิ่มรูปภาพ", + "Add image...": "เพิ่มรูปภาพ...", + "Adding images needs the desktop app or a service that stores uploads.": "การเพิ่มรูปภาพต้องใช้แอปเดสก์ท็อปหรือบริการที่เก็บไฟล์อัปโหลด", + "Alpha": "แอลฟา", + "B": "B", + "Bands": "แถบ", + "Base color": "สีฐาน", + "Base diffuse roughness": "ความหยาบดิฟฟิวส์ของฐาน", + "Base metalness": "ความเป็นโลหะของฐาน", + "Base weight": "น้ำหนักฐาน", + "Bilinear": "ไบลิเนียร์", + "Box": "กล่อง", + "Brushed": "ขัดเป็นเส้น", + "Bump": "บัมพ์", + "C": "C", + "Cell edge": "ขอบเซลล์", + "Change a node setting": "เปลี่ยนการตั้งค่าโหนด", + "Change a node value": "เปลี่ยนค่าโหนด", + "Chebyshev": "เชบีเชฟ", + "Checker": "ตารางหมากรุก", + "Clamp": "จำกัดขอบ", + "Click to add a stop": "คลิกเพื่อเพิ่มจุดหยุด", + "Close the node editor": "ปิดตัวแก้ไขโหนด", + "Coat color": "สีชั้นเคลือบ", + "Coat ior": "IOR ชั้นเคลือบ", + "Coat roughness": "ความหยาบชั้นเคลือบ", + "Coat weight": "น้ำหนักชั้นเคลือบ", + "colour": "สี", + "Colour 1": "สี 1", + "Colour 2": "สี 2", + "Colour and maths": "สีและคณิตศาสตร์", + "Colour ramp": "แถบไล่สี", + "Colour space": "ปริภูมิสี", + "Connect": "เชื่อมต่อ", + "Connect an input to an output.": "เชื่อมอินพุตเข้ากับเอาต์พุต", + "Connect an output to an input.": "เชื่อมเอาต์พุตเข้ากับอินพุต", + "Connect or disconnect": "เชื่อมต่อหรือตัดการเชื่อมต่อ", + "Connect or disconnect the focused node": "เชื่อมต่อหรือตัดการเชื่อมต่อโหนดที่โฟกัส", + "Constant": "ค่าคงที่", + "Copied {n} nodes.": "คัดลอก {n} โหนดแล้ว", + "Copy the selected nodes": "คัดลอกโหนดที่เลือก", + "Cut the selected nodes": "ตัดโหนดที่เลือก", + "Cylindrical": "ทรงกระบอก", + "Data": "ข้อมูล", + "Delete stop": "ลบจุดหยุด", + "Delete the selected nodes": "ลบโหนดที่เลือก", + "Density": "ความหนาแน่น", + "Detail": "รายละเอียด", + "Disconnect": "ตัดการเชื่อมต่อ", + "Displacement": "ดิสเพลซเมนต์", + "Distance": "ระยะทาง", + "Distortion": "การบิดเบือน", + "Divide": "หาร", + "Duplicate the selected nodes": "ทำซ้ำโหนดที่เลือก", + "Edit the focused node; Escape returns": "แก้ไขโหนดที่โฟกัส กด Escape เพื่อกลับ", + "Emission color": "สีการเปล่งแสง", + "Euclidean": "ยูคลิด", + "Factor": "ตัวประกอบ", + "Fallback": "ค่าสำรอง", + "Feature": "ฟีเจอร์", + "Filter": "ตัวกรอง", + "Flakes": "เกล็ด", + "Flip green": "กลับด้านสีเขียว", + "Fractal noise": "นอยส์แบบเศษส่วน", + "Frame all nodes": "แสดงทุกโหนดในเฟรม", + "Fuzz color": "สีขน", + "Fuzz roughness": "ความหยาบของขน", + "Fuzz weight": "น้ำหนักขน", + "Gain": "เกน", + "Geometry opacity": "ความทึบของเรขาคณิต", + "Go back to the last graph the engine accepted": "ย้อนกลับไปยังกราฟล่าสุดที่เอนจินยอมรับ", + "Gradient": "ไล่ระดับ", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "กดค้างแล้วลากเพื่อเลื่อนมุมมอง การลากด้วยปุ่มกลางและการเลื่อนสองนิ้วก็เลื่อนมุมมองได้", + "Image texture": "เท็กซ์เจอร์รูปภาพ", + "Images": "รูปภาพ", + "Inputs": "อินพุต", + "Interpolation": "การประมาณค่าช่วง", + "Invert": "กลับค่า", + "Lacunarity": "ลาคูนาริตี", + "Length": "ความยาว", + "Lerp": "Lerp", + "Linear": "เชิงเส้น", + "Manhattan": "แมนฮัตตัน", + "Mapping": "การแมป", + "Marble": "หินอ่อน", + "Mask": "มาสก์", + "Material output": "เอาต์พุตแมทีเรียล", + "Math": "คณิตศาสตร์", + "Maximum": "สูงสุด", + "Metric": "เมตริก", + "Minimum": "ต่ำสุด", + "Mirror": "กระจกเงา", + "Mix": "ผสม", + "Move focus to the nearest node": "ย้ายโฟกัสไปยังโหนดที่ใกล้ที่สุด", + "Move the selected nodes": "ย้ายโหนดที่เลือก", + "Multiply": "คูณ", + "Nearest": "ใกล้ที่สุด", + "Nearest point": "จุดที่ใกล้ที่สุด", + "Node canvas": "แคนวาสโหนด", + "Node editor": "ตัวแก้ไขโหนด", + "Node editor keys": "คีย์ของตัวแก้ไขโหนด", + "Node editor: {name}": "ตัวแก้ไขโหนด: {name}", + "Noise": "นอยส์", + "normal": "นอร์มอล", + "Normal map": "นอร์มอลแมป", + "Not applied: {reason}. The material keeps its last working graph.": "ไม่ได้นำไปใช้: {reason} แมทีเรียลยังใช้กราฟล่าสุดที่ทำงานได้", + "Nothing matches": "ไม่มีรายการที่ตรงกัน", + "Number": "ตัวเลข", + "number": "ตัวเลข", + "Octaves": "อ็อกเทฟ", + "Offset X": "ออฟเซ็ต X", + "Offset Y": "ออฟเซ็ต Y", + "Operation": "การดำเนินการ", + "Paste nodes, also into another material": "วางโหนด รวมถึงวางในแมทีเรียลอื่น", + "Patterns": "แพตเทิร์น", + "Phase": "เฟส", + "Planar": "ระนาบ", + "Position": "ตำแหน่ง", + "Power": "ยกกำลัง", + "Profile": "โพรไฟล์", + "Projection": "การโปรเจกต์", + "Quadratic": "กำลังสอง", + "Radial": "รัศมี", + "Randomness": "ความสุ่ม", + "Repeat": "การวนซ้ำ", + "Result": "ผลลัพธ์", + "Revert": "ย้อนกลับ", + "Rings": "วงแหวน", + "Saw": "ฟันเลื่อย", + "Scale X": "สเกล X", + "Scale Y": "สเกล Y", + "Second nearest": "ใกล้ที่สุดอันดับสอง", + "Seed": "ซีด", + "Select every node": "เลือกทุกโหนด", + "Shape": "รูปร่าง", + "Show these keys": "แสดงคีย์เหล่านี้", + "Sine": "ไซน์", + "Space bar": "แป้นเว้นวรรค", + "Specular color": "สีสเปกคูลาร์", + "Specular ior": "IOR สเปกคูลาร์", + "Specular roughness": "ความหยาบสเปกคูลาร์", + "Specular roughness anisotropy": "แอนไอโซทรอปีความหยาบสเปกคูลาร์", + "Specular weight": "น้ำหนักสเปกคูลาร์", + "Spherical": "ทรงกลม", + "Spread": "การกระจาย", + "sRGB": "sRGB", + "Stop colour": "สีจุดหยุด", + "Stop position": "ตำแหน่งจุดหยุด", + "Stop {n} at {pos}": "จุดหยุด {n} ที่ {pos}", + "Stops": "จุดหยุด", + "Strength": "ความเข้ม", + "Subtract": "ลบ", + "Surface": "พื้นผิว", + "That link would make a loop.": "การเชื่อมนั้นจะทำให้เกิดวงวน", + "The engine did not add the image.": "เอนจินไม่ได้เพิ่มรูปภาพ", + "The image could not be stored ({status})": "เก็บรูปภาพไม่ได้ ({status})", + "The material was removed, so the node editor closed.": "แมทีเรียลถูกลบ ตัวแก้ไขโหนดจึงปิด", + "The node editor could not open: {reason}": "เปิดตัวแก้ไขโหนดไม่ได้: {reason}", + "Transmission color": "สีการส่องผ่าน", + "Transmission weight": "น้ำหนักการส่องผ่าน", + "Triangle": "สามเหลี่ยม", + "Trilinear": "ไตรลิเนียร์", + "Type": "ชนิด", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "เลิกทำและทำซ้ำใช้ปุ่มของแอป คือ Mod+Z และ Shift+Mod+Z", + "UV": "UV", + "Value": "ค่า", + "Vector": "เวกเตอร์", + "vector": "เวกเตอร์", + "Veins": "เส้นลาย", + "Voronoi": "วอรอนอย", + "Wave": "คลื่น", + "Wrap": "การห่อ", + "Zoom in": "ซูมเข้า", + "Zoom out": "ซูมออก", + "Zoom to 100%": "ซูมเป็น 100%", + "{kind} node {id}": "โหนด {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} โหนด, {links} การเชื่อม", + "{socket} input, linked from {from}": "อินพุต {socket} เชื่อมจาก {from}", + "{socket} input, {type}": "อินพุต {socket}, {type}", + "{socket} output, {type}": "เอาต์พุต {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/tr.json b/frontend/src/i18n/modules/graph/tr.json new file mode 100644 index 00000000..96bab364 --- /dev/null +++ b/frontend/src/i18n/modules/graph/tr.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Bir grafik en fazla {n} düğüm içerebilir.", + "A node cannot feed itself.": "Bir düğüm kendini besleyemez.", + "A {from} output cannot feed a {to} input.": "{from} çıktısı bir {to} girdisini besleyemez.", + "ACEScg": "ACEScg", + "Add": "Topla", + "Add a node": "Düğüm ekle", + "Add a node at the pointer": "Düğümü imlecin olduğu yere ekle", + "Add an image to a node": "Bir düğüme görüntü ekle", + "Add image": "Görüntü ekle", + "Add image...": "Görüntü ekle...", + "Adding images needs the desktop app or a service that stores uploads.": "Görüntü eklemek için masaüstü uygulaması veya yüklemeleri saklayan bir hizmet gerekir.", + "Alpha": "Alfa", + "B": "B", + "Bands": "Bantlar", + "Base color": "Temel renk", + "Base diffuse roughness": "Temel yaygın pürüzlülük", + "Base metalness": "Temel metaliklik", + "Base weight": "Temel ağırlık", + "Bilinear": "Bilinear", + "Box": "Kutu", + "Brushed": "Fırçalanmış", + "Bump": "Bump", + "C": "C", + "Cell edge": "Hücre kenarı", + "Change a node setting": "Düğüm ayarını değiştir", + "Change a node value": "Düğüm değerini değiştir", + "Chebyshev": "Chebyshev", + "Checker": "Dama tahtası", + "Clamp": "Sınırla", + "Click to add a stop": "Bir durak eklemek için tıklayın", + "Close the node editor": "Düğüm düzenleyicisini kapat", + "Coat color": "Kaplama rengi", + "Coat ior": "Kaplama IOR'u", + "Coat roughness": "Kaplama pürüzlülüğü", + "Coat weight": "Kaplama ağırlığı", + "colour": "renk", + "Colour 1": "Renk 1", + "Colour 2": "Renk 2", + "Colour and maths": "Renk ve matematik", + "Colour ramp": "Renk rampası", + "Colour space": "Renk uzayı", + "Connect": "Bağla", + "Connect an input to an output.": "Bir girdiyi bir çıktıya bağlayın.", + "Connect an output to an input.": "Bir çıktıyı bir girdiye bağlayın.", + "Connect or disconnect": "Bağla veya bağlantıyı kes", + "Connect or disconnect the focused node": "Odaktaki düğümü bağla veya bağlantısını kes", + "Constant": "Sabit", + "Copied {n} nodes.": "{n} düğüm kopyalandı.", + "Copy the selected nodes": "Seçili düğümleri kopyala", + "Cut the selected nodes": "Seçili düğümleri kes", + "Cylindrical": "Silindirik", + "Data": "Veri", + "Delete stop": "Durağı sil", + "Delete the selected nodes": "Seçili düğümleri sil", + "Density": "Yoğunluk", + "Detail": "Detay", + "Disconnect": "Bağlantıyı kes", + "Displacement": "Yer değiştirme", + "Distance": "Mesafe", + "Distortion": "Bozulma", + "Divide": "Böl", + "Duplicate the selected nodes": "Seçili düğümleri çoğalt", + "Edit the focused node; Escape returns": "Odaktaki düğümü düzenle; Escape geri döndürür", + "Emission color": "Emisyon rengi", + "Euclidean": "Öklid", + "Factor": "Çarpan", + "Fallback": "Yedek", + "Feature": "Öğe", + "Filter": "Filtre", + "Flakes": "Pullar", + "Flip green": "Yeşili çevir", + "Fractal noise": "Fraktal gürültü", + "Frame all nodes": "Tüm düğümleri çerçevele", + "Fuzz color": "Tüy rengi", + "Fuzz roughness": "Tüy pürüzlülüğü", + "Fuzz weight": "Tüy ağırlığı", + "Gain": "Kazanç", + "Geometry opacity": "Geometri opaklığı", + "Go back to the last graph the engine accepted": "Motorun kabul ettiği son grafiğe dön", + "Gradient": "Gradyan", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Kaydırmak için basılı tutup sürükleyin; orta tuşla sürükleme ve iki parmakla kaydırma da kaydırır", + "Image texture": "Görüntü dokusu", + "Images": "Görüntüler", + "Inputs": "Girdiler", + "Interpolation": "Ara değerleme", + "Invert": "Ters çevir", + "Lacunarity": "Boşluklülük", + "Length": "Uzunluk", + "Lerp": "Lerp", + "Linear": "Doğrusal", + "Manhattan": "Manhattan", + "Mapping": "Eşleme", + "Marble": "Mermer", + "Mask": "Maske", + "Material output": "Malzeme çıktısı", + "Math": "Matematik", + "Maximum": "Maksimum", + "Metric": "Metrik", + "Minimum": "Minimum", + "Mirror": "Yansıt", + "Mix": "Karıştır", + "Move focus to the nearest node": "Odağı en yakın düğüme taşı", + "Move the selected nodes": "Seçili düğümleri taşı", + "Multiply": "Çarp", + "Nearest": "En yakın", + "Nearest point": "En yakın nokta", + "Node canvas": "Düğüm tuvali", + "Node editor": "Düğüm düzenleyicisi", + "Node editor keys": "Düğüm düzenleyicisi tuşları", + "Node editor: {name}": "Düğüm düzenleyicisi: {name}", + "Noise": "Gürültü", + "normal": "normal", + "Normal map": "Normal haritası", + "Not applied: {reason}. The material keeps its last working graph.": "Uygulanmadı: {reason}. Malzeme son çalışan grafiğini korur.", + "Nothing matches": "Eşleşen yok", + "Number": "Sayı", + "number": "sayı", + "Octaves": "Oktavlar", + "Offset X": "X kaydırma", + "Offset Y": "Y kaydırma", + "Operation": "İşlem", + "Paste nodes, also into another material": "Düğümleri yapıştır, başka bir malzemeye de", + "Patterns": "Desenler", + "Phase": "Faz", + "Planar": "Düzlemsel", + "Position": "Konum", + "Power": "Üs", + "Profile": "Profil", + "Projection": "İzdüşüm", + "Quadratic": "İkinci derece", + "Radial": "Radyal", + "Randomness": "Rastgelelik", + "Repeat": "Tekrarla", + "Result": "Sonuç", + "Revert": "Geri al", + "Rings": "Halkalar", + "Saw": "Testere", + "Scale X": "X ölçeği", + "Scale Y": "Y ölçeği", + "Second nearest": "İkinci en yakın", + "Seed": "Tohum", + "Select every node": "Tüm düğümleri seç", + "Shape": "Şekil", + "Show these keys": "Bu tuşları göster", + "Sine": "Sinüs", + "Space bar": "Boşluk tuşu", + "Specular color": "Yansıma rengi", + "Specular ior": "Yansıma IOR'u", + "Specular roughness": "Yansıma pürüzlülüğü", + "Specular roughness anisotropy": "Yansıma pürüzlülüğü anizotropisi", + "Specular weight": "Yansıma ağırlığı", + "Spherical": "Küresel", + "Spread": "Yayılım", + "sRGB": "sRGB", + "Stop colour": "Durak rengi", + "Stop position": "Durak konumu", + "Stop {n} at {pos}": "{n}. durak, konum {pos}", + "Stops": "Duraklar", + "Strength": "Güç", + "Subtract": "Çıkar", + "Surface": "Yüzey", + "That link would make a loop.": "Bu bağlantı bir döngü oluşturur.", + "The engine did not add the image.": "Motor görüntüyü eklemedi.", + "The image could not be stored ({status})": "Görüntü saklanamadı ({status})", + "The material was removed, so the node editor closed.": "Malzeme kaldırıldığı için düğüm düzenleyicisi kapandı.", + "The node editor could not open: {reason}": "Düğüm düzenleyicisi açılamadı: {reason}", + "Transmission color": "Geçirgenlik rengi", + "Transmission weight": "Geçirgenlik ağırlığı", + "Triangle": "Üçgen", + "Trilinear": "Trilinear", + "Type": "Tür", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Geri alma ve yineleme uygulama tuşlarını kullanır: Mod+Z ve Shift+Mod+Z.", + "UV": "UV", + "Value": "Değer", + "Vector": "Vektör", + "vector": "vektör", + "Veins": "Damarlar", + "Voronoi": "Voronoi", + "Wave": "Dalga", + "Wrap": "Sarma", + "Zoom in": "Yakınlaştır", + "Zoom out": "Uzaklaştır", + "Zoom to 100%": "%100'e yakınlaştır", + "{kind} node {id}": "{kind} düğümü {id}", + "{nodes} nodes, {links} links": "{nodes} düğüm, {links} bağlantı", + "{socket} input, linked from {from}": "{socket} girdisi, {from} kaynağından bağlı", + "{socket} input, {type}": "{socket} girdisi, {type}", + "{socket} output, {type}": "{socket} çıktısı, {type}" +} diff --git a/frontend/src/i18n/modules/graph/uk.json b/frontend/src/i18n/modules/graph/uk.json new file mode 100644 index 00000000..947b7004 --- /dev/null +++ b/frontend/src/i18n/modules/graph/uk.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Граф може містити не більше {n} вузлів.", + "A node cannot feed itself.": "Вузол не може живити сам себе.", + "A {from} output cannot feed a {to} input.": "Вихід {from} не може живити вхід {to}.", + "ACEScg": "ACEScg", + "Add": "Додавання", + "Add a node": "Додати вузол", + "Add a node at the pointer": "Додати вузол біля курсора", + "Add an image to a node": "Додати зображення до вузла", + "Add image": "Додати зображення", + "Add image...": "Додати зображення...", + "Adding images needs the desktop app or a service that stores uploads.": "Для додавання зображень потрібен настільний застосунок або служба, що зберігає завантаження.", + "Alpha": "Альфа", + "B": "B", + "Bands": "Смуги", + "Base color": "Базовий колір", + "Base diffuse roughness": "Базова дифузна шорсткість", + "Base metalness": "Базова металевість", + "Base weight": "Базова вага", + "Bilinear": "Білінійна", + "Box": "Куб", + "Brushed": "Шліфований", + "Bump": "Бамп", + "C": "C", + "Cell edge": "Край комірки", + "Change a node setting": "Змінити налаштування вузла", + "Change a node value": "Змінити значення вузла", + "Chebyshev": "Чебишова", + "Checker": "Шахівниця", + "Clamp": "Обмеження", + "Click to add a stop": "Клацніть, щоб додати опорну точку", + "Close the node editor": "Закрити редактор вузлів", + "Coat color": "Колір покриття", + "Coat ior": "IOR покриття", + "Coat roughness": "Шорсткість покриття", + "Coat weight": "Вага покриття", + "colour": "колір", + "Colour 1": "Колір 1", + "Colour 2": "Колір 2", + "Colour and maths": "Колір і математика", + "Colour ramp": "Колірна шкала", + "Colour space": "Колірний простір", + "Connect": "З'єднати", + "Connect an input to an output.": "З'єднайте вхід із виходом.", + "Connect an output to an input.": "З'єднайте вихід із входом.", + "Connect or disconnect": "З'єднати або роз'єднати", + "Connect or disconnect the focused node": "З'єднати або роз'єднати вузол у фокусі", + "Constant": "Константа", + "Copied {n} nodes.": "Скопійовано вузлів: {n}.", + "Copy the selected nodes": "Копіювати вибрані вузли", + "Cut the selected nodes": "Вирізати вибрані вузли", + "Cylindrical": "Циліндрична", + "Data": "Дані", + "Delete stop": "Видалити опорну точку", + "Delete the selected nodes": "Видалити вибрані вузли", + "Density": "Щільність", + "Detail": "Деталізація", + "Disconnect": "Роз'єднати", + "Displacement": "Зміщення", + "Distance": "Відстань", + "Distortion": "Спотворення", + "Divide": "Ділення", + "Duplicate the selected nodes": "Дублювати вибрані вузли", + "Edit the focused node; Escape returns": "Редагувати вузол у фокусі; Escape повертає назад", + "Emission color": "Колір випромінювання", + "Euclidean": "Евклідова", + "Factor": "Коефіцієнт", + "Fallback": "Запасне значення", + "Feature": "Особливість", + "Filter": "Фільтр", + "Flakes": "Блискітки", + "Flip green": "Інвертувати зелений", + "Fractal noise": "Фрактальний шум", + "Frame all nodes": "Показати всі вузли", + "Fuzz color": "Колір ворсу", + "Fuzz roughness": "Шорсткість ворсу", + "Fuzz weight": "Вага ворсу", + "Gain": "Підсилення", + "Geometry opacity": "Непрозорість геометрії", + "Go back to the last graph the engine accepted": "Повернутися до останнього графа, прийнятого рушієм", + "Gradient": "Градієнт", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Утримуйте й перетягуйте для зсуву; зсув також працює середньою кнопкою та прокручуванням двома пальцями", + "Image texture": "Текстура зображення", + "Images": "Зображення", + "Inputs": "Входи", + "Interpolation": "Інтерполяція", + "Invert": "Інверсія", + "Lacunarity": "Лакунарність", + "Length": "Довжина", + "Lerp": "Лерп", + "Linear": "Лінійна", + "Manhattan": "Манхеттенська", + "Mapping": "Проєктування", + "Marble": "Мармур", + "Mask": "Маска", + "Material output": "Вихід матеріалу", + "Math": "Математика", + "Maximum": "Максимум", + "Metric": "Метрика", + "Minimum": "Мінімум", + "Mirror": "Дзеркало", + "Mix": "Змішування", + "Move focus to the nearest node": "Перевести фокус на найближчий вузол", + "Move the selected nodes": "Перемістити вибрані вузли", + "Multiply": "Множення", + "Nearest": "Найближчий", + "Nearest point": "Найближча точка", + "Node canvas": "Полотно вузлів", + "Node editor": "Редактор вузлів", + "Node editor keys": "Клавіші редактора вузлів", + "Node editor: {name}": "Редактор вузлів: {name}", + "Noise": "Шум", + "normal": "нормаль", + "Normal map": "Карта нормалей", + "Not applied: {reason}. The material keeps its last working graph.": "Не застосовано: {reason}. Матеріал зберігає останній робочий граф.", + "Nothing matches": "Нічого не знайдено", + "Number": "Число", + "number": "число", + "Octaves": "Октави", + "Offset X": "Зміщення за X", + "Offset Y": "Зміщення за Y", + "Operation": "Операція", + "Paste nodes, also into another material": "Вставити вузли, зокрема в інший матеріал", + "Patterns": "Візерунки", + "Phase": "Фаза", + "Planar": "Пласка", + "Position": "Положення", + "Power": "Степінь", + "Profile": "Профіль", + "Projection": "Проєкція", + "Quadratic": "Квадратична", + "Radial": "Радіальна", + "Randomness": "Випадковість", + "Repeat": "Повтор", + "Result": "Результат", + "Revert": "Повернути", + "Rings": "Кільця", + "Saw": "Пилка", + "Scale X": "Масштаб за X", + "Scale Y": "Масштаб за Y", + "Second nearest": "Друга найближча", + "Seed": "Початкове значення", + "Select every node": "Виділити всі вузли", + "Shape": "Форма", + "Show these keys": "Показати ці клавіші", + "Sine": "Синус", + "Space bar": "Пробіл", + "Specular color": "Колір відблисків", + "Specular ior": "IOR відблисків", + "Specular roughness": "Шорсткість відблисків", + "Specular roughness anisotropy": "Анізотропія шорсткості відблисків", + "Specular weight": "Вага відблисків", + "Spherical": "Сферична", + "Spread": "Розкид", + "sRGB": "sRGB", + "Stop colour": "Колір опорної точки", + "Stop position": "Положення опорної точки", + "Stop {n} at {pos}": "Опорна точка {n} у позиції {pos}", + "Stops": "Опорні точки", + "Strength": "Сила", + "Subtract": "Віднімання", + "Surface": "Поверхня", + "That link would make a loop.": "Цей зв'язок створить цикл.", + "The engine did not add the image.": "Рушій не додав зображення.", + "The image could not be stored ({status})": "Не вдалося зберегти зображення ({status})", + "The material was removed, so the node editor closed.": "Матеріал видалено, тому редактор вузлів закрито.", + "The node editor could not open: {reason}": "Не вдалося відкрити редактор вузлів: {reason}", + "Transmission color": "Колір пропускання", + "Transmission weight": "Вага пропускання", + "Triangle": "Трикутна", + "Trilinear": "Трилінійна", + "Type": "Тип", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Скасування й повторення використовують клавіші застосунку, Mod+Z і Shift+Mod+Z.", + "UV": "UV", + "Value": "Значення", + "Vector": "Вектор", + "vector": "вектор", + "Veins": "Прожилки", + "Voronoi": "Вороного", + "Wave": "Хвиля", + "Wrap": "Обгортання", + "Zoom in": "Збільшити", + "Zoom out": "Зменшити", + "Zoom to 100%": "Масштаб 100%", + "{kind} node {id}": "Вузол {kind} {id}", + "{nodes} nodes, {links} links": "Вузлів: {nodes}, зв'язків: {links}", + "{socket} input, linked from {from}": "Вхід {socket}, пов'язаний із {from}", + "{socket} input, {type}": "Вхід {socket}, {type}", + "{socket} output, {type}": "Вихід {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/vi.json b/frontend/src/i18n/modules/graph/vi.json new file mode 100644 index 00000000..58fcded2 --- /dev/null +++ b/frontend/src/i18n/modules/graph/vi.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "Một đồ thị có tối đa {n} nút.", + "A node cannot feed itself.": "Một nút không thể tự cấp dữ liệu cho chính nó.", + "A {from} output cannot feed a {to} input.": "Đầu ra {from} không thể cấp cho đầu vào {to}.", + "ACEScg": "ACEScg", + "Add": "Cộng", + "Add a node": "Thêm nút", + "Add a node at the pointer": "Thêm nút tại con trỏ", + "Add an image to a node": "Thêm ảnh vào nút", + "Add image": "Thêm ảnh", + "Add image...": "Thêm ảnh...", + "Adding images needs the desktop app or a service that stores uploads.": "Thêm ảnh cần ứng dụng máy tính hoặc dịch vụ có lưu trữ tệp tải lên.", + "Alpha": "Alpha", + "B": "B", + "Bands": "Dải", + "Base color": "Màu nền", + "Base diffuse roughness": "Độ nhám khuếch tán nền", + "Base metalness": "Độ kim loại nền", + "Base weight": "Trọng số nền", + "Bilinear": "Song tuyến tính", + "Box": "Hộp", + "Brushed": "Xước", + "Bump": "Bump", + "C": "C", + "Cell edge": "Cạnh ô", + "Change a node setting": "Đổi thiết lập nút", + "Change a node value": "Đổi giá trị nút", + "Chebyshev": "Chebyshev", + "Checker": "Ô bàn cờ", + "Clamp": "Kẹp", + "Click to add a stop": "Nhấp để thêm điểm dừng", + "Close the node editor": "Đóng trình sửa nút", + "Coat color": "Màu lớp phủ", + "Coat ior": "IOR lớp phủ", + "Coat roughness": "Độ nhám lớp phủ", + "Coat weight": "Trọng số lớp phủ", + "colour": "màu", + "Colour 1": "Màu 1", + "Colour 2": "Màu 2", + "Colour and maths": "Màu và toán học", + "Colour ramp": "Dải màu", + "Colour space": "Không gian màu", + "Connect": "Kết nối", + "Connect an input to an output.": "Nối một đầu vào với một đầu ra.", + "Connect an output to an input.": "Nối một đầu ra với một đầu vào.", + "Connect or disconnect": "Kết nối hoặc ngắt kết nối", + "Connect or disconnect the focused node": "Kết nối hoặc ngắt kết nối nút đang chọn tiêu điểm", + "Constant": "Hằng số", + "Copied {n} nodes.": "Đã sao chép {n} nút.", + "Copy the selected nodes": "Sao chép các nút đã chọn", + "Cut the selected nodes": "Cắt các nút đã chọn", + "Cylindrical": "Hình trụ", + "Data": "Dữ liệu", + "Delete stop": "Xóa điểm dừng", + "Delete the selected nodes": "Xóa các nút đã chọn", + "Density": "Mật độ", + "Detail": "Chi tiết", + "Disconnect": "Ngắt kết nối", + "Displacement": "Dịch chuyển", + "Distance": "Khoảng cách", + "Distortion": "Biến dạng", + "Divide": "Chia", + "Duplicate the selected nodes": "Nhân bản các nút đã chọn", + "Edit the focused node; Escape returns": "Sửa nút đang chọn tiêu điểm; Escape để quay lại", + "Emission color": "Màu phát sáng", + "Euclidean": "Euclid", + "Factor": "Hệ số", + "Fallback": "Dự phòng", + "Feature": "Đặc trưng", + "Filter": "Bộ lọc", + "Flakes": "Vảy", + "Flip green": "Lật kênh xanh lá", + "Fractal noise": "Nhiễu fractal", + "Frame all nodes": "Căn khung mọi nút", + "Fuzz color": "Màu lông mịn", + "Fuzz roughness": "Độ nhám lông mịn", + "Fuzz weight": "Trọng số lông mịn", + "Gain": "Độ lợi", + "Geometry opacity": "Độ đục hình học", + "Go back to the last graph the engine accepted": "Quay lại đồ thị gần nhất mà công cụ đã chấp nhận", + "Gradient": "Chuyển sắc", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "Giữ và kéo để di chuyển; kéo chuột giữa và cuộn hai ngón cũng di chuyển được", + "Image texture": "Kết cấu ảnh", + "Images": "Ảnh", + "Inputs": "Đầu vào", + "Interpolation": "Nội suy", + "Invert": "Đảo ngược", + "Lacunarity": "Lacunarity", + "Length": "Độ dài", + "Lerp": "Lerp", + "Linear": "Tuyến tính", + "Manhattan": "Manhattan", + "Mapping": "Ánh xạ", + "Marble": "Đá cẩm thạch", + "Mask": "Mặt nạ", + "Material output": "Đầu ra vật liệu", + "Math": "Toán học", + "Maximum": "Lớn nhất", + "Metric": "Thước đo", + "Minimum": "Nhỏ nhất", + "Mirror": "Gương", + "Mix": "Trộn", + "Move focus to the nearest node": "Chuyển tiêu điểm tới nút gần nhất", + "Move the selected nodes": "Di chuyển các nút đã chọn", + "Multiply": "Nhân", + "Nearest": "Gần nhất", + "Nearest point": "Điểm gần nhất", + "Node canvas": "Vùng vẽ nút", + "Node editor": "Trình sửa nút", + "Node editor keys": "Phím của trình sửa nút", + "Node editor: {name}": "Trình sửa nút: {name}", + "Noise": "Nhiễu", + "normal": "pháp tuyến", + "Normal map": "Map pháp tuyến", + "Not applied: {reason}. The material keeps its last working graph.": "Chưa áp dụng: {reason}. Vật liệu giữ đồ thị chạy được gần nhất.", + "Nothing matches": "Không có kết quả khớp", + "Number": "Số", + "number": "số", + "Octaves": "Octave", + "Offset X": "Độ lệch X", + "Offset Y": "Độ lệch Y", + "Operation": "Phép toán", + "Paste nodes, also into another material": "Dán các nút, kể cả vào vật liệu khác", + "Patterns": "Họa tiết", + "Phase": "Pha", + "Planar": "Phẳng", + "Position": "Vị trí", + "Power": "Lũy thừa", + "Profile": "Đường cong", + "Projection": "Phép chiếu", + "Quadratic": "Bậc hai", + "Radial": "Xuyên tâm", + "Randomness": "Độ ngẫu nhiên", + "Repeat": "Lặp lại", + "Result": "Kết quả", + "Revert": "Hoàn nguyên", + "Rings": "Vòng", + "Saw": "Răng cưa", + "Scale X": "Tỷ lệ X", + "Scale Y": "Tỷ lệ Y", + "Second nearest": "Gần thứ hai", + "Seed": "Hạt giống", + "Select every node": "Chọn mọi nút", + "Shape": "Hình dạng", + "Show these keys": "Hiện các phím này", + "Sine": "Sin", + "Space bar": "Phím cách", + "Specular color": "Màu phản chiếu", + "Specular ior": "IOR phản chiếu", + "Specular roughness": "Độ nhám phản chiếu", + "Specular roughness anisotropy": "Dị hướng độ nhám phản chiếu", + "Specular weight": "Trọng số phản chiếu", + "Spherical": "Hình cầu", + "Spread": "Độ lan", + "sRGB": "sRGB", + "Stop colour": "Màu điểm dừng", + "Stop position": "Vị trí điểm dừng", + "Stop {n} at {pos}": "Điểm dừng {n} tại {pos}", + "Stops": "Điểm dừng", + "Strength": "Cường độ", + "Subtract": "Trừ", + "Surface": "Bề mặt", + "That link would make a loop.": "Liên kết đó sẽ tạo thành vòng lặp.", + "The engine did not add the image.": "Công cụ không thêm ảnh.", + "The image could not be stored ({status})": "Không thể lưu ảnh ({status})", + "The material was removed, so the node editor closed.": "Vật liệu đã bị xóa nên trình sửa nút đã đóng.", + "The node editor could not open: {reason}": "Không thể mở trình sửa nút: {reason}", + "Transmission color": "Màu truyền sáng", + "Transmission weight": "Trọng số truyền sáng", + "Triangle": "Tam giác", + "Trilinear": "Ba tuyến tính", + "Type": "Loại", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "Hoàn tác và làm lại dùng phím của ứng dụng, Mod+Z và Shift+Mod+Z.", + "UV": "UV", + "Value": "Giá trị", + "Vector": "Vectơ", + "vector": "vectơ", + "Veins": "Vân", + "Voronoi": "Voronoi", + "Wave": "Sóng", + "Wrap": "Bọc", + "Zoom in": "Phóng to", + "Zoom out": "Thu nhỏ", + "Zoom to 100%": "Phóng về 100%", + "{kind} node {id}": "Nút {kind} {id}", + "{nodes} nodes, {links} links": "{nodes} nút, {links} liên kết", + "{socket} input, linked from {from}": "Đầu vào {socket}, liên kết từ {from}", + "{socket} input, {type}": "Đầu vào {socket}, {type}", + "{socket} output, {type}": "Đầu ra {socket}, {type}" +} diff --git a/frontend/src/i18n/modules/graph/zh-CN.json b/frontend/src/i18n/modules/graph/zh-CN.json new file mode 100644 index 00000000..0b00e32c --- /dev/null +++ b/frontend/src/i18n/modules/graph/zh-CN.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "一张图最多包含 {n} 个节点。", + "A node cannot feed itself.": "节点不能连接到自身。", + "A {from} output cannot feed a {to} input.": "{from} 输出不能连接到 {to} 输入。", + "ACEScg": "ACEScg", + "Add": "相加", + "Add a node": "添加节点", + "Add a node at the pointer": "在指针处添加节点", + "Add an image to a node": "向节点添加图像", + "Add image": "添加图像", + "Add image...": "添加图像...", + "Adding images needs the desktop app or a service that stores uploads.": "添加图像需要桌面应用,或能保存上传文件的服务。", + "Alpha": "Alpha", + "B": "B", + "Bands": "条带", + "Base color": "基础色", + "Base diffuse roughness": "基础漫反射粗糙度", + "Base metalness": "基础金属度", + "Base weight": "基础权重", + "Bilinear": "双线性", + "Box": "立方体", + "Brushed": "拉丝", + "Bump": "凹凸", + "C": "C", + "Cell edge": "单元边缘", + "Change a node setting": "更改节点设置", + "Change a node value": "更改节点值", + "Chebyshev": "切比雪夫", + "Checker": "棋盘格", + "Clamp": "钳制", + "Click to add a stop": "点击以添加色标", + "Close the node editor": "关闭节点编辑器", + "Coat color": "清漆颜色", + "Coat ior": "清漆 IOR", + "Coat roughness": "清漆粗糙度", + "Coat weight": "清漆权重", + "colour": "颜色", + "Colour 1": "颜色 1", + "Colour 2": "颜色 2", + "Colour and maths": "颜色与数学", + "Colour ramp": "颜色渐变", + "Colour space": "色彩空间", + "Connect": "连接", + "Connect an input to an output.": "将输入连接到输出。", + "Connect an output to an input.": "将输出连接到输入。", + "Connect or disconnect": "连接或断开", + "Connect or disconnect the focused node": "连接或断开当前聚焦的节点", + "Constant": "常量", + "Copied {n} nodes.": "已复制 {n} 个节点。", + "Copy the selected nodes": "复制所选节点", + "Cut the selected nodes": "剪切所选节点", + "Cylindrical": "圆柱", + "Data": "数据", + "Delete stop": "删除色标", + "Delete the selected nodes": "删除所选节点", + "Density": "密度", + "Detail": "细节", + "Disconnect": "断开", + "Displacement": "置换", + "Distance": "距离", + "Distortion": "扭曲", + "Divide": "相除", + "Duplicate the selected nodes": "复制所选节点", + "Edit the focused node; Escape returns": "编辑当前聚焦的节点;按 Escape 返回", + "Emission color": "自发光颜色", + "Euclidean": "欧几里得", + "Factor": "系数", + "Fallback": "备用值", + "Feature": "特征", + "Filter": "过滤", + "Flakes": "薄片", + "Flip green": "翻转绿色", + "Fractal noise": "分形噪波", + "Frame all nodes": "框选所有节点", + "Fuzz color": "绒毛颜色", + "Fuzz roughness": "绒毛粗糙度", + "Fuzz weight": "绒毛权重", + "Gain": "增益", + "Geometry opacity": "几何不透明度", + "Go back to the last graph the engine accepted": "返回引擎接受的上一张图", + "Gradient": "渐变", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "按住并拖动可平移;鼠标中键拖动和双指滚动同样可以平移", + "Image texture": "图像纹理", + "Images": "图像", + "Inputs": "输入", + "Interpolation": "插值", + "Invert": "反转", + "Lacunarity": "间隙度", + "Length": "长度", + "Lerp": "线性插值", + "Linear": "线性", + "Manhattan": "曼哈顿", + "Mapping": "映射", + "Marble": "大理石", + "Mask": "遮罩", + "Material output": "材质输出", + "Math": "数学", + "Maximum": "最大值", + "Metric": "度量", + "Minimum": "最小值", + "Mirror": "镜像", + "Mix": "混合", + "Move focus to the nearest node": "将焦点移到最近的节点", + "Move the selected nodes": "移动所选节点", + "Multiply": "相乘", + "Nearest": "最近邻", + "Nearest point": "最近点", + "Node canvas": "节点画布", + "Node editor": "节点编辑器", + "Node editor keys": "节点编辑器快捷键", + "Node editor: {name}": "节点编辑器:{name}", + "Noise": "噪波", + "normal": "法线", + "Normal map": "法线贴图", + "Not applied: {reason}. The material keeps its last working graph.": "未应用:{reason}。材质保留其上一张可用的图。", + "Nothing matches": "没有匹配项", + "Number": "数字", + "number": "数字", + "Octaves": "倍频", + "Offset X": "X 偏移", + "Offset Y": "Y 偏移", + "Operation": "运算", + "Paste nodes, also into another material": "粘贴节点,也可粘贴到其他材质中", + "Patterns": "图案", + "Phase": "相位", + "Planar": "平面", + "Position": "位置", + "Power": "幂", + "Profile": "轮廓", + "Projection": "投影", + "Quadratic": "二次", + "Radial": "径向", + "Randomness": "随机性", + "Repeat": "重复", + "Result": "结果", + "Revert": "还原", + "Rings": "环", + "Saw": "锯齿波", + "Scale X": "X 缩放", + "Scale Y": "Y 缩放", + "Second nearest": "第二近", + "Seed": "种子", + "Select every node": "选择所有节点", + "Shape": "形状", + "Show these keys": "显示这些快捷键", + "Sine": "正弦", + "Space bar": "空格键", + "Specular color": "镜面反射颜色", + "Specular ior": "镜面反射 IOR", + "Specular roughness": "镜面反射粗糙度", + "Specular roughness anisotropy": "镜面反射粗糙度各向异性", + "Specular weight": "镜面反射权重", + "Spherical": "球形", + "Spread": "扩散", + "sRGB": "sRGB", + "Stop colour": "色标颜色", + "Stop position": "色标位置", + "Stop {n} at {pos}": "第 {n} 个色标,位置 {pos}", + "Stops": "色标", + "Strength": "强度", + "Subtract": "相减", + "Surface": "表面", + "That link would make a loop.": "该连接会形成循环。", + "The engine did not add the image.": "引擎没有添加该图像。", + "The image could not be stored ({status})": "无法存储图像 ({status})", + "The material was removed, so the node editor closed.": "材质已被移除,因此节点编辑器已关闭。", + "The node editor could not open: {reason}": "无法打开节点编辑器:{reason}", + "Transmission color": "透射颜色", + "Transmission weight": "透射权重", + "Triangle": "三角波", + "Trilinear": "三线性", + "Type": "类型", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "撤销和重做使用应用快捷键 Mod+Z 和 Shift+Mod+Z。", + "UV": "UV", + "Value": "值", + "Vector": "矢量", + "vector": "矢量", + "Veins": "脉络", + "Voronoi": "沃罗诺伊", + "Wave": "波浪", + "Wrap": "环绕", + "Zoom in": "放大", + "Zoom out": "缩小", + "Zoom to 100%": "缩放到 100%", + "{kind} node {id}": "{kind} 节点 {id}", + "{nodes} nodes, {links} links": "{nodes} 个节点,{links} 条连接", + "{socket} input, linked from {from}": "{socket} 输入,连接自 {from}", + "{socket} input, {type}": "{socket} 输入,{type}", + "{socket} output, {type}": "{socket} 输出,{type}" +} diff --git a/frontend/src/i18n/modules/graph/zh-TW.json b/frontend/src/i18n/modules/graph/zh-TW.json new file mode 100644 index 00000000..c31ddd40 --- /dev/null +++ b/frontend/src/i18n/modules/graph/zh-TW.json @@ -0,0 +1,191 @@ +{ + "A": "A", + "A graph holds at most {n} nodes.": "一張圖最多包含 {n} 個節點。", + "A node cannot feed itself.": "節點不能連接到自身。", + "A {from} output cannot feed a {to} input.": "{from} 輸出不能連接到 {to} 輸入。", + "ACEScg": "ACEScg", + "Add": "相加", + "Add a node": "加入節點", + "Add a node at the pointer": "在指標處加入節點", + "Add an image to a node": "向節點加入影像", + "Add image": "加入影像", + "Add image...": "加入影像...", + "Adding images needs the desktop app or a service that stores uploads.": "加入影像需要桌面應用程式,或能儲存上傳檔案的服務。", + "Alpha": "Alpha", + "B": "B", + "Bands": "條帶", + "Base color": "基礎色", + "Base diffuse roughness": "基礎漫射粗糙度", + "Base metalness": "基礎金屬度", + "Base weight": "基礎權重", + "Bilinear": "雙線性", + "Box": "立方體", + "Brushed": "拉絲", + "Bump": "凹凸", + "C": "C", + "Cell edge": "單元邊緣", + "Change a node setting": "變更節點設定", + "Change a node value": "變更節點值", + "Chebyshev": "切比雪夫", + "Checker": "棋盤格", + "Clamp": "夾制", + "Click to add a stop": "按一下以加入色標", + "Close the node editor": "關閉節點編輯器", + "Coat color": "透明塗層顏色", + "Coat ior": "透明塗層 IOR", + "Coat roughness": "透明塗層粗糙度", + "Coat weight": "透明塗層權重", + "colour": "顏色", + "Colour 1": "顏色 1", + "Colour 2": "顏色 2", + "Colour and maths": "顏色與數學", + "Colour ramp": "顏色漸層", + "Colour space": "色彩空間", + "Connect": "連接", + "Connect an input to an output.": "將輸入連接到輸出。", + "Connect an output to an input.": "將輸出連接到輸入。", + "Connect or disconnect": "連接或中斷", + "Connect or disconnect the focused node": "連接或中斷目前聚焦的節點", + "Constant": "常數", + "Copied {n} nodes.": "已拷貝 {n} 個節點。", + "Copy the selected nodes": "拷貝所選節點", + "Cut the selected nodes": "剪下所選節點", + "Cylindrical": "圓柱", + "Data": "資料", + "Delete stop": "刪除色標", + "Delete the selected nodes": "刪除所選節點", + "Density": "密度", + "Detail": "細節", + "Disconnect": "中斷", + "Displacement": "置換", + "Distance": "距離", + "Distortion": "扭曲", + "Divide": "相除", + "Duplicate the selected nodes": "複製所選節點", + "Edit the focused node; Escape returns": "編輯目前聚焦的節點;按 Escape 返回", + "Emission color": "自發光顏色", + "Euclidean": "歐幾里得", + "Factor": "係數", + "Fallback": "備用值", + "Feature": "特徵", + "Filter": "篩選", + "Flakes": "薄片", + "Flip green": "翻轉綠色", + "Fractal noise": "碎形雜訊", + "Frame all nodes": "框選所有節點", + "Fuzz color": "絨毛顏色", + "Fuzz roughness": "絨毛粗糙度", + "Fuzz weight": "絨毛權重", + "Gain": "增益", + "Geometry opacity": "幾何不透明度", + "Go back to the last graph the engine accepted": "返回引擎接受的上一張圖", + "Gradient": "漸層", + "Hold and drag to pan; middle drag and two-finger scroll pan too": "按住並拖曳可平移;滑鼠中鍵拖曳和雙指捲動同樣可以平移", + "Image texture": "影像紋理", + "Images": "影像", + "Inputs": "輸入", + "Interpolation": "內插", + "Invert": "反轉", + "Lacunarity": "間隙度", + "Length": "長度", + "Lerp": "線性內插", + "Linear": "線性", + "Manhattan": "曼哈頓", + "Mapping": "對應", + "Marble": "大理石", + "Mask": "遮罩", + "Material output": "材質輸出", + "Math": "數學", + "Maximum": "最大值", + "Metric": "度量", + "Minimum": "最小值", + "Mirror": "鏡射", + "Mix": "混合", + "Move focus to the nearest node": "將焦點移到最近的節點", + "Move the selected nodes": "移動所選節點", + "Multiply": "相乘", + "Nearest": "最近鄰", + "Nearest point": "最近點", + "Node canvas": "節點畫布", + "Node editor": "節點編輯器", + "Node editor keys": "節點編輯器快速鍵", + "Node editor: {name}": "節點編輯器:{name}", + "Noise": "雜訊", + "normal": "法線", + "Normal map": "法線貼圖", + "Not applied: {reason}. The material keeps its last working graph.": "未套用:{reason}。材質保留其上一張可用的圖。", + "Nothing matches": "沒有相符項目", + "Number": "數字", + "number": "數字", + "Octaves": "倍頻", + "Offset X": "X 偏移", + "Offset Y": "Y 偏移", + "Operation": "運算", + "Paste nodes, also into another material": "貼上節點,也可貼到其他材質中", + "Patterns": "圖樣", + "Phase": "相位", + "Planar": "平面", + "Position": "位置", + "Power": "冪", + "Profile": "輪廓", + "Projection": "投影", + "Quadratic": "二次", + "Radial": "徑向", + "Randomness": "隨機性", + "Repeat": "重複", + "Result": "結果", + "Revert": "還原", + "Rings": "環", + "Saw": "鋸齒波", + "Scale X": "X 縮放", + "Scale Y": "Y 縮放", + "Second nearest": "第二近", + "Seed": "種子", + "Select every node": "選取所有節點", + "Shape": "形狀", + "Show these keys": "顯示這些快速鍵", + "Sine": "正弦", + "Space bar": "空白鍵", + "Specular color": "鏡面反射顏色", + "Specular ior": "鏡面反射 IOR", + "Specular roughness": "鏡面反射粗糙度", + "Specular roughness anisotropy": "鏡面反射粗糙度各向異性", + "Specular weight": "鏡面反射權重", + "Spherical": "球形", + "Spread": "擴散", + "sRGB": "sRGB", + "Stop colour": "色標顏色", + "Stop position": "色標位置", + "Stop {n} at {pos}": "第 {n} 個色標,位置 {pos}", + "Stops": "色標", + "Strength": "強度", + "Subtract": "相減", + "Surface": "表面", + "That link would make a loop.": "該連接會形成迴圈。", + "The engine did not add the image.": "引擎沒有加入該影像。", + "The image could not be stored ({status})": "無法儲存影像 ({status})", + "The material was removed, so the node editor closed.": "材質已被移除,因此節點編輯器已關閉。", + "The node editor could not open: {reason}": "無法開啟節點編輯器:{reason}", + "Transmission color": "透射顏色", + "Transmission weight": "透射權重", + "Triangle": "三角波", + "Trilinear": "三線性", + "Type": "類型", + "Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.": "復原和重做使用應用程式快速鍵 Mod+Z 和 Shift+Mod+Z。", + "UV": "UV", + "Value": "值", + "Vector": "向量", + "vector": "向量", + "Veins": "脈絡", + "Voronoi": "沃羅諾伊", + "Wave": "波浪", + "Wrap": "環繞", + "Zoom in": "放大", + "Zoom out": "縮小", + "Zoom to 100%": "縮放到 100%", + "{kind} node {id}": "{kind} 節點 {id}", + "{nodes} nodes, {links} links": "{nodes} 個節點,{links} 條連接", + "{socket} input, linked from {from}": "{socket} 輸入,連接自 {from}", + "{socket} input, {type}": "{socket} 輸入,{type}", + "{socket} output, {type}": "{socket} 輸出,{type}" +} diff --git a/frontend/src/i18n/modules/handoff/cs.json b/frontend/src/i18n/modules/handoff/cs.json new file mode 100644 index 00000000..f7d2384a --- /dev/null +++ b/frontend/src/i18n/modules/handoff/cs.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 z {count}", + "A Form app is handing something over": "Aplikace Form něco předává", + "A mesh with maps by role": "Síť s mapami podle role", + "A model file": "Soubor modelu", + "Add to this document": "Přidat do tohoto dokumentu", + "Added {title} from {app}": "Přidáno {title} z aplikace {app}", + "Always allow": "Vždy povolit", + "Always allow {app}": "Vždy povolit aplikaci {app}", + "An object from the GoF folder": "Objekt ze složky GoF", + "another app": "jiná aplikace", + "As a new document": "Jako nový dokument", + "Base colour": "Základní barva", + "Block": "Zablokovat", + "Choose a hand-off or give a path": "Vyberte předání nebo zadejte cestu", + "Contents": "Obsah", + "Could not be read": "Nepodařilo se přečíst", + "Decline": "Odmítnout", + "Emission": "Emise", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot sleduje složku GoF a exporty z FormSurface, dokud je toto okno otevřené. Když aplikace Form něco předá, FormShot se zde zeptá, než to otevře.", + "FormSurface": "FormSurface", + "FormSurface exports": "Exporty z FormSurface", + "From": "Od", + "GoF folder": "Složka GoF", + "Hand-off Settings": "Nastavení předání", + "Hand-offs": "Předání", + "Hand-offs from {app}": "Předání z aplikace {app}", + "Maps": "Mapy", + "Maps by role, without a mesh": "Mapy podle role, bez sítě", + "Metalness": "Kovovost", + "Normal": "Normálová", + "not found": "nenalezeno", + "Not read yet": "Zatím nepřečteno", + "Nothing from the Form apps is waiting in their hand-off folders.": "V předávacích složkách aplikací Form nic nečeká.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Nic se neotevře, dokud nevyberete. Textury zůstanou tam, kam je aplikace zapsala, a odkazuje se na ně podle role.", + "Occlusion, roughness and metalness": "Okluze, drsnost a kovovost", + "Opacity": "Neprůhlednost", + "Open a Hand-off": "Otevřít předání", + "Open a Hand-off...": "Otevřít předání...", + "Open it": "Otevřít", + "Open once": "Otevřít jednou", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Otevřít to, co předal FormSculpt, FormFabric, FormSurface nebo FormCAD", + "Opened {title} from {app} as a new document": "{title} z aplikace {app} bylo otevřeno jako nový dokument", + "Or a path to a file or folder": "Nebo cesta k souboru či složce", + "Other maps": "Další mapy", + "Reading...": "Čtení...", + "Roughness": "Drsnost", + "Sent as": "Odesláno jako", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Služba FormShot není dostupná, takže tyto volby nelze nyní přečíst ani změnit.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "To, co FormSculpt a FormFabric vložily do složky GoF a co exportoval FormSurface. Otevření odtud nevyžaduje potvrzení, protože jste to sami zvolili.", + "{app} is handing over {title}: {what}.": "{app} předává {title}: {what}.", + "{count} maps from FormSurface": "{count} map z FormSurface", + "{count} maps: {roles}": "{count} map: {roles}", + "{count} materials": "{count} materiálů", + "{format} file": "Soubor {format}", + "{format} file, {count} triangles": "Soubor {format}, {count} trojúhelníků", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} sítí, {triangles} trojúhelníků, {materials} materiálů", + "{n} days ago": "před {n} dny" +} diff --git a/frontend/src/i18n/modules/handoff/da.json b/frontend/src/i18n/modules/handoff/da.json new file mode 100644 index 00000000..78a2b0b0 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/da.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 af {count}", + "A Form app is handing something over": "En Form-app afleverer noget", + "A mesh with maps by role": "Et mesh med maps efter rolle", + "A model file": "En modelfil", + "Add to this document": "Føj til dette dokument", + "Added {title} from {app}": "Tilføjede {title} fra {app}", + "Always allow": "Tillad altid", + "Always allow {app}": "Tillad altid {app}", + "An object from the GoF folder": "Et objekt fra GoF-mappen", + "another app": "en anden app", + "As a new document": "Som et nyt dokument", + "Base colour": "Basisfarve", + "Block": "Blokér", + "Choose a hand-off or give a path": "Vælg en overdragelse, eller angiv en sti", + "Contents": "Indhold", + "Could not be read": "Kunne ikke læses", + "Decline": "Afvis", + "Emission": "Emission", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot overvåger GoF-mappen og FormSurfaces eksporter, så længe dette vindue er åbent. Når en Form-app afleverer noget, spørger FormShot her, før det åbnes.", + "FormSurface": "FormSurface", + "FormSurface exports": "Eksporter fra FormSurface", + "From": "Fra", + "GoF folder": "GoF-mappe", + "Hand-off Settings": "Indstillinger for overdragelse", + "Hand-offs": "Overdragelser", + "Hand-offs from {app}": "Overdragelser fra {app}", + "Maps": "Maps", + "Maps by role, without a mesh": "Maps efter rolle, uden mesh", + "Metalness": "Metalness", + "Normal": "Normal", + "not found": "ikke fundet", + "Not read yet": "Endnu ikke læst", + "Nothing from the Form apps is waiting in their hand-off folders.": "Der venter intet fra Form-apps i deres overdragelsesmapper.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Intet åbnes, før du vælger. Teksturer bliver, hvor appen skrev dem, og refereres efter rolle.", + "Occlusion, roughness and metalness": "Okklusion, ruhed og metalness", + "Opacity": "Opacitet", + "Open a Hand-off": "Åbn en overdragelse", + "Open a Hand-off...": "Åbn en overdragelse...", + "Open it": "Åbn den", + "Open once": "Åbn én gang", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Åbn det, som FormSculpt, FormFabric, FormSurface eller FormCAD har afleveret", + "Opened {title} from {app} as a new document": "Åbnede {title} fra {app} som et nyt dokument", + "Or a path to a file or folder": "Eller en sti til en fil eller mappe", + "Other maps": "Andre maps", + "Reading...": "Læser...", + "Roughness": "Ruhed", + "Sent as": "Sendt som", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot-tjenesten er ikke tilgængelig, så disse valg kan ikke læses eller ændres nu.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Det, som FormSculpt og FormFabric lagde i GoF-mappen, og det, som FormSurface eksporterede. Det kræver ingen forespørgsel at åbne noget her, fordi du selv har valgt det.", + "{app} is handing over {title}: {what}.": "{app} afleverer {title}: {what}.", + "{count} maps from FormSurface": "{count} maps fra FormSurface", + "{count} maps: {roles}": "{count} maps: {roles}", + "{count} materials": "{count} materialer", + "{format} file": "{format}-fil", + "{format} file, {count} triangles": "{format}-fil, {count} trekanter", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} meshes, {triangles} trekanter, {materials} materialer", + "{n} days ago": "for {n} dage siden" +} diff --git a/frontend/src/i18n/modules/handoff/de.json b/frontend/src/i18n/modules/handoff/de.json new file mode 100644 index 00000000..047e68d4 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/de.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 von {count}", + "A Form app is handing something over": "Eine Form-App übergibt etwas", + "A mesh with maps by role": "Ein Mesh mit Maps nach Rolle", + "A model file": "Eine Modelldatei", + "Add to this document": "Zu diesem Dokument hinzufügen", + "Added {title} from {app}": "{title} aus {app} hinzugefügt", + "Always allow": "Immer erlauben", + "Always allow {app}": "{app} immer erlauben", + "An object from the GoF folder": "Ein Objekt aus dem GoF-Ordner", + "another app": "eine andere App", + "As a new document": "Als neues Dokument", + "Base colour": "Basisfarbe", + "Block": "Blockieren", + "Choose a hand-off or give a path": "Wähle eine Übergabe oder gib einen Pfad an", + "Contents": "Inhalt", + "Could not be read": "Konnte nicht gelesen werden", + "Decline": "Ablehnen", + "Emission": "Emission", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot überwacht den GoF-Ordner und die Exporte von FormSurface, solange dieses Fenster geöffnet ist. Wenn eine Form-App etwas übergibt, fragt FormShot hier nach, bevor es geöffnet wird.", + "FormSurface": "FormSurface", + "FormSurface exports": "FormSurface-Exporte", + "From": "Von", + "GoF folder": "GoF-Ordner", + "Hand-off Settings": "Einstellungen für Übergaben", + "Hand-offs": "Übergaben", + "Hand-offs from {app}": "Übergaben von {app}", + "Maps": "Maps", + "Maps by role, without a mesh": "Maps nach Rolle, ohne Mesh", + "Metalness": "Metallizität", + "Normal": "Normale", + "not found": "nicht gefunden", + "Not read yet": "Noch nicht gelesen", + "Nothing from the Form apps is waiting in their hand-off folders.": "In den Übergabeordnern der Form-Apps wartet nichts.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Nichts wird geöffnet, bevor du es auswählst. Texturen bleiben dort, wo die App sie geschrieben hat, und werden nach Rolle referenziert.", + "Occlusion, roughness and metalness": "Okklusion, Rauheit und Metallizität", + "Opacity": "Deckkraft", + "Open a Hand-off": "Übergabe öffnen", + "Open a Hand-off...": "Übergabe öffnen ...", + "Open it": "Öffnen", + "Open once": "Einmal öffnen", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Öffnen, was FormSculpt, FormFabric, FormSurface oder FormCAD übergeben haben", + "Opened {title} from {app} as a new document": "{title} aus {app} als neues Dokument geöffnet", + "Or a path to a file or folder": "Oder ein Pfad zu einer Datei oder einem Ordner", + "Other maps": "Weitere Maps", + "Reading...": "Wird gelesen ...", + "Roughness": "Rauheit", + "Sent as": "Gesendet als", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Der FormShot-Dienst ist nicht erreichbar, daher lassen sich diese Optionen jetzt weder lesen noch ändern.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Was FormSculpt und FormFabric im GoF-Ordner abgelegt haben und was FormSurface exportiert hat. Das Öffnen von hier braucht keine Rückfrage, weil du es ausgewählt hast.", + "{app} is handing over {title}: {what}.": "{app} übergibt {title}: {what}.", + "{count} maps from FormSurface": "{count} Maps von FormSurface", + "{count} maps: {roles}": "{count} Maps: {roles}", + "{count} materials": "{count} Materialien", + "{format} file": "{format}-Datei", + "{format} file, {count} triangles": "{format}-Datei, {count} Dreiecke", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} Meshes, {triangles} Dreiecke, {materials} Materialien", + "{n} days ago": "vor {n} Tagen" +} diff --git a/frontend/src/i18n/modules/handoff/es-MX.json b/frontend/src/i18n/modules/handoff/es-MX.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/es-MX.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/handoff/es.json b/frontend/src/i18n/modules/handoff/es.json new file mode 100644 index 00000000..b1f916db --- /dev/null +++ b/frontend/src/i18n/modules/handoff/es.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 de {count}", + "A Form app is handing something over": "Una app de Form está traspasando algo", + "A mesh with maps by role": "Una malla con mapas por función", + "A model file": "Un archivo de modelo", + "Add to this document": "Añadir a este documento", + "Added {title} from {app}": "Se añadió {title} desde {app}", + "Always allow": "Permitir siempre", + "Always allow {app}": "Permitir siempre {app}", + "An object from the GoF folder": "Un objeto de la carpeta GoF", + "another app": "otra app", + "As a new document": "Como documento nuevo", + "Base colour": "Color base", + "Block": "Bloquear", + "Choose a hand-off or give a path": "Elige un traspaso o indica una ruta", + "Contents": "Contenido", + "Could not be read": "No se pudo leer", + "Decline": "Rechazar", + "Emission": "Emisión", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot vigila la carpeta GoF y las exportaciones de FormSurface mientras esta ventana está abierta. Cuando una app de Form traspasa algo, FormShot pregunta aquí antes de abrirlo.", + "FormSurface": "FormSurface", + "FormSurface exports": "Exportaciones de FormSurface", + "From": "De", + "GoF folder": "Carpeta GoF", + "Hand-off Settings": "Ajustes de traspasos", + "Hand-offs": "Traspasos", + "Hand-offs from {app}": "Traspasos desde {app}", + "Maps": "Mapas", + "Maps by role, without a mesh": "Mapas por función, sin malla", + "Metalness": "Metalicidad", + "Normal": "Normal", + "not found": "no encontrado", + "Not read yet": "Aún sin leer", + "Nothing from the Form apps is waiting in their hand-off folders.": "No hay nada de las apps de Form esperando en sus carpetas de traspaso.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "No se abre nada hasta que lo elijas. Las texturas se quedan donde la app las escribió y se referencian por función.", + "Occlusion, roughness and metalness": "Oclusión, rugosidad y metalicidad", + "Opacity": "Opacidad", + "Open a Hand-off": "Abrir un traspaso", + "Open a Hand-off...": "Abrir un traspaso...", + "Open it": "Abrir", + "Open once": "Abrir una vez", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Abrir lo que FormSculpt, FormFabric, FormSurface o FormCAD han traspasado", + "Opened {title} from {app} as a new document": "Se abrió {title} desde {app} como documento nuevo", + "Or a path to a file or folder": "O una ruta a un archivo o a una carpeta", + "Other maps": "Otros mapas", + "Reading...": "Leyendo...", + "Roughness": "Rugosidad", + "Sent as": "Enviado como", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "El servicio de FormShot no está disponible, así que ahora no se pueden leer ni cambiar estas opciones.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Lo que FormSculpt y FormFabric han puesto en la carpeta GoF y lo que FormSurface ha exportado. Abrirlo desde aquí no pide confirmación, porque lo has elegido tú.", + "{app} is handing over {title}: {what}.": "{app} está traspasando {title}: {what}.", + "{count} maps from FormSurface": "{count} mapas de FormSurface", + "{count} maps: {roles}": "{count} mapas: {roles}", + "{count} materials": "{count} materiales", + "{format} file": "Archivo {format}", + "{format} file, {count} triangles": "Archivo {format}, {count} triángulos", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} mallas, {triangles} triángulos, {materials} materiales", + "{n} days ago": "hace {n} días" +} diff --git a/frontend/src/i18n/modules/handoff/fi.json b/frontend/src/i18n/modules/handoff/fi.json new file mode 100644 index 00000000..2d5bda16 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/fi.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 / {count}", + "A Form app is handing something over": "Form-sovellus luovuttaa jotakin", + "A mesh with maps by role": "Verkko, jonka kartat on annettu roolin mukaan", + "A model file": "Mallitiedosto", + "Add to this document": "Lisää tähän dokumenttiin", + "Added {title} from {app}": "{title} lisätty sovelluksesta {app}", + "Always allow": "Salli aina", + "Always allow {app}": "Salli {app} aina", + "An object from the GoF folder": "Objekti GoF-kansiosta", + "another app": "toinen sovellus", + "As a new document": "Uutena dokumenttina", + "Base colour": "Perusväri", + "Block": "Estä", + "Choose a hand-off or give a path": "Valitse siirto tai anna polku", + "Contents": "Sisältö", + "Could not be read": "Lukeminen ei onnistunut", + "Decline": "Hylkää", + "Emission": "Emissio", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot seuraa GoF-kansiota ja FormSurfacen vientejä, kun tämä ikkuna on auki. Kun Form-sovellus luovuttaa jotakin, FormShot kysyy täällä ennen sen avaamista.", + "FormSurface": "FormSurface", + "FormSurface exports": "FormSurfacen viennit", + "From": "Lähde", + "GoF folder": "GoF-kansio", + "Hand-off Settings": "Siirtojen asetukset", + "Hand-offs": "Siirrot", + "Hand-offs from {app}": "Siirrot sovelluksesta {app}", + "Maps": "Kartat", + "Maps by role, without a mesh": "Kartat rooleittain, ilman verkkoa", + "Metalness": "Metallisuus", + "Normal": "Normaali", + "not found": "ei löytynyt", + "Not read yet": "Ei vielä luettu", + "Nothing from the Form apps is waiting in their hand-off folders.": "Form-sovellusten siirtokansioissa ei odota mitään.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Mitään ei avata ennen kuin valitset. Tekstuurit pysyvät siellä, minne sovellus ne kirjoitti, ja niihin viitataan roolin mukaan.", + "Occlusion, roughness and metalness": "Okkluusio, karheus ja metallisuus", + "Opacity": "Peittävyys", + "Open a Hand-off": "Avaa siirto", + "Open a Hand-off...": "Avaa siirto...", + "Open it": "Avaa se", + "Open once": "Avaa kerran", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Avaa se, minkä FormSculpt, FormFabric, FormSurface tai FormCAD luovutti", + "Opened {title} from {app} as a new document": "{title} avattu sovelluksesta {app} uutena dokumenttina", + "Or a path to a file or folder": "Tai polku tiedostoon tai kansioon", + "Other maps": "Muut kartat", + "Reading...": "Luetaan...", + "Roughness": "Karheus", + "Sent as": "Lähetetty muodossa", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot-palvelu ei ole tavoitettavissa, joten näitä valintoja ei voi nyt lukea eikä muuttaa.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Se, mitä FormSculpt ja FormFabric ovat laittaneet GoF-kansioon ja mitä FormSurface on viennyt. Täällä avaaminen ei vaadi kehotetta, koska olet itse valinnut sen.", + "{app} is handing over {title}: {what}.": "{app} luovuttaa kohteen {title}: {what}.", + "{count} maps from FormSurface": "{count} karttaa FormSurfacesta", + "{count} maps: {roles}": "{count} karttaa: {roles}", + "{count} materials": "{count} materiaalia", + "{format} file": "{format}-tiedosto", + "{format} file, {count} triangles": "{format}-tiedosto, {count} kolmiota", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} verkkoa, {triangles} kolmiota, {materials} materiaalia", + "{n} days ago": "{n} päivää sitten" +} diff --git a/frontend/src/i18n/modules/handoff/fr-CA.json b/frontend/src/i18n/modules/handoff/fr-CA.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/fr-CA.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/handoff/fr.json b/frontend/src/i18n/modules/handoff/fr.json new file mode 100644 index 00000000..e1d28754 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/fr.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 sur {count}", + "A Form app is handing something over": "Une application Form transmet quelque chose", + "A mesh with maps by role": "Un maillage avec des maps par rôle", + "A model file": "Un fichier de modèle", + "Add to this document": "Ajouter à ce document", + "Added {title} from {app}": "{title} ajouté depuis {app}", + "Always allow": "Toujours autoriser", + "Always allow {app}": "Toujours autoriser {app}", + "An object from the GoF folder": "Un objet du dossier GoF", + "another app": "une autre application", + "As a new document": "Comme nouveau document", + "Base colour": "Couleur de base", + "Block": "Bloquer", + "Choose a hand-off or give a path": "Choisissez un transfert ou indiquez un chemin", + "Contents": "Contenu", + "Could not be read": "Lecture impossible", + "Decline": "Refuser", + "Emission": "Émission", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot surveille le dossier GoF et les exports de FormSurface tant que cette fenêtre est ouverte. Lorsqu'une application Form transmet quelque chose, FormShot demande ici avant de l'ouvrir.", + "FormSurface": "FormSurface", + "FormSurface exports": "Exports FormSurface", + "From": "De", + "GoF folder": "Dossier GoF", + "Hand-off Settings": "Réglages des transferts", + "Hand-offs": "Transferts", + "Hand-offs from {app}": "Transferts depuis {app}", + "Maps": "Maps", + "Maps by role, without a mesh": "Maps par rôle, sans maillage", + "Metalness": "Métallicité", + "Normal": "Normale", + "not found": "introuvable", + "Not read yet": "Pas encore lu", + "Nothing from the Form apps is waiting in their hand-off folders.": "Rien ne les attend dans les dossiers de transfert des applications Form.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Rien n'est ouvert tant que vous n'avez pas choisi. Les textures restent là où l'application les a écrites et sont référencées par rôle.", + "Occlusion, roughness and metalness": "Occlusion, rugosité et métallicité", + "Opacity": "Opacité", + "Open a Hand-off": "Ouvrir un transfert", + "Open a Hand-off...": "Ouvrir un transfert...", + "Open it": "Ouvrir", + "Open once": "Ouvrir une fois", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Ouvrir ce que FormSculpt, FormFabric, FormSurface ou FormCAD ont transmis", + "Opened {title} from {app} as a new document": "{title} ouvert depuis {app} comme nouveau document", + "Or a path to a file or folder": "Ou un chemin vers un fichier ou un dossier", + "Other maps": "Autres maps", + "Reading...": "Lecture...", + "Roughness": "Rugosité", + "Sent as": "Envoyé comme", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Le service FormShot est injoignable, ces choix ne peuvent donc être ni lus ni modifiés pour le moment.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Ce que FormSculpt et FormFabric ont déposé dans le dossier GoF et ce que FormSurface a exporté. L'ouverture depuis ici ne demande aucune confirmation, car c'est vous qui l'avez choisi.", + "{app} is handing over {title}: {what}.": "{app} transmet {title} : {what}.", + "{count} maps from FormSurface": "{count} maps de FormSurface", + "{count} maps: {roles}": "{count} maps : {roles}", + "{count} materials": "{count} matériaux", + "{format} file": "Fichier {format}", + "{format} file, {count} triangles": "Fichier {format}, {count} triangles", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} maillages, {triangles} triangles, {materials} matériaux", + "{n} days ago": "il y a {n} jours" +} diff --git a/frontend/src/i18n/modules/handoff/hu.json b/frontend/src/i18n/modules/handoff/hu.json new file mode 100644 index 00000000..d01cdda7 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/hu.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 / {count}", + "A Form app is handing something over": "Egy Form alkalmazás átad valamit", + "A mesh with maps by role": "Háló szerepük szerinti térképekkel", + "A model file": "Modellfájl", + "Add to this document": "Hozzáadás ehhez a dokumentumhoz", + "Added {title} from {app}": "{title} hozzáadva innen: {app}", + "Always allow": "Mindig engedélyez", + "Always allow {app}": "{app} mindig engedélyezése", + "An object from the GoF folder": "Objektum a GoF mappából", + "another app": "másik alkalmazás", + "As a new document": "Új dokumentumként", + "Base colour": "Alapszín", + "Block": "Tiltás", + "Choose a hand-off or give a path": "Válasszon átadást, vagy adjon meg útvonalat", + "Contents": "Tartalom", + "Could not be read": "Nem sikerült beolvasni", + "Decline": "Elutasítás", + "Emission": "Emisszió", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "A FormShot figyeli a GoF mappát és a FormSurface exportjait, amíg ez az ablak nyitva van. Ha egy Form alkalmazás átad valamit, a FormShot itt kérdez rá, mielőtt megnyitná.", + "FormSurface": "FormSurface", + "FormSurface exports": "A FormSurface exportjai", + "From": "Forrás", + "GoF folder": "GoF mappa", + "Hand-off Settings": "Átadási beállítások", + "Hand-offs": "Átadások", + "Hand-offs from {app}": "Átadások innen: {app}", + "Maps": "Térképek", + "Maps by role, without a mesh": "Szerepük szerinti térképek háló nélkül", + "Metalness": "Fémesség", + "Normal": "Normál", + "not found": "nem található", + "Not read yet": "Még nincs beolvasva", + "Nothing from the Form apps is waiting in their hand-off folders.": "A Form alkalmazások átadási mappáiban semmi sem vár.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Semmi sem nyílik meg, amíg Ön nem választ. A textúrák ott maradnak, ahová az alkalmazás írta őket, és szerepük szerint hivatkozunk rájuk.", + "Occlusion, roughness and metalness": "Okklúzió, érdesség és fémesség", + "Opacity": "Átlátszatlanság", + "Open a Hand-off": "Átadás megnyitása", + "Open a Hand-off...": "Átadás megnyitása...", + "Open it": "Megnyitás", + "Open once": "Megnyitás egyszer", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Megnyitja, amit a FormSculpt, a FormFabric, a FormSurface vagy a FormCAD átadott", + "Opened {title} from {app} as a new document": "{title} megnyitva innen: {app}, új dokumentumként", + "Or a path to a file or folder": "Vagy egy fájl vagy mappa útvonala", + "Other maps": "További térképek", + "Reading...": "Beolvasás...", + "Roughness": "Érdesség", + "Sent as": "Küldés módja", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "A FormShot szolgáltatás nem érhető el, ezért ezeket a beállításokat most nem lehet beolvasni vagy módosítani.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Amit a FormSculpt és a FormFabric a GoF mappába tett, és amit a FormSurface exportált. A megnyitás innen nem igényel megerősítést, mert Ön választotta ki.", + "{app} is handing over {title}: {what}.": "A(z) {app} átadja a következőt: {title} ({what}).", + "{count} maps from FormSurface": "{count} térkép a FormSurface-ből", + "{count} maps: {roles}": "{count} térkép: {roles}", + "{count} materials": "{count} anyag", + "{format} file": "{format} fájl", + "{format} file, {count} triangles": "{format} fájl, {count} háromszög", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} háló, {triangles} háromszög, {materials} anyag", + "{n} days ago": "{n} napja" +} diff --git a/frontend/src/i18n/modules/handoff/id.json b/frontend/src/i18n/modules/handoff/id.json new file mode 100644 index 00000000..360870dc --- /dev/null +++ b/frontend/src/i18n/modules/handoff/id.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 dari {count}", + "A Form app is handing something over": "Sebuah aplikasi Form sedang menyerahkan sesuatu", + "A mesh with maps by role": "Mesh dengan map menurut peran", + "A model file": "Sebuah file model", + "Add to this document": "Tambahkan ke dokumen ini", + "Added {title} from {app}": "{title} dari {app} ditambahkan", + "Always allow": "Selalu izinkan", + "Always allow {app}": "Selalu izinkan {app}", + "An object from the GoF folder": "Objek dari folder GoF", + "another app": "aplikasi lain", + "As a new document": "Sebagai dokumen baru", + "Base colour": "Warna dasar", + "Block": "Blokir", + "Choose a hand-off or give a path": "Pilih serah terima atau berikan path", + "Contents": "Isi", + "Could not be read": "Tidak dapat dibaca", + "Decline": "Tolak", + "Emission": "Emisi", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot memantau folder GoF dan ekspor FormSurface selama jendela ini terbuka. Saat aplikasi Form menyerahkan sesuatu, FormShot bertanya di sini sebelum membukanya.", + "FormSurface": "FormSurface", + "FormSurface exports": "Ekspor FormSurface", + "From": "Dari", + "GoF folder": "Folder GoF", + "Hand-off Settings": "Pengaturan Serah Terima", + "Hand-offs": "Serah Terima", + "Hand-offs from {app}": "Serah terima dari {app}", + "Maps": "Map", + "Maps by role, without a mesh": "Map menurut peran, tanpa mesh", + "Metalness": "Metalness", + "Normal": "Normal", + "not found": "tidak ditemukan", + "Not read yet": "Belum dibaca", + "Nothing from the Form apps is waiting in their hand-off folders.": "Tidak ada apa pun dari aplikasi Form yang menunggu di folder serah terima mereka.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Tidak ada yang dibuka sampai Anda memilih. Tekstur tetap berada di tempat aplikasi menulisnya dan dirujuk menurut peran.", + "Occlusion, roughness and metalness": "Oklusi, roughness, dan metalness", + "Opacity": "Opasitas", + "Open a Hand-off": "Buka Serah Terima", + "Open a Hand-off...": "Buka Serah Terima...", + "Open it": "Buka", + "Open once": "Buka sekali", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Buka apa yang diserahkan FormSculpt, FormFabric, FormSurface, atau FormCAD", + "Opened {title} from {app} as a new document": "{title} dari {app} dibuka sebagai dokumen baru", + "Or a path to a file or folder": "Atau path ke file atau folder", + "Other maps": "Map lainnya", + "Reading...": "Membaca...", + "Roughness": "Roughness", + "Sent as": "Dikirim sebagai", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Layanan FormShot tidak dapat dijangkau, sehingga pilihan ini tidak dapat dibaca atau diubah sekarang.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Apa yang ditaruh FormSculpt dan FormFabric di folder GoF dan apa yang diekspor FormSurface. Membukanya dari sini tidak perlu konfirmasi, karena Anda yang memilihnya.", + "{app} is handing over {title}: {what}.": "{app} menyerahkan {title}: {what}.", + "{count} maps from FormSurface": "{count} map dari FormSurface", + "{count} maps: {roles}": "{count} map: {roles}", + "{count} materials": "{count} material", + "{format} file": "File {format}", + "{format} file, {count} triangles": "File {format}, {count} segitiga", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} mesh, {triangles} segitiga, {materials} material", + "{n} days ago": "{n} hari lalu" +} diff --git a/frontend/src/i18n/modules/handoff/it.json b/frontend/src/i18n/modules/handoff/it.json new file mode 100644 index 00000000..ddd8185f --- /dev/null +++ b/frontend/src/i18n/modules/handoff/it.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 di {count}", + "A Form app is handing something over": "Un'app Form sta trasferendo qualcosa", + "A mesh with maps by role": "Una mesh con mappe per ruolo", + "A model file": "Un file di modello", + "Add to this document": "Aggiungi a questo documento", + "Added {title} from {app}": "{title} aggiunto da {app}", + "Always allow": "Consenti sempre", + "Always allow {app}": "Consenti sempre {app}", + "An object from the GoF folder": "Un oggetto dalla cartella GoF", + "another app": "un'altra app", + "As a new document": "Come nuovo documento", + "Base colour": "Colore di base", + "Block": "Blocca", + "Choose a hand-off or give a path": "Scegli un trasferimento o indica un percorso", + "Contents": "Contenuto", + "Could not be read": "Impossibile leggere", + "Decline": "Rifiuta", + "Emission": "Emissione", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot controlla la cartella GoF e le esportazioni di FormSurface finché questa finestra è aperta. Quando un'app Form trasferisce qualcosa, FormShot chiede qui prima di aprirlo.", + "FormSurface": "FormSurface", + "FormSurface exports": "Esportazioni di FormSurface", + "From": "Da", + "GoF folder": "Cartella GoF", + "Hand-off Settings": "Impostazioni dei trasferimenti", + "Hand-offs": "Trasferimenti", + "Hand-offs from {app}": "Trasferimenti da {app}", + "Maps": "Mappe", + "Maps by role, without a mesh": "Mappe per ruolo, senza mesh", + "Metalness": "Metallicità", + "Normal": "Normale", + "not found": "non trovato", + "Not read yet": "Non ancora letto", + "Nothing from the Form apps is waiting in their hand-off folders.": "Nessun file dalle app Form è in attesa nelle loro cartelle di trasferimento.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Non viene aperto nulla finché non scegli. Le texture restano dove l'app le ha scritte e sono referenziate per ruolo.", + "Occlusion, roughness and metalness": "Occlusione, rugosità e metallicità", + "Opacity": "Opacità", + "Open a Hand-off": "Apri un trasferimento", + "Open a Hand-off...": "Apri un trasferimento...", + "Open it": "Apri", + "Open once": "Apri una volta", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Apri ciò che FormSculpt, FormFabric, FormSurface o FormCAD hanno trasferito", + "Opened {title} from {app} as a new document": "{title} aperto da {app} come nuovo documento", + "Or a path to a file or folder": "Oppure un percorso a un file o a una cartella", + "Other maps": "Altre mappe", + "Reading...": "Lettura in corso...", + "Roughness": "Rugosità", + "Sent as": "Inviato come", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Il servizio FormShot non è raggiungibile, quindi queste scelte ora non possono essere lette né modificate.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Ciò che FormSculpt e FormFabric hanno messo nella cartella GoF e ciò che FormSurface ha esportato. Aprire da qui non richiede conferme, perché lo hai scelto tu.", + "{app} is handing over {title}: {what}.": "{app} sta trasferendo {title}: {what}.", + "{count} maps from FormSurface": "{count} mappe da FormSurface", + "{count} maps: {roles}": "{count} mappe: {roles}", + "{count} materials": "{count} materiali", + "{format} file": "File {format}", + "{format} file, {count} triangles": "File {format}, {count} triangoli", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} mesh, {triangles} triangoli, {materials} materiali", + "{n} days ago": "{n} giorni fa" +} diff --git a/frontend/src/i18n/modules/handoff/ja.json b/frontend/src/i18n/modules/handoff/ja.json new file mode 100644 index 00000000..5425b57c --- /dev/null +++ b/frontend/src/i18n/modules/handoff/ja.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 / {count}", + "A Form app is handing something over": "Form アプリが何かを引き渡そうとしています", + "A mesh with maps by role": "役割ごとのマップ付きメッシュ", + "A model file": "モデルファイル", + "Add to this document": "このドキュメントに追加", + "Added {title} from {app}": "{app} から {title} を追加しました", + "Always allow": "常に許可", + "Always allow {app}": "{app} を常に許可", + "An object from the GoF folder": "GoF フォルダのオブジェクト", + "another app": "別のアプリ", + "As a new document": "新規ドキュメントとして", + "Base colour": "ベースカラー", + "Block": "ブロック", + "Choose a hand-off or give a path": "ハンドオフを選ぶか、パスを指定してください", + "Contents": "内容", + "Could not be read": "読み取れませんでした", + "Decline": "拒否", + "Emission": "エミッション", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "このウィンドウを開いている間、FormShot は GoF フォルダと FormSurface の書き出し先を監視します。Form アプリが何かを引き渡すと、開く前にここで確認します。", + "FormSurface": "FormSurface", + "FormSurface exports": "FormSurface の書き出し", + "From": "送信元", + "GoF folder": "GoF フォルダ", + "Hand-off Settings": "ハンドオフ設定", + "Hand-offs": "ハンドオフ", + "Hand-offs from {app}": "{app} からのハンドオフ", + "Maps": "マップ", + "Maps by role, without a mesh": "メッシュなしの役割ごとのマップ", + "Metalness": "メタルネス", + "Normal": "法線", + "not found": "見つかりません", + "Not read yet": "未読み取り", + "Nothing from the Form apps is waiting in their hand-off folders.": "Form アプリのハンドオフフォルダに、待機中のものはありません。", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "選ぶまでは何も開かれません。テクスチャはアプリが書き出した場所に残り、役割で参照されます。", + "Occlusion, roughness and metalness": "オクルージョン、ラフネス、メタルネス", + "Opacity": "不透明度", + "Open a Hand-off": "ハンドオフを開く", + "Open a Hand-off...": "ハンドオフを開く...", + "Open it": "開く", + "Open once": "今回のみ開く", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "FormSculpt、FormFabric、FormSurface、FormCAD から引き渡されたものを開きます", + "Opened {title} from {app} as a new document": "{app} の {title} を新規ドキュメントとして開きました", + "Or a path to a file or folder": "または、ファイルかフォルダのパス", + "Other maps": "その他のマップ", + "Reading...": "読み取り中...", + "Roughness": "ラフネス", + "Sent as": "送信形式", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot サービスに接続できないため、現在これらの選択を読み取ることも変更することもできません。", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "FormSculpt と FormFabric が GoF フォルダに置いたものと、FormSurface が書き出したものです。ここで開くのはご自身で選んだ操作なので、確認は表示されません。", + "{app} is handing over {title}: {what}.": "{app} が {title} を引き渡そうとしています: {what}。", + "{count} maps from FormSurface": "FormSurface からのマップ {count} 個", + "{count} maps: {roles}": "マップ {count} 個: {roles}", + "{count} materials": "マテリアル {count} 個", + "{format} file": "{format} ファイル", + "{format} file, {count} triangles": "{format} ファイル、三角形 {count} 個", + "{meshes} meshes, {triangles} triangles, {materials} materials": "メッシュ {meshes} 個、三角形 {triangles} 個、マテリアル {materials} 個", + "{n} days ago": "{n} 日前" +} diff --git a/frontend/src/i18n/modules/handoff/ko.json b/frontend/src/i18n/modules/handoff/ko.json new file mode 100644 index 00000000..550710fb --- /dev/null +++ b/frontend/src/i18n/modules/handoff/ko.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "{count}개 중 1개", + "A Form app is handing something over": "Form 앱이 무언가를 넘겨주려 합니다", + "A mesh with maps by role": "역할별 맵이 있는 메시", + "A model file": "모델 파일", + "Add to this document": "이 문서에 추가", + "Added {title} from {app}": "{app}의 {title}을(를) 추가했습니다", + "Always allow": "항상 허용", + "Always allow {app}": "{app} 항상 허용", + "An object from the GoF folder": "GoF 폴더의 오브젝트", + "another app": "다른 앱", + "As a new document": "새 문서로", + "Base colour": "베이스 컬러", + "Block": "차단", + "Choose a hand-off or give a path": "핸드오프를 선택하거나 경로를 입력하세요", + "Contents": "내용", + "Could not be read": "읽을 수 없음", + "Decline": "거부", + "Emission": "발광", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "이 창이 열려 있는 동안 FormShot은 GoF 폴더와 FormSurface의 내보내기 폴더를 감시합니다. Form 앱이 무언가를 넘겨주면 열기 전에 여기서 확인합니다.", + "FormSurface": "FormSurface", + "FormSurface exports": "FormSurface 내보내기", + "From": "보낸 곳", + "GoF folder": "GoF 폴더", + "Hand-off Settings": "핸드오프 설정", + "Hand-offs": "핸드오프", + "Hand-offs from {app}": "{app}에서 온 핸드오프", + "Maps": "맵", + "Maps by role, without a mesh": "메시 없이 역할별 맵만", + "Metalness": "메탈니스", + "Normal": "노멀", + "not found": "찾을 수 없음", + "Not read yet": "아직 읽지 않음", + "Nothing from the Form apps is waiting in their hand-off folders.": "Form 앱의 핸드오프 폴더에 대기 중인 항목이 없습니다.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "선택하기 전에는 아무것도 열리지 않습니다. 텍스처는 앱이 기록한 위치에 그대로 있으며 역할별로 참조됩니다.", + "Occlusion, roughness and metalness": "오클루전, 러프니스, 메탈니스", + "Opacity": "불투명도", + "Open a Hand-off": "핸드오프 열기", + "Open a Hand-off...": "핸드오프 열기...", + "Open it": "열기", + "Open once": "한 번만 열기", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "FormSculpt, FormFabric, FormSurface, FormCAD가 넘겨준 항목을 엽니다", + "Opened {title} from {app} as a new document": "{app}의 {title}을(를) 새 문서로 열었습니다", + "Or a path to a file or folder": "또는 파일이나 폴더 경로", + "Other maps": "기타 맵", + "Reading...": "읽는 중...", + "Roughness": "러프니스", + "Sent as": "전송 형식", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot 서비스에 연결할 수 없어 지금은 이 선택을 읽거나 바꿀 수 없습니다.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "FormSculpt와 FormFabric이 GoF 폴더에 넣은 항목과 FormSurface가 내보낸 항목입니다. 직접 선택하는 것이므로 여기서 열 때는 확인 창이 나오지 않습니다.", + "{app} is handing over {title}: {what}.": "{app}이(가) {title}을(를) 넘겨주려 합니다: {what}.", + "{count} maps from FormSurface": "FormSurface의 맵 {count}개", + "{count} maps: {roles}": "맵 {count}개: {roles}", + "{count} materials": "머티리얼 {count}개", + "{format} file": "{format} 파일", + "{format} file, {count} triangles": "{format} 파일, 삼각형 {count}개", + "{meshes} meshes, {triangles} triangles, {materials} materials": "메시 {meshes}개, 삼각형 {triangles}개, 머티리얼 {materials}개", + "{n} days ago": "{n}일 전" +} diff --git a/frontend/src/i18n/modules/handoff/nb.json b/frontend/src/i18n/modules/handoff/nb.json new file mode 100644 index 00000000..0770ed42 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/nb.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 av {count}", + "A Form app is handing something over": "En Form-app overleverer noe", + "A mesh with maps by role": "Et mesh med maps etter rolle", + "A model file": "En modellfil", + "Add to this document": "Legg til i dette dokumentet", + "Added {title} from {app}": "La til {title} fra {app}", + "Always allow": "Tillat alltid", + "Always allow {app}": "Tillat alltid {app}", + "An object from the GoF folder": "Et objekt fra GoF-mappen", + "another app": "en annen app", + "As a new document": "Som et nytt dokument", + "Base colour": "Basisfarge", + "Block": "Blokker", + "Choose a hand-off or give a path": "Velg en overlevering eller oppgi en sti", + "Contents": "Innhold", + "Could not be read": "Kunne ikke leses", + "Decline": "Avslå", + "Emission": "Emisjon", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot overvåker GoF-mappen og eksportene fra FormSurface så lenge dette vinduet er åpent. Når en Form-app overleverer noe, spør FormShot her før det åpnes.", + "FormSurface": "FormSurface", + "FormSurface exports": "Eksporter fra FormSurface", + "From": "Fra", + "GoF folder": "GoF-mappe", + "Hand-off Settings": "Innstillinger for overlevering", + "Hand-offs": "Overleveringer", + "Hand-offs from {app}": "Overleveringer fra {app}", + "Maps": "Maps", + "Maps by role, without a mesh": "Maps etter rolle, uten mesh", + "Metalness": "Metalness", + "Normal": "Normal", + "not found": "ikke funnet", + "Not read yet": "Ikke lest ennå", + "Nothing from the Form apps is waiting in their hand-off folders.": "Ingenting fra Form-appene venter i overleveringsmappene deres.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Ingenting åpnes før du velger. Teksturer blir liggende der appen skrev dem og refereres etter rolle.", + "Occlusion, roughness and metalness": "Okklusjon, ruhet og metalness", + "Opacity": "Opasitet", + "Open a Hand-off": "Åpne en overlevering", + "Open a Hand-off...": "Åpne en overlevering...", + "Open it": "Åpne den", + "Open once": "Åpne én gang", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Åpne det som FormSculpt, FormFabric, FormSurface eller FormCAD har overlevert", + "Opened {title} from {app} as a new document": "Åpnet {title} fra {app} som et nytt dokument", + "Or a path to a file or folder": "Eller en sti til en fil eller mappe", + "Other maps": "Andre maps", + "Reading...": "Leser...", + "Roughness": "Ruhet", + "Sent as": "Sendt som", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot-tjenesten er ikke tilgjengelig, så disse valgene kan ikke leses eller endres nå.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Det FormSculpt og FormFabric la i GoF-mappen og det FormSurface eksporterte. Å åpne noe her krever ingen bekreftelse, fordi du har valgt det selv.", + "{app} is handing over {title}: {what}.": "{app} overleverer {title}: {what}.", + "{count} maps from FormSurface": "{count} maps fra FormSurface", + "{count} maps: {roles}": "{count} maps: {roles}", + "{count} materials": "{count} materialer", + "{format} file": "{format}-fil", + "{format} file, {count} triangles": "{format}-fil, {count} trekanter", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} meshes, {triangles} trekanter, {materials} materialer", + "{n} days ago": "for {n} dager siden" +} diff --git a/frontend/src/i18n/modules/handoff/nl.json b/frontend/src/i18n/modules/handoff/nl.json new file mode 100644 index 00000000..2641a3a5 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/nl.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 van {count}", + "A Form app is handing something over": "Een Form-app draagt iets over", + "A mesh with maps by role": "Een mesh met maps per rol", + "A model file": "Een modelbestand", + "Add to this document": "Aan dit document toevoegen", + "Added {title} from {app}": "{title} uit {app} toegevoegd", + "Always allow": "Altijd toestaan", + "Always allow {app}": "{app} altijd toestaan", + "An object from the GoF folder": "Een object uit de GoF-map", + "another app": "een andere app", + "As a new document": "Als nieuw document", + "Base colour": "Basiskleur", + "Block": "Blokkeren", + "Choose a hand-off or give a path": "Kies een overdracht of geef een pad op", + "Contents": "Inhoud", + "Could not be read": "Kon niet worden gelezen", + "Decline": "Weigeren", + "Emission": "Emissie", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot bewaakt de GoF-map en de exports van FormSurface zolang dit venster openstaat. Als een Form-app iets overdraagt, vraagt FormShot hier eerst toestemming voordat het wordt geopend.", + "FormSurface": "FormSurface", + "FormSurface exports": "Exports van FormSurface", + "From": "Van", + "GoF folder": "GoF-map", + "Hand-off Settings": "Overdrachtsinstellingen", + "Hand-offs": "Overdrachten", + "Hand-offs from {app}": "Overdrachten van {app}", + "Maps": "Maps", + "Maps by role, without a mesh": "Maps per rol, zonder mesh", + "Metalness": "Metalness", + "Normal": "Normal", + "not found": "niet gevonden", + "Not read yet": "Nog niet gelezen", + "Nothing from the Form apps is waiting in their hand-off folders.": "Er wacht niets van de Form-apps in hun overdrachtsmappen.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Er wordt niets geopend voordat je kiest. Teksturen blijven waar de app ze heeft geschreven en worden per rol aangeduid.", + "Occlusion, roughness and metalness": "Occlusie, ruwheid en metalness", + "Opacity": "Dekking", + "Open a Hand-off": "Een overdracht openen", + "Open a Hand-off...": "Een overdracht openen...", + "Open it": "Openen", + "Open once": "Eenmalig openen", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Open wat FormSculpt, FormFabric, FormSurface of FormCAD heeft overgedragen", + "Opened {title} from {app} as a new document": "{title} uit {app} geopend als nieuw document", + "Or a path to a file or folder": "Of een pad naar een bestand of map", + "Other maps": "Overige maps", + "Reading...": "Lezen...", + "Roughness": "Ruwheid", + "Sent as": "Verzonden als", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "De FormShot-service is niet bereikbaar, dus deze keuzes kunnen nu niet worden gelezen of gewijzigd.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Wat FormSculpt en FormFabric in de GoF-map hebben gezet en wat FormSurface heeft geëxporteerd. Hier iets openen vraagt niet om bevestiging, want je hebt het zelf gekozen.", + "{app} is handing over {title}: {what}.": "{app} draagt {title} over: {what}.", + "{count} maps from FormSurface": "{count} maps van FormSurface", + "{count} maps: {roles}": "{count} maps: {roles}", + "{count} materials": "{count} materialen", + "{format} file": "{format}-bestand", + "{format} file, {count} triangles": "{format}-bestand, {count} driehoeken", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} meshes, {triangles} driehoeken, {materials} materialen", + "{n} days ago": "{n} dagen geleden" +} diff --git a/frontend/src/i18n/modules/handoff/pl.json b/frontend/src/i18n/modules/handoff/pl.json new file mode 100644 index 00000000..89ecd471 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/pl.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 z {count}", + "A Form app is handing something over": "Aplikacja Form coś przekazuje", + "A mesh with maps by role": "Siatka z mapami według roli", + "A model file": "Plik modelu", + "Add to this document": "Dodaj do tego dokumentu", + "Added {title} from {app}": "Dodano {title} z aplikacji {app}", + "Always allow": "Zawsze zezwalaj", + "Always allow {app}": "Zawsze zezwalaj aplikacji {app}", + "An object from the GoF folder": "Obiekt z folderu GoF", + "another app": "inna aplikacja", + "As a new document": "Jako nowy dokument", + "Base colour": "Kolor bazowy", + "Block": "Zablokuj", + "Choose a hand-off or give a path": "Wybierz przekazanie albo podaj ścieżkę", + "Contents": "Zawartość", + "Could not be read": "Nie udało się odczytać", + "Decline": "Odrzuć", + "Emission": "Emisja", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot obserwuje folder GoF i eksporty FormSurface, dopóki to okno jest otwarte. Gdy aplikacja Form coś przekazuje, FormShot pyta tutaj, zanim to otworzy.", + "FormSurface": "FormSurface", + "FormSurface exports": "Eksporty z FormSurface", + "From": "Od", + "GoF folder": "Folder GoF", + "Hand-off Settings": "Ustawienia przekazań", + "Hand-offs": "Przekazania", + "Hand-offs from {app}": "Przekazania z aplikacji {app}", + "Maps": "Mapy", + "Maps by role, without a mesh": "Mapy według roli, bez siatki", + "Metalness": "Metaliczność", + "Normal": "Normalne", + "not found": "nie znaleziono", + "Not read yet": "Jeszcze nie odczytano", + "Nothing from the Form apps is waiting in their hand-off folders.": "W folderach przekazań aplikacji Form nic nie czeka.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Nic nie zostanie otwarte, dopóki nie wybierzesz. Tekstury zostają tam, gdzie zapisała je aplikacja, i są wskazywane według roli.", + "Occlusion, roughness and metalness": "Okluzja, chropowatość i metaliczność", + "Opacity": "Nieprzezroczystość", + "Open a Hand-off": "Otwórz przekazanie", + "Open a Hand-off...": "Otwórz przekazanie...", + "Open it": "Otwórz", + "Open once": "Otwórz jednorazowo", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Otwórz to, co przekazał FormSculpt, FormFabric, FormSurface lub FormCAD", + "Opened {title} from {app} as a new document": "Otwarto {title} z aplikacji {app} jako nowy dokument", + "Or a path to a file or folder": "Albo ścieżka do pliku lub folderu", + "Other maps": "Pozostałe mapy", + "Reading...": "Odczytywanie...", + "Roughness": "Chropowatość", + "Sent as": "Przekazano jako", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Usługa FormShot jest nieosiągalna, więc tych ustawień nie można teraz odczytać ani zmienić.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "To, co FormSculpt i FormFabric umieściły w folderze GoF, oraz to, co wyeksportował FormSurface. Otwarcie stąd nie wymaga potwierdzenia, bo sam to wybierasz.", + "{app} is handing over {title}: {what}.": "{app} przekazuje {title}: {what}.", + "{count} maps from FormSurface": "Mapy z FormSurface: {count}", + "{count} maps: {roles}": "Mapy: {count} ({roles})", + "{count} materials": "Materiały: {count}", + "{format} file": "Plik {format}", + "{format} file, {count} triangles": "Plik {format}, trójkąty: {count}", + "{meshes} meshes, {triangles} triangles, {materials} materials": "Siatki: {meshes}, trójkąty: {triangles}, materiały: {materials}", + "{n} days ago": "{n} dni temu" +} diff --git a/frontend/src/i18n/modules/handoff/pt-BR.json b/frontend/src/i18n/modules/handoff/pt-BR.json new file mode 100644 index 00000000..6393cd5a --- /dev/null +++ b/frontend/src/i18n/modules/handoff/pt-BR.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 de {count}", + "A Form app is handing something over": "Um app da família Form está enviando algo", + "A mesh with maps by role": "Uma malha com mapas por função", + "A model file": "Um arquivo de modelo", + "Add to this document": "Adicionar a este documento", + "Added {title} from {app}": "{title} adicionado de {app}", + "Always allow": "Sempre permitir", + "Always allow {app}": "Sempre permitir {app}", + "An object from the GoF folder": "Um objeto da pasta GoF", + "another app": "outro app", + "As a new document": "Como novo documento", + "Base colour": "Cor base", + "Block": "Bloco", + "Choose a hand-off or give a path": "Escolha uma transferência ou informe um caminho", + "Contents": "Conteúdo", + "Could not be read": "Não foi possível ler", + "Decline": "Recusar", + "Emission": "Emissão", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "O FormShot monitora a pasta GoF e as exportações do FormSurface enquanto esta janela estiver aberta. Quando um app da família Form envia algo, o FormShot pergunta aqui antes de abrir.", + "FormSurface": "FormSurface", + "FormSurface exports": "Exportações do FormSurface", + "From": "De", + "GoF folder": "Pasta GoF", + "Hand-off Settings": "Configurações de transferência", + "Hand-offs": "Transferências", + "Hand-offs from {app}": "Transferências de {app}", + "Maps": "Mapas", + "Maps by role, without a mesh": "Mapas por função, sem malha", + "Metalness": "Metalicidade", + "Normal": "Normal", + "not found": "não encontrado", + "Not read yet": "Ainda não lido", + "Nothing from the Form apps is waiting in their hand-off folders.": "Nada dos apps Form está aguardando nas pastas de transferência.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Nada é aberto até você escolher. As texturas ficam onde o app as gravou e são referenciadas por função.", + "Occlusion, roughness and metalness": "Oclusão, rugosidade e metalicidade", + "Opacity": "Opacidade", + "Open a Hand-off": "Abrir transferência", + "Open a Hand-off...": "Abrir transferência...", + "Open it": "Abrir", + "Open once": "Abrir uma vez", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Abra o que o FormSculpt, o FormFabric, o FormSurface ou o FormCAD enviou", + "Opened {title} from {app} as a new document": "{title} de {app} aberto como novo documento", + "Or a path to a file or folder": "Ou um caminho para um arquivo ou pasta", + "Other maps": "Outros mapas", + "Reading...": "Lendo...", + "Roughness": "Rugosidade", + "Sent as": "Enviado como", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "O serviço do FormShot não está acessível, então estas escolhas não podem ser lidas nem alteradas agora.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "O que o FormSculpt e o FormFabric colocam na pasta GoF e o que o FormSurface exportou. Abrir um item aqui não pede confirmação, porque você o escolheu.", + "{app} is handing over {title}: {what}.": "{app} está enviando {title}: {what}.", + "{count} maps from FormSurface": "{count} mapas do FormSurface", + "{count} maps: {roles}": "{count} mapas: {roles}", + "{count} materials": "{count} materiais", + "{format} file": "Arquivo {format}", + "{format} file, {count} triangles": "Arquivo {format}, {count} triângulos", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} malhas, {triangles} triângulos, {materials} materiais", + "{n} days ago": "há {n} dias" +} diff --git a/frontend/src/i18n/modules/handoff/ru.json b/frontend/src/i18n/modules/handoff/ru.json new file mode 100644 index 00000000..bd5eec4d --- /dev/null +++ b/frontend/src/i18n/modules/handoff/ru.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 из {count}", + "A Form app is handing something over": "Приложение Form передаёт данные", + "A mesh with maps by role": "Меш с картами по ролям", + "A model file": "Файл модели", + "Add to this document": "Добавить в этот документ", + "Added {title} from {app}": "Добавлено: {title} из {app}", + "Always allow": "Всегда разрешать", + "Always allow {app}": "Всегда разрешать {app}", + "An object from the GoF folder": "Объект из папки GoF", + "another app": "другое приложение", + "As a new document": "Как новый документ", + "Base colour": "Базовый цвет", + "Block": "Блок", + "Choose a hand-off or give a path": "Выберите передачу или укажите путь", + "Contents": "Содержимое", + "Could not be read": "Не удалось прочитать", + "Decline": "Отклонить", + "Emission": "Излучение", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot следит за папкой GoF и экспортом FormSurface, пока это окно открыто. Когда приложение Form что-то передаёт, FormShot спрашивает здесь, прежде чем открыть.", + "FormSurface": "FormSurface", + "FormSurface exports": "Экспорт FormSurface", + "From": "От", + "GoF folder": "Папка GoF", + "Hand-off Settings": "Настройки передачи", + "Hand-offs": "Передачи", + "Hand-offs from {app}": "Передачи от {app}", + "Maps": "Карты", + "Maps by role, without a mesh": "Карты по ролям, без меша", + "Metalness": "Металличность", + "Normal": "Нормали", + "not found": "не найдено", + "Not read yet": "Ещё не прочитано", + "Nothing from the Form apps is waiting in their hand-off folders.": "В папках передачи приложений Form ничего не ожидает.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Ничего не открывается, пока вы не выберете. Текстуры остаются там, где их записало приложение, и подключаются по ролям.", + "Occlusion, roughness and metalness": "Окклюзия, шероховатость и металличность", + "Opacity": "Непрозрачность", + "Open a Hand-off": "Открыть передачу", + "Open a Hand-off...": "Открыть передачу...", + "Open it": "Открыть", + "Open once": "Открыть один раз", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Откройте то, что передали FormSculpt, FormFabric, FormSurface или FormCAD", + "Opened {title} from {app} as a new document": "Открыто: {title} из {app} как новый документ", + "Or a path to a file or folder": "Или путь к файлу или папке", + "Other maps": "Другие карты", + "Reading...": "Чтение...", + "Roughness": "Шероховатость", + "Sent as": "Передано как", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Служба FormShot недоступна, поэтому сейчас нельзя прочитать или изменить эти настройки.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "То, что FormSculpt и FormFabric кладут в папку GoF, и то, что экспортировал FormSurface. Открытие отсюда не требует подтверждения, потому что вы выбрали это сами.", + "{app} is handing over {title}: {what}.": "{app} передаёт {title}: {what}.", + "{count} maps from FormSurface": "Карт от FormSurface: {count}", + "{count} maps: {roles}": "Карт: {count}: {roles}", + "{count} materials": "Материалов: {count}", + "{format} file": "Файл {format}", + "{format} file, {count} triangles": "Файл {format}, треугольников: {count}", + "{meshes} meshes, {triangles} triangles, {materials} materials": "Мешей: {meshes}, треугольников: {triangles}, материалов: {materials}", + "{n} days ago": "{n} дн. назад" +} diff --git a/frontend/src/i18n/modules/handoff/strings.json b/frontend/src/i18n/modules/handoff/strings.json new file mode 100644 index 00000000..a9e61bad --- /dev/null +++ b/frontend/src/i18n/modules/handoff/strings.json @@ -0,0 +1,62 @@ +[ + "1 of {count}", + "A Form app is handing something over", + "A mesh with maps by role", + "A model file", + "Add to this document", + "Added {title} from {app}", + "Always allow", + "Always allow {app}", + "An object from the GoF folder", + "another app", + "As a new document", + "Base colour", + "Block", + "Choose a hand-off or give a path", + "Contents", + "Could not be read", + "Decline", + "Emission", + "FormCAD", + "FormFabric", + "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.", + "FormSurface", + "FormSurface exports", + "From", + "GoF folder", + "Hand-off Settings", + "Hand-offs", + "Hand-offs from {app}", + "Maps", + "Maps by role, without a mesh", + "Metalness", + "Normal", + "not found", + "Not read yet", + "Nothing from the Form apps is waiting in their hand-off folders.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.", + "Occlusion, roughness and metalness", + "Opacity", + "Open a Hand-off", + "Open a Hand-off...", + "Open it", + "Open once", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over", + "Opened {title} from {app} as a new document", + "Or a path to a file or folder", + "Other maps", + "Reading...", + "Roughness", + "Sent as", + "The FormShot service is not reachable, so these choices cannot be read or changed now.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.", + "{app} is handing over {title}: {what}.", + "{count} maps from FormSurface", + "{count} maps: {roles}", + "{count} materials", + "{format} file", + "{format} file, {count} triangles", + "{meshes} meshes, {triangles} triangles, {materials} materials", + "{n} days ago" +] diff --git a/frontend/src/i18n/modules/handoff/sv.json b/frontend/src/i18n/modules/handoff/sv.json new file mode 100644 index 00000000..1ee1ef01 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/sv.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 av {count}", + "A Form app is handing something over": "En Form-app lämnar över något", + "A mesh with maps by role": "En mesh med maps per roll", + "A model file": "En modellfil", + "Add to this document": "Lägg till i det här dokumentet", + "Added {title} from {app}": "Lade till {title} från {app}", + "Always allow": "Tillåt alltid", + "Always allow {app}": "Tillåt alltid {app}", + "An object from the GoF folder": "Ett objekt från GoF-mappen", + "another app": "en annan app", + "As a new document": "Som ett nytt dokument", + "Base colour": "Basfärg", + "Block": "Blockera", + "Choose a hand-off or give a path": "Välj en överlämning eller ange en sökväg", + "Contents": "Innehåll", + "Could not be read": "Kunde inte läsas", + "Decline": "Avböj", + "Emission": "Emission", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot bevakar GoF-mappen och FormSurfaces exporter så länge det här fönstret är öppet. När en Form-app lämnar över något frågar FormShot här innan det öppnas.", + "FormSurface": "FormSurface", + "FormSurface exports": "Exporter från FormSurface", + "From": "Från", + "GoF folder": "GoF-mapp", + "Hand-off Settings": "Inställningar för överlämning", + "Hand-offs": "Överlämningar", + "Hand-offs from {app}": "Överlämningar från {app}", + "Maps": "Maps", + "Maps by role, without a mesh": "Maps per roll, utan mesh", + "Metalness": "Metallighet", + "Normal": "Normal", + "not found": "hittades inte", + "Not read yet": "Inte läst ännu", + "Nothing from the Form apps is waiting in their hand-off folders.": "Inget från Form-apparna väntar i deras överlämningsmappar.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Inget öppnas förrän du väljer. Texturer ligger kvar där appen skrev dem och refereras per roll.", + "Occlusion, roughness and metalness": "Ocklusion, råhet och metallighet", + "Opacity": "Opacitet", + "Open a Hand-off": "Öppna en överlämning", + "Open a Hand-off...": "Öppna en överlämning...", + "Open it": "Öppna den", + "Open once": "Öppna en gång", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Öppna det som FormSculpt, FormFabric, FormSurface eller FormCAD lämnat över", + "Opened {title} from {app} as a new document": "Öppnade {title} från {app} som ett nytt dokument", + "Or a path to a file or folder": "Eller en sökväg till en fil eller mapp", + "Other maps": "Övriga maps", + "Reading...": "Läser...", + "Roughness": "Råhet", + "Sent as": "Skickat som", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot-tjänsten går inte att nå, så de här valen kan inte läsas eller ändras nu.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Det som FormSculpt och FormFabric lade i GoF-mappen och det som FormSurface exporterade. Att öppna något här kräver ingen fråga, eftersom du har valt det.", + "{app} is handing over {title}: {what}.": "{app} lämnar över {title}: {what}.", + "{count} maps from FormSurface": "{count} maps från FormSurface", + "{count} maps: {roles}": "{count} maps: {roles}", + "{count} materials": "{count} material", + "{format} file": "{format}-fil", + "{format} file, {count} triangles": "{format}-fil, {count} trianglar", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} meshar, {triangles} trianglar, {materials} material", + "{n} days ago": "för {n} dagar sedan" +} diff --git a/frontend/src/i18n/modules/handoff/th.json b/frontend/src/i18n/modules/handoff/th.json new file mode 100644 index 00000000..25e208a5 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/th.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 จาก {count}", + "A Form app is handing something over": "แอป Form กำลังส่งบางอย่างมาให้", + "A mesh with maps by role": "เมชพร้อมแมปตามบทบาท", + "A model file": "ไฟล์โมเดล", + "Add to this document": "เพิ่มในเอกสารนี้", + "Added {title} from {app}": "เพิ่ม {title} จาก {app} แล้ว", + "Always allow": "อนุญาตเสมอ", + "Always allow {app}": "อนุญาต {app} เสมอ", + "An object from the GoF folder": "วัตถุจากโฟลเดอร์ GoF", + "another app": "แอปอื่น", + "As a new document": "เป็นเอกสารใหม่", + "Base colour": "สีฐาน", + "Block": "บล็อก", + "Choose a hand-off or give a path": "เลือกรายการส่งต่อหรือระบุพาธ", + "Contents": "เนื้อหา", + "Could not be read": "อ่านไม่ได้", + "Decline": "ปฏิเสธ", + "Emission": "การเปล่งแสง", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot เฝ้าดูโฟลเดอร์ GoF และไฟล์ที่ FormSurface ส่งออกขณะเปิดหน้าต่างนี้ เมื่อแอป Form ส่งอะไรมา FormShot จะถามที่นี่ก่อนเปิด", + "FormSurface": "FormSurface", + "FormSurface exports": "ไฟล์ส่งออกของ FormSurface", + "From": "จาก", + "GoF folder": "โฟลเดอร์ GoF", + "Hand-off Settings": "การตั้งค่าการส่งต่อ", + "Hand-offs": "รายการส่งต่อ", + "Hand-offs from {app}": "รายการส่งต่อจาก {app}", + "Maps": "แมป", + "Maps by role, without a mesh": "แมปตามบทบาท ไม่มีเมช", + "Metalness": "ความเป็นโลหะ", + "Normal": "นอร์มอล", + "not found": "ไม่พบ", + "Not read yet": "ยังไม่ได้อ่าน", + "Nothing from the Form apps is waiting in their hand-off folders.": "ไม่มีสิ่งใดจากแอป Form รออยู่ในโฟลเดอร์ส่งต่อ", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "จะไม่เปิดอะไรจนกว่าคุณจะเลือก เท็กซ์เจอร์ยังอยู่ที่เดิมที่แอปเขียนไว้ และอ้างอิงตามบทบาท", + "Occlusion, roughness and metalness": "ออคลูชัน ความหยาบ และความเป็นโลหะ", + "Opacity": "ความทึบ", + "Open a Hand-off": "เปิดรายการส่งต่อ", + "Open a Hand-off...": "เปิดรายการส่งต่อ...", + "Open it": "เปิดเลย", + "Open once": "เปิดครั้งเดียว", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "เปิดสิ่งที่ FormSculpt, FormFabric, FormSurface หรือ FormCAD ส่งมา", + "Opened {title} from {app} as a new document": "เปิด {title} จาก {app} เป็นเอกสารใหม่แล้ว", + "Or a path to a file or folder": "หรือพาธของไฟล์หรือโฟลเดอร์", + "Other maps": "แมปอื่น ๆ", + "Reading...": "กำลังอ่าน...", + "Roughness": "ความหยาบ", + "Sent as": "ส่งมาเป็น", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "เข้าถึงบริการ FormShot ไม่ได้ จึงอ่านหรือเปลี่ยนตัวเลือกเหล่านี้ไม่ได้ในขณะนี้", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "สิ่งที่ FormSculpt และ FormFabric วางไว้ในโฟลเดอร์ GoF และสิ่งที่ FormSurface ส่งออก การเปิดรายการที่นี่ไม่ต้องถามอีก เพราะคุณเป็นผู้เลือกเอง", + "{app} is handing over {title}: {what}.": "{app} กำลังส่ง {title} มาให้: {what}", + "{count} maps from FormSurface": "{count} แมปจาก FormSurface", + "{count} maps: {roles}": "{count} แมป: {roles}", + "{count} materials": "{count} แมทีเรียล", + "{format} file": "ไฟล์ {format}", + "{format} file, {count} triangles": "ไฟล์ {format}, {count} สามเหลี่ยม", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} เมช, {triangles} สามเหลี่ยม, {materials} แมทีเรียล", + "{n} days ago": "{n} วันที่แล้ว" +} diff --git a/frontend/src/i18n/modules/handoff/tr.json b/frontend/src/i18n/modules/handoff/tr.json new file mode 100644 index 00000000..e57908e2 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/tr.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 / {count}", + "A Form app is handing something over": "Bir Form uygulaması bir şey devrediyor", + "A mesh with maps by role": "Role göre haritalarla bir mesh", + "A model file": "Bir model dosyası", + "Add to this document": "Bu belgeye ekle", + "Added {title} from {app}": "{app} uygulamasından {title} eklendi", + "Always allow": "Her zaman izin ver", + "Always allow {app}": "{app} için her zaman izin ver", + "An object from the GoF folder": "GoF klasöründen bir nesne", + "another app": "başka bir uygulama", + "As a new document": "Yeni belge olarak", + "Base colour": "Temel renk", + "Block": "Blok", + "Choose a hand-off or give a path": "Bir devir seçin veya yol girin", + "Contents": "İçerik", + "Could not be read": "Okunamadı", + "Decline": "Reddet", + "Emission": "Emisyon", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "Bu pencere açıkken FormShot, GoF klasörünü ve FormSurface dışa aktarımlarını izler. Bir Form uygulaması bir şey devrettiğinde FormShot, açmadan önce burada sorar.", + "FormSurface": "FormSurface", + "FormSurface exports": "FormSurface dışa aktarımları", + "From": "Kaynak", + "GoF folder": "GoF klasörü", + "Hand-off Settings": "Devir Ayarları", + "Hand-offs": "Devirler", + "Hand-offs from {app}": "{app} devirleri", + "Maps": "Haritalar", + "Maps by role, without a mesh": "Role göre haritalar, mesh olmadan", + "Metalness": "Metalik", + "Normal": "Normal", + "not found": "bulunamadı", + "Not read yet": "Henüz okunmadı", + "Nothing from the Form apps is waiting in their hand-off folders.": "Form uygulamalarının devir klasörlerinde bekleyen bir şey yok.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Siz seçmeden hiçbir şey açılmaz. Dokular uygulamanın yazdığı yerde kalır ve role göre başvurulur.", + "Occlusion, roughness and metalness": "Oklüzyon, pürüzlülük ve metaliklik", + "Opacity": "Opaklık", + "Open a Hand-off": "Devri Aç", + "Open a Hand-off...": "Devri Aç...", + "Open it": "Aç", + "Open once": "Bir kez aç", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "FormSculpt, FormFabric, FormSurface veya FormCAD'in devrettiğini açın", + "Opened {title} from {app} as a new document": "{app} uygulamasından {title} yeni belge olarak açıldı", + "Or a path to a file or folder": "Veya bir dosya ya da klasör yolu", + "Other maps": "Diğer haritalar", + "Reading...": "Okunuyor...", + "Roughness": "Pürüzlülük", + "Sent as": "Gönderilme biçimi", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot hizmetine ulaşılamıyor, bu yüzden bu seçimler şu anda okunamaz veya değiştirilemez.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "FormSculpt ve FormFabric'in GoF klasörüne koyduklarıyla FormSurface'in dışa aktardıkları. Buradan açmak onay gerektirmez, çünkü onu siz seçtiniz.", + "{app} is handing over {title}: {what}.": "{app}, {title} öğesini devrediyor: {what}.", + "{count} maps from FormSurface": "FormSurface'ten {count} harita", + "{count} maps: {roles}": "{count} harita: {roles}", + "{count} materials": "{count} malzeme", + "{format} file": "{format} dosyası", + "{format} file, {count} triangles": "{format} dosyası, {count} üçgen", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} mesh, {triangles} üçgen, {materials} malzeme", + "{n} days ago": "{n} gün önce" +} diff --git a/frontend/src/i18n/modules/handoff/uk.json b/frontend/src/i18n/modules/handoff/uk.json new file mode 100644 index 00000000..6b193848 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/uk.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 із {count}", + "A Form app is handing something over": "Застосунок Form передає дані", + "A mesh with maps by role": "Меш із картами за ролями", + "A model file": "Файл моделі", + "Add to this document": "Додати до цього документа", + "Added {title} from {app}": "Додано: {title} з {app}", + "Always allow": "Завжди дозволяти", + "Always allow {app}": "Завжди дозволяти {app}", + "An object from the GoF folder": "Об'єкт із теки GoF", + "another app": "інший застосунок", + "As a new document": "Як новий документ", + "Base colour": "Базовий колір", + "Block": "Блок", + "Choose a hand-off or give a path": "Виберіть передачу або вкажіть шлях", + "Contents": "Вміст", + "Could not be read": "Не вдалося прочитати", + "Decline": "Відхилити", + "Emission": "Випромінювання", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot стежить за текою GoF та експортом FormSurface, поки це вікно відкрите. Коли застосунок Form щось передає, FormShot питає тут, перш ніж відкрити.", + "FormSurface": "FormSurface", + "FormSurface exports": "Експорт FormSurface", + "From": "Від", + "GoF folder": "Тека GoF", + "Hand-off Settings": "Налаштування передачі", + "Hand-offs": "Передачі", + "Hand-offs from {app}": "Передачі від {app}", + "Maps": "Карти", + "Maps by role, without a mesh": "Карти за ролями, без меша", + "Metalness": "Металевість", + "Normal": "Нормалі", + "not found": "не знайдено", + "Not read yet": "Ще не прочитано", + "Nothing from the Form apps is waiting in their hand-off folders.": "У теках передачі застосунків Form нічого не очікує.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Нічого не відкривається, поки ви не оберете. Текстури залишаються там, де їх записав застосунок, і підключаються за ролями.", + "Occlusion, roughness and metalness": "Оклюзія, шорсткість і металевість", + "Opacity": "Непрозорість", + "Open a Hand-off": "Відкрити передачу", + "Open a Hand-off...": "Відкрити передачу...", + "Open it": "Відкрити", + "Open once": "Відкрити один раз", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Відкрийте те, що передали FormSculpt, FormFabric, FormSurface або FormCAD", + "Opened {title} from {app} as a new document": "Відкрито: {title} з {app} як новий документ", + "Or a path to a file or folder": "Або шлях до файлу чи теки", + "Other maps": "Інші карти", + "Reading...": "Читання...", + "Roughness": "Шорсткість", + "Sent as": "Передано як", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Служба FormShot недоступна, тому зараз не можна прочитати чи змінити ці налаштування.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Те, що FormSculpt і FormFabric кладуть у теку GoF, і те, що експортував FormSurface. Відкриття звідси не потребує підтвердження, бо ви обрали це самі.", + "{app} is handing over {title}: {what}.": "{app} передає {title}: {what}.", + "{count} maps from FormSurface": "Карт від FormSurface: {count}", + "{count} maps: {roles}": "Карт: {count}: {roles}", + "{count} materials": "Матеріалів: {count}", + "{format} file": "Файл {format}", + "{format} file, {count} triangles": "Файл {format}, трикутників: {count}", + "{meshes} meshes, {triangles} triangles, {materials} materials": "Мешів: {meshes}, трикутників: {triangles}, матеріалів: {materials}", + "{n} days ago": "{n} дн. тому" +} diff --git a/frontend/src/i18n/modules/handoff/vi.json b/frontend/src/i18n/modules/handoff/vi.json new file mode 100644 index 00000000..ff32c200 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/vi.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "1 trên {count}", + "A Form app is handing something over": "Một ứng dụng Form đang chuyển giao nội dung", + "A mesh with maps by role": "Một mesh kèm các map theo vai trò", + "A model file": "Một tệp mô hình", + "Add to this document": "Thêm vào tài liệu này", + "Added {title} from {app}": "Đã thêm {title} từ {app}", + "Always allow": "Luôn cho phép", + "Always allow {app}": "Luôn cho phép {app}", + "An object from the GoF folder": "Một đối tượng từ thư mục GoF", + "another app": "ứng dụng khác", + "As a new document": "Làm tài liệu mới", + "Base colour": "Màu cơ bản", + "Block": "Chặn", + "Choose a hand-off or give a path": "Chọn một mục chuyển giao hoặc nhập đường dẫn", + "Contents": "Nội dung", + "Could not be read": "Không đọc được", + "Decline": "Từ chối", + "Emission": "Phát sáng", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "FormShot theo dõi thư mục GoF và các tệp FormSurface xuất ra khi cửa sổ này đang mở. Khi một ứng dụng Form chuyển giao nội dung, FormShot sẽ hỏi tại đây trước khi mở.", + "FormSurface": "FormSurface", + "FormSurface exports": "Tệp xuất của FormSurface", + "From": "Từ", + "GoF folder": "Thư mục GoF", + "Hand-off Settings": "Cài đặt chuyển giao", + "Hand-offs": "Chuyển giao", + "Hand-offs from {app}": "Chuyển giao từ {app}", + "Maps": "Map", + "Maps by role, without a mesh": "Các map theo vai trò, không có mesh", + "Metalness": "Độ kim loại", + "Normal": "Pháp tuyến", + "not found": "không tìm thấy", + "Not read yet": "Chưa đọc", + "Nothing from the Form apps is waiting in their hand-off folders.": "Không có gì từ các ứng dụng Form đang chờ trong thư mục chuyển giao của chúng.", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "Sẽ không mở gì cho đến khi bạn chọn. Kết cấu vẫn nằm ở nơi ứng dụng đã ghi và được tham chiếu theo vai trò.", + "Occlusion, roughness and metalness": "Độ che khuất, độ nhám và độ kim loại", + "Opacity": "Độ mờ đục", + "Open a Hand-off": "Mở một mục chuyển giao", + "Open a Hand-off...": "Mở một mục chuyển giao...", + "Open it": "Mở ngay", + "Open once": "Mở một lần", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "Mở nội dung mà FormSculpt, FormFabric, FormSurface hoặc FormCAD đã chuyển giao", + "Opened {title} from {app} as a new document": "Đã mở {title} từ {app} thành tài liệu mới", + "Or a path to a file or folder": "Hoặc đường dẫn tới một tệp hoặc thư mục", + "Other maps": "Các map khác", + "Reading...": "Đang đọc...", + "Roughness": "Độ nhám", + "Sent as": "Gửi dưới dạng", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "Không kết nối được dịch vụ FormShot nên hiện chưa thể đọc hay đổi các lựa chọn này.", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "Những gì FormSculpt và FormFabric đặt trong thư mục GoF và những gì FormSurface đã xuất. Mở một mục tại đây không cần hỏi lại vì chính bạn đã chọn.", + "{app} is handing over {title}: {what}.": "{app} đang chuyển giao {title}: {what}.", + "{count} maps from FormSurface": "{count} map từ FormSurface", + "{count} maps: {roles}": "{count} map: {roles}", + "{count} materials": "{count} vật liệu", + "{format} file": "Tệp {format}", + "{format} file, {count} triangles": "Tệp {format}, {count} tam giác", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} mesh, {triangles} tam giác, {materials} vật liệu", + "{n} days ago": "{n} ngày trước" +} diff --git a/frontend/src/i18n/modules/handoff/zh-CN.json b/frontend/src/i18n/modules/handoff/zh-CN.json new file mode 100644 index 00000000..48f68b08 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/zh-CN.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "第 1 个,共 {count} 个", + "A Form app is handing something over": "有 Form 应用正在移交内容", + "A mesh with maps by role": "按用途分类贴图的网格", + "A model file": "模型文件", + "Add to this document": "添加到此文档", + "Added {title} from {app}": "已从 {app} 添加 {title}", + "Always allow": "始终允许", + "Always allow {app}": "始终允许 {app}", + "An object from the GoF folder": "GoF 文件夹中的对象", + "another app": "另一个应用", + "As a new document": "作为新文档", + "Base colour": "基础色", + "Block": "阻止", + "Choose a hand-off or give a path": "选择一个移交,或提供路径", + "Contents": "内容", + "Could not be read": "无法读取", + "Decline": "拒绝", + "Emission": "自发光", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "此窗口打开期间,FormShot 会监视 GoF 文件夹和 FormSurface 的导出。当 Form 应用移交内容时,FormShot 会先在此询问,再打开。", + "FormSurface": "FormSurface", + "FormSurface exports": "FormSurface 导出", + "From": "来自", + "GoF folder": "GoF 文件夹", + "Hand-off Settings": "移交设置", + "Hand-offs": "移交", + "Hand-offs from {app}": "来自 {app} 的移交", + "Maps": "贴图", + "Maps by role, without a mesh": "按用途分类的贴图,不含网格", + "Metalness": "金属度", + "Normal": "法线", + "not found": "未找到", + "Not read yet": "尚未读取", + "Nothing from the Form apps is waiting in their hand-off folders.": "Form 应用的移交文件夹中没有待处理的内容。", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "在你选择之前不会打开任何内容。纹理保留在应用写入的位置,并按用途引用。", + "Occlusion, roughness and metalness": "遮挡、粗糙度和金属度", + "Opacity": "不透明度", + "Open a Hand-off": "打开移交", + "Open a Hand-off...": "打开移交...", + "Open it": "打开", + "Open once": "仅打开一次", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "打开 FormSculpt、FormFabric、FormSurface 或 FormCAD 移交的内容", + "Opened {title} from {app} as a new document": "已将来自 {app} 的 {title} 作为新文档打开", + "Or a path to a file or folder": "或文件或文件夹的路径", + "Other maps": "其他贴图", + "Reading...": "正在读取...", + "Roughness": "粗糙度", + "Sent as": "发送形式", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot 服务无法访问,因此现在无法读取或更改这些选项。", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "FormSculpt 和 FormFabric 放入 GoF 文件夹的内容,以及 FormSurface 导出的内容。由你自己选择,因此在此打开无需提示。", + "{app} is handing over {title}: {what}.": "{app} 正在移交 {title}:{what}。", + "{count} maps from FormSurface": "来自 FormSurface 的 {count} 张贴图", + "{count} maps: {roles}": "{count} 张贴图:{roles}", + "{count} materials": "{count} 个材质", + "{format} file": "{format} 文件", + "{format} file, {count} triangles": "{format} 文件,{count} 个三角形", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} 个网格,{triangles} 个三角形,{materials} 个材质", + "{n} days ago": "{n} 天前" +} diff --git a/frontend/src/i18n/modules/handoff/zh-TW.json b/frontend/src/i18n/modules/handoff/zh-TW.json new file mode 100644 index 00000000..9c933432 --- /dev/null +++ b/frontend/src/i18n/modules/handoff/zh-TW.json @@ -0,0 +1,62 @@ +{ + "1 of {count}": "第 1 個,共 {count} 個", + "A Form app is handing something over": "有 Form 應用程式正在移交內容", + "A mesh with maps by role": "依用途分類貼圖的網格", + "A model file": "模型檔案", + "Add to this document": "加入此文件", + "Added {title} from {app}": "已從 {app} 加入 {title}", + "Always allow": "一律允許", + "Always allow {app}": "一律允許 {app}", + "An object from the GoF folder": "GoF 資料夾中的物件", + "another app": "另一個應用程式", + "As a new document": "作為新文件", + "Base colour": "基礎色", + "Block": "封鎖", + "Choose a hand-off or give a path": "選擇一個移交,或提供路徑", + "Contents": "內容", + "Could not be read": "無法讀取", + "Decline": "拒絕", + "Emission": "自發光", + "FormCAD": "FormCAD", + "FormFabric": "FormFabric", + "FormSculpt": "FormSculpt", + "FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.": "此視窗開啟期間,FormShot 會監看 GoF 資料夾和 FormSurface 的匯出。當 Form 應用程式移交內容時,FormShot 會先在此詢問,再開啟。", + "FormSurface": "FormSurface", + "FormSurface exports": "FormSurface 匯出", + "From": "來自", + "GoF folder": "GoF 資料夾", + "Hand-off Settings": "移交設定", + "Hand-offs": "移交", + "Hand-offs from {app}": "來自 {app} 的移交", + "Maps": "貼圖", + "Maps by role, without a mesh": "依用途分類的貼圖,不含網格", + "Metalness": "金屬度", + "Normal": "法線", + "not found": "找不到", + "Not read yet": "尚未讀取", + "Nothing from the Form apps is waiting in their hand-off folders.": "Form 應用程式的移交資料夾中沒有待處理的內容。", + "Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.": "在你選擇之前不會開啟任何內容。紋理保留在應用程式寫入的位置,並依用途參照。", + "Occlusion, roughness and metalness": "遮蔽、粗糙度和金屬度", + "Opacity": "不透明度", + "Open a Hand-off": "開啟移交", + "Open a Hand-off...": "開啟移交...", + "Open it": "開啟", + "Open once": "僅開啟一次", + "Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over": "開啟 FormSculpt、FormFabric、FormSurface 或 FormCAD 移交的內容", + "Opened {title} from {app} as a new document": "已將來自 {app} 的 {title} 作為新文件開啟", + "Or a path to a file or folder": "或檔案或資料夾的路徑", + "Other maps": "其他貼圖", + "Reading...": "正在讀取...", + "Roughness": "粗糙度", + "Sent as": "傳送形式", + "The FormShot service is not reachable, so these choices cannot be read or changed now.": "FormShot 服務無法連線,因此現在無法讀取或變更這些選項。", + "What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.": "FormSculpt 和 FormFabric 放入 GoF 資料夾的內容,以及 FormSurface 匯出的內容。由你自己選擇,因此在此開啟無需提示。", + "{app} is handing over {title}: {what}.": "{app} 正在移交 {title}:{what}。", + "{count} maps from FormSurface": "來自 FormSurface 的 {count} 張貼圖", + "{count} maps: {roles}": "{count} 張貼圖:{roles}", + "{count} materials": "{count} 個材質", + "{format} file": "{format} 檔案", + "{format} file, {count} triangles": "{format} 檔案,{count} 個三角形", + "{meshes} meshes, {triangles} triangles, {materials} materials": "{meshes} 個網格,{triangles} 個三角形,{materials} 個材質", + "{n} days ago": "{n} 天前" +} diff --git a/frontend/src/i18n/modules/import/cs.json b/frontend/src/i18n/modules/import/cs.json new file mode 100644 index 00000000..d803738c --- /dev/null +++ b/frontend/src/i18n/modules/import/cs.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D modely", + "Automatic": "Automaticky", + "CAD quality": "Kvalita CAD", + "Centimetres (cm)": "Centimetry (cm)", + "Centre on the origin": "Vystředit na počátek", + "Choose model files and import them into the scene with options.": "Vyberte soubory modelů a importujte je do scény s využitím voleb.", + "Cleaning up meshes": "Čištění sítí", + "Clear Recent Imports": "Vymazat nedávné importy", + "Could not import the file: {reason}": "Soubor se nepodařilo importovat: {reason}", + "Could not import {name}: {reason}": "Soubor {name} se nepodařilo importovat: {reason}", + "Could not open {name}: {reason}": "Soubor {name} se nepodařilo otevřít: {reason}", + "Could not read the file: {reason}": "Soubor se nepodařilo přečíst: {reason}", + "Could not reimport: {reason}": "Opakovaný import se nezdařil: {reason}", + "Could not send the file: {reason}": "Soubor se nepodařilo odeslat: {reason}", + "Discard unsaved changes?": "Zahodit neuložené změny?", + "Draft": "Koncept", + "Drop to import into the scene": "Pusťte pro import do scény", + "Feet (ft)": "Stopy (ft)", + "Format": "Formát", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot otevírá najednou jen jeden projekt; ostatní soubory projektů ({n}) zůstaly neotevřené.", + "Frame the view after import": "Po importu zarámovat pohled", + "High": "Vysoká", + "Import": "Importovat", + "Import All": "Importovat vše", + "Import Files": "Importovat soubory", + "Import Model": "Importovat model", + "Import Recent File": "Importovat nedávný soubor", + "Imported {name}.": "Importováno: {name}.", + "Imported {name}: {parts} parts, {triangles} triangles.": "Importováno: {name}, {parts} částí, {triangles} trojúhelníků.", + "Imported {name}: {parts} parts.": "Importováno: {name}, {parts} částí.", + "Importing": "Importuje se", + "In this file": "V tomto souboru", + "Inches (in)": "Palce (in)", + "Making materials": "Vytváření materiálů", + "Materials": "Materiály", + "Medium": "Střední", + "Merge into one group": "Sloučit do jedné skupiny", + "Metres (m)": "Metry (m)", + "Millimetres (mm)": "Milimetry (mm)", + "No Recent Imports": "Žádné nedávné importy", + "No warnings.": "Žádná upozornění.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Není co importovat: FormShot importuje soubory GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP a IGES.", + "One file beside it": "Jeden soubor vedle něj", + "Opening {name} will close the open project and discard its unsaved changes.": "Otevřením {name} se zavře otevřený projekt a zahodí se jeho neuložené změny.", + "Options": "Možnosti", + "Parts": "Části", + "Placing in the scene": "Umísťování do scény", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Znovu načte zdrojové soubory vybraných částí (nebo všech importovaných částí) a ponechá jejich materiály.", + "Reading the file": "Čtení souboru", + "Reading the file...": "Čtení souboru...", + "Recent Imports": "Nedávné importy", + "Reimport": "Importovat znovu", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Znovu importováno: aktualizováno {matched}, nových {added}, skryto {hidden}.", + "Send model files to FormShot and import them into the scene with options.": "Odešlete soubory modelů do FormShotu a importujte je do scény s využitím voleb.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Více souborů se importuje jeden po druhém. Vyrovnávací paměti, materiály a textury vedle modelu se importují spolu s ním.", + "Size": "Velikost", + "Stand on the floor": "Postavit na podlahu", + "Tessellating CAD surfaces": "Teselace ploch CAD", + "The engine decides from the file.": "Engine rozhodne podle souboru.", + "The engine did not start an import job": "Engine nespustil úlohu importu", + "The engine did not start in time, so the files FormShot was given were not opened.": "Engine se nespustil včas, takže soubory předané FormShotu nebyly otevřeny.", + "The file says it is in {unit}.": "Soubor udává jednotku: {unit}.", + "The import failed": "Import se nezdařil", + "The import goes on; the files after it were not imported.": "Import pokračuje; následující soubory nebyly importovány.", + "The import of {name} was cancelled.": "Import souboru {name} byl zrušen.", + "The upload failed ({status})": "Nahrání se nezdařilo ({status})", + "The upload was cancelled": "Nahrávání bylo zrušeno", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Tento engine se nemůže před importem podívat dovnitř souboru, takže souhrn zůstane prázdný.", + "This engine cannot stop an import once it has started": "Tento engine nemůže zastavit import, jakmile začal", + "This engine imports in one step, so there is no progress to show or stop.": "Tento engine importuje jedním krokem, takže není co zobrazit ani zastavit.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Soubor neuvádí jednotky. FormShot podle velikosti odhadl jednotky ({unit}); před importem je zkontrolujte.", + "Triangles": "Trojúhelníky", + "Ultra": "Ultra", + "Units": "Jednotky", + "Up axis": "Osa nahoru", + "Up axis in file": "Osa nahoru v souboru", + "Uploading": "Nahrávání", + "Y is up": "Y je nahoru", + "Z is up": "Z je nahoru", + "centimetres": "centimetry", + "feet": "stopy", + "inches": "palce", + "metres": "metry", + "millimetres": "milimetry", + "{i} of {n}": "{i} z {n}", + "{n} files beside it": "{n} souborů vedle něj", + "{n} files were not imported.": "Nebylo importováno souborů: {n}.", + "{n} warnings; the Scene page lists the parts.": "Upozornění: {n}; části vypisuje stránka scény." +} diff --git a/frontend/src/i18n/modules/import/da.json b/frontend/src/i18n/modules/import/da.json new file mode 100644 index 00000000..9b20f660 --- /dev/null +++ b/frontend/src/i18n/modules/import/da.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D-modeller", + "Automatic": "Automatisk", + "CAD quality": "CAD-kvalitet", + "Centimetres (cm)": "Centimeter (cm)", + "Centre on the origin": "Centrer på origo", + "Choose model files and import them into the scene with options.": "Vælg modelfiler, og importer dem til scenen med indstillinger.", + "Cleaning up meshes": "Rydder meshes op", + "Clear Recent Imports": "Ryd seneste importer", + "Could not import the file: {reason}": "Filen kunne ikke importeres: {reason}", + "Could not import {name}: {reason}": "{name} kunne ikke importeres: {reason}", + "Could not open {name}: {reason}": "{name} kunne ikke åbnes: {reason}", + "Could not read the file: {reason}": "Filen kunne ikke læses: {reason}", + "Could not reimport: {reason}": "Det lykkedes ikke at importere igen: {reason}", + "Could not send the file: {reason}": "Filen kunne ikke sendes: {reason}", + "Discard unsaved changes?": "Kassér ikke-gemte ændringer?", + "Draft": "Udkast", + "Drop to import into the scene": "Slip for at importere til scenen", + "Feet (ft)": "Fod (ft)", + "Format": "Format", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot åbner ét projekt ad gangen; {n} andre projektfiler blev ikke åbnet.", + "Frame the view after import": "Indram visningen efter import", + "High": "Høj", + "Import": "Importer", + "Import All": "Importer alle", + "Import Files": "Importer filer", + "Import Model": "Importer model", + "Import Recent File": "Importer seneste fil", + "Imported {name}.": "{name} er importeret.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} er importeret: {parts} dele, {triangles} trekanter.", + "Imported {name}: {parts} parts.": "{name} er importeret: {parts} dele.", + "Importing": "Importerer", + "In this file": "I denne fil", + "Inches (in)": "Tomme (in)", + "Making materials": "Opretter materialer", + "Materials": "Materialer", + "Medium": "Mellem", + "Merge into one group": "Flet til én gruppe", + "Metres (m)": "Meter (m)", + "Millimetres (mm)": "Millimeter (mm)", + "No Recent Imports": "Ingen seneste importer", + "No warnings.": "Ingen advarsler.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Intet at importere: FormShot importerer GLB-, glTF-, OBJ-, STL-, PLY-, 3MF-, FBX-, STEP- og IGES-filer.", + "One file beside it": "Én fil ved siden af", + "Opening {name} will close the open project and discard its unsaved changes.": "Hvis du åbner {name}, lukkes det åbne projekt, og dets ikke-gemte ændringer kasseres.", + "Options": "Indstillinger", + "Parts": "Dele", + "Placing in the scene": "Placerer i scenen", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Læser kildefilerne for de valgte dele (eller for alle importerede dele) igen og beholder deres materialer.", + "Reading the file": "Læser filen", + "Reading the file...": "Læser filen...", + "Recent Imports": "Seneste importer", + "Reimport": "Importer igen", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Importeret igen: {matched} opdateret, {added} nye, {hidden} skjult.", + "Send model files to FormShot and import them into the scene with options.": "Send modelfiler til FormShot, og importer dem til scenen med indstillinger.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Flere filer importeres efter hinanden. Buffere, materialer og teksturer ved siden af en model følger med.", + "Size": "Størrelse", + "Stand on the floor": "Stil på gulvet", + "Tessellating CAD surfaces": "Tessellerer CAD-overflader", + "The engine decides from the file.": "Motoren afgør det ud fra filen.", + "The engine did not start an import job": "Motoren startede ikke et importjob", + "The engine did not start in time, so the files FormShot was given were not opened.": "Motoren startede ikke i tide, så de filer, FormShot fik, blev ikke åbnet.", + "The file says it is in {unit}.": "Filen angiver, at den er i {unit}.", + "The import failed": "Importen mislykkedes", + "The import goes on; the files after it were not imported.": "Importen fortsætter; filerne efter den blev ikke importeret.", + "The import of {name} was cancelled.": "Importen af {name} blev annulleret.", + "The upload failed ({status})": "Uploadingen mislykkedes ({status})", + "The upload was cancelled": "Uploadingen blev annulleret", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Denne motor kan ikke kigge ind i en fil før import, så oversigten forbliver tom.", + "This engine cannot stop an import once it has started": "Denne motor kan ikke stoppe en import, når den først er startet", + "This engine imports in one step, so there is no progress to show or stop.": "Denne motor importerer i ét trin, så der er ingen fremdrift at vise eller stoppe.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Denne fil angiver ikke sine enheder. FormShot gættede på {unit} ud fra størrelsen; kontrollér det før importen.", + "Triangles": "Trekanter", + "Ultra": "Ultra", + "Units": "Enheder", + "Up axis": "Opadgående akse", + "Up axis in file": "Opadgående akse i filen", + "Uploading": "Uploader", + "Y is up": "Y er op", + "Z is up": "Z er op", + "centimetres": "centimeter", + "feet": "fod", + "inches": "tommer", + "metres": "meter", + "millimetres": "millimeter", + "{i} of {n}": "{i} af {n}", + "{n} files beside it": "{n} filer ved siden af", + "{n} files were not imported.": "{n} filer blev ikke importeret.", + "{n} warnings; the Scene page lists the parts.": "{n} advarsler; Scenesiden viser delene." +} diff --git a/frontend/src/i18n/modules/import/de.json b/frontend/src/i18n/modules/import/de.json new file mode 100644 index 00000000..7cb276c0 --- /dev/null +++ b/frontend/src/i18n/modules/import/de.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D-Modelle", + "Automatic": "Automatisch", + "CAD quality": "CAD-Qualität", + "Centimetres (cm)": "Zentimeter (cm)", + "Centre on the origin": "Auf den Ursprung zentrieren", + "Choose model files and import them into the scene with options.": "Wähle Modelldateien aus und importiere sie mit Optionen in die Szene.", + "Cleaning up meshes": "Meshes werden bereinigt", + "Clear Recent Imports": "Zuletzt importierte Dateien löschen", + "Could not import the file: {reason}": "Die Datei konnte nicht importiert werden: {reason}", + "Could not import {name}: {reason}": "{name} konnte nicht importiert werden: {reason}", + "Could not open {name}: {reason}": "{name} konnte nicht geöffnet werden: {reason}", + "Could not read the file: {reason}": "Die Datei konnte nicht gelesen werden: {reason}", + "Could not reimport: {reason}": "Erneutes Importieren nicht möglich: {reason}", + "Could not send the file: {reason}": "Die Datei konnte nicht gesendet werden: {reason}", + "Discard unsaved changes?": "Nicht gespeicherte Änderungen verwerfen?", + "Draft": "Entwurf", + "Drop to import into the scene": "Zum Importieren in die Szene ablegen", + "Feet (ft)": "Fuß (ft)", + "Format": "Format", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot öffnet jeweils ein Projekt; {n} weitere Projektdateien wurden nicht geöffnet.", + "Frame the view after import": "Ansicht nach dem Import einpassen", + "High": "Hoch", + "Import": "Importieren", + "Import All": "Alle importieren", + "Import Files": "Dateien importieren", + "Import Model": "Modell importieren", + "Import Recent File": "Zuletzt verwendete Datei importieren", + "Imported {name}.": "{name} importiert.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} importiert: {parts} Teile, {triangles} Dreiecke.", + "Imported {name}: {parts} parts.": "{name} importiert: {parts} Teile.", + "Importing": "Import läuft", + "In this file": "In dieser Datei", + "Inches (in)": "Zoll (in)", + "Making materials": "Materialien werden erstellt", + "Materials": "Materialien", + "Medium": "Mittel", + "Merge into one group": "In einer Gruppe zusammenführen", + "Metres (m)": "Meter (m)", + "Millimetres (mm)": "Millimeter (mm)", + "No Recent Imports": "Keine zuletzt importierten Dateien", + "No warnings.": "Keine Warnungen.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Nichts zu importieren: FormShot importiert GLB-, glTF-, OBJ-, STL-, PLY-, 3MF-, FBX-, STEP- und IGES-Dateien.", + "One file beside it": "Eine Datei daneben", + "Opening {name} will close the open project and discard its unsaved changes.": "Beim Öffnen von {name} wird das geöffnete Projekt geschlossen und seine nicht gespeicherten Änderungen gehen verloren.", + "Options": "Optionen", + "Parts": "Teile", + "Placing in the scene": "Platzierung in der Szene", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Liest die Quelldateien der ausgewählten Teile (oder aller importierten Teile) erneut ein und behält ihre Materialien.", + "Reading the file": "Datei wird gelesen", + "Reading the file...": "Datei wird gelesen ...", + "Recent Imports": "Zuletzt importiert", + "Reimport": "Erneut importieren", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Erneut importiert: {matched} aktualisiert, {added} neu, {hidden} ausgeblendet.", + "Send model files to FormShot and import them into the scene with options.": "Sende Modelldateien an FormShot und importiere sie mit Optionen in die Szene.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Mehrere Dateien werden nacheinander importiert. Puffer, Materialien und Texturen neben einem Modell gehören dazu.", + "Size": "Größe", + "Stand on the floor": "Auf den Boden stellen", + "Tessellating CAD surfaces": "CAD-Flächen werden trianguliert", + "The engine decides from the file.": "Die Engine entscheidet anhand der Datei.", + "The engine did not start an import job": "Die Engine hat keinen Importauftrag gestartet", + "The engine did not start in time, so the files FormShot was given were not opened.": "Die Engine wurde nicht rechtzeitig gestartet, daher wurden die an FormShot übergebenen Dateien nicht geöffnet.", + "The file says it is in {unit}.": "Die Datei gibt {unit} als Einheit an.", + "The import failed": "Der Import ist fehlgeschlagen", + "The import goes on; the files after it were not imported.": "Der Import läuft weiter; die nachfolgenden Dateien wurden nicht importiert.", + "The import of {name} was cancelled.": "Der Import von {name} wurde abgebrochen.", + "The upload failed ({status})": "Der Upload ist fehlgeschlagen ({status})", + "The upload was cancelled": "Der Upload wurde abgebrochen", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Diese Engine kann vor dem Import nicht in eine Datei hineinsehen, daher bleibt die Zusammenfassung leer.", + "This engine cannot stop an import once it has started": "Diese Engine kann einen gestarteten Import nicht mehr anhalten", + "This engine imports in one step, so there is no progress to show or stop.": "Diese Engine importiert in einem Schritt, daher gibt es keinen Fortschritt anzuzeigen oder zu stoppen.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Diese Datei nennt ihre Einheiten nicht. FormShot hat aus der Größe {unit} geschätzt; prüfe das vor dem Import.", + "Triangles": "Dreiecke", + "Ultra": "Ultra", + "Units": "Einheiten", + "Up axis": "Achse nach oben", + "Up axis in file": "Achse nach oben in der Datei", + "Uploading": "Upload läuft", + "Y is up": "Y zeigt nach oben", + "Z is up": "Z zeigt nach oben", + "centimetres": "Zentimeter", + "feet": "Fuß", + "inches": "Zoll", + "metres": "Meter", + "millimetres": "Millimeter", + "{i} of {n}": "{i} von {n}", + "{n} files beside it": "{n} Dateien daneben", + "{n} files were not imported.": "{n} Dateien wurden nicht importiert.", + "{n} warnings; the Scene page lists the parts.": "{n} Warnungen; die Szenenseite listet die Teile auf." +} diff --git a/frontend/src/i18n/modules/import/es-MX.json b/frontend/src/i18n/modules/import/es-MX.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/import/es-MX.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/import/es.json b/frontend/src/i18n/modules/import/es.json new file mode 100644 index 00000000..13d1a092 --- /dev/null +++ b/frontend/src/i18n/modules/import/es.json @@ -0,0 +1,90 @@ +{ + "3D models": "Modelos 3D", + "Automatic": "Automático", + "CAD quality": "Calidad CAD", + "Centimetres (cm)": "Centímetros (cm)", + "Centre on the origin": "Centrar en el origen", + "Choose model files and import them into the scene with options.": "Elige archivos de modelo e impórtalos en la escena con opciones.", + "Cleaning up meshes": "Limpiando las mallas", + "Clear Recent Imports": "Borrar importaciones recientes", + "Could not import the file: {reason}": "No se pudo importar el archivo: {reason}", + "Could not import {name}: {reason}": "No se pudo importar {name}: {reason}", + "Could not open {name}: {reason}": "No se pudo abrir {name}: {reason}", + "Could not read the file: {reason}": "No se pudo leer el archivo: {reason}", + "Could not reimport: {reason}": "No se pudo reimportar: {reason}", + "Could not send the file: {reason}": "No se pudo enviar el archivo: {reason}", + "Discard unsaved changes?": "¿Descartar los cambios sin guardar?", + "Draft": "Borrador", + "Drop to import into the scene": "Suelta para importar en la escena", + "Feet (ft)": "Pies (ft)", + "Format": "Formato", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot abre un solo proyecto a la vez; {n} archivos de proyecto más se quedaron sin abrir.", + "Frame the view after import": "Encuadrar la vista tras importar", + "High": "Alta", + "Import": "Importar", + "Import All": "Importar todo", + "Import Files": "Importar archivos", + "Import Model": "Importar modelo", + "Import Recent File": "Importar archivo reciente", + "Imported {name}.": "Se importó {name}.", + "Imported {name}: {parts} parts, {triangles} triangles.": "Se importó {name}: {parts} piezas, {triangles} triángulos.", + "Imported {name}: {parts} parts.": "Se importó {name}: {parts} piezas.", + "Importing": "Importando", + "In this file": "En este archivo", + "Inches (in)": "Pulgadas (in)", + "Making materials": "Creando los materiales", + "Materials": "Materiales", + "Medium": "Media", + "Merge into one group": "Combinar en un solo grupo", + "Metres (m)": "Metros (m)", + "Millimetres (mm)": "Milímetros (mm)", + "No Recent Imports": "Sin importaciones recientes", + "No warnings.": "Sin advertencias.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Nada que importar: FormShot importa archivos GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP e IGES.", + "One file beside it": "Un archivo al lado", + "Opening {name} will close the open project and discard its unsaved changes.": "Al abrir {name} se cerrará el proyecto abierto y se descartarán sus cambios sin guardar.", + "Options": "Opciones", + "Parts": "Piezas", + "Placing in the scene": "Colocando en la escena", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Vuelve a leer los archivos de origen de las piezas seleccionadas (o de todas las importadas) conservando sus materiales.", + "Reading the file": "Leyendo el archivo", + "Reading the file...": "Leyendo el archivo...", + "Recent Imports": "Importaciones recientes", + "Reimport": "Reimportar", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Reimportado: {matched} actualizadas, {added} nuevas, {hidden} ocultas.", + "Send model files to FormShot and import them into the scene with options.": "Envía archivos de modelo a FormShot e impórtalos en la escena con opciones.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Varios archivos se importan uno tras otro. Los búferes, materiales y texturas junto a un modelo se importan con él.", + "Size": "Tamaño", + "Stand on the floor": "Apoyar en el suelo", + "Tessellating CAD surfaces": "Teselando las superficies CAD", + "The engine decides from the file.": "El motor lo decide a partir del archivo.", + "The engine did not start an import job": "El motor no inició ninguna tarea de importación", + "The engine did not start in time, so the files FormShot was given were not opened.": "El motor no arrancó a tiempo, así que los archivos entregados a FormShot no se abrieron.", + "The file says it is in {unit}.": "El archivo indica que está en {unit}.", + "The import failed": "La importación falló", + "The import goes on; the files after it were not imported.": "La importación continúa; los archivos siguientes no se importaron.", + "The import of {name} was cancelled.": "Se canceló la importación de {name}.", + "The upload failed ({status})": "La subida falló ({status})", + "The upload was cancelled": "Se canceló la subida", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Este motor no puede mirar dentro de un archivo antes de importarlo, así que el resumen queda vacío.", + "This engine cannot stop an import once it has started": "Este motor no puede detener una importación una vez iniciada", + "This engine imports in one step, so there is no progress to show or stop.": "Este motor importa en un solo paso, así que no hay progreso que mostrar ni detener.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Este archivo no indica sus unidades. FormShot supuso {unit} por su tamaño; compruébalo antes de importar.", + "Triangles": "Triángulos", + "Ultra": "Ultra", + "Units": "Unidades", + "Up axis": "Eje vertical", + "Up axis in file": "Eje vertical en el archivo", + "Uploading": "Subiendo", + "Y is up": "Y es hacia arriba", + "Z is up": "Z es hacia arriba", + "centimetres": "centímetros", + "feet": "pies", + "inches": "pulgadas", + "metres": "metros", + "millimetres": "milímetros", + "{i} of {n}": "{i} de {n}", + "{n} files beside it": "{n} archivos al lado", + "{n} files were not imported.": "{n} archivos no se importaron.", + "{n} warnings; the Scene page lists the parts.": "{n} advertencias; la página de escena enumera las piezas." +} diff --git a/frontend/src/i18n/modules/import/fi.json b/frontend/src/i18n/modules/import/fi.json new file mode 100644 index 00000000..ec02e146 --- /dev/null +++ b/frontend/src/i18n/modules/import/fi.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D-mallit", + "Automatic": "Automaattinen", + "CAD quality": "CAD-laatu", + "Centimetres (cm)": "Senttimetrit (cm)", + "Centre on the origin": "Keskitä origoon", + "Choose model files and import them into the scene with options.": "Valitse mallitiedostot ja tuo ne kohtaukseen asetusten kanssa.", + "Cleaning up meshes": "Siivotaan verkkoja", + "Clear Recent Imports": "Tyhjennä viimeisimmät tuonnit", + "Could not import the file: {reason}": "Tiedostoa ei voitu tuoda: {reason}", + "Could not import {name}: {reason}": "Tiedostoa {name} ei voitu tuoda: {reason}", + "Could not open {name}: {reason}": "Tiedostoa {name} ei voitu avata: {reason}", + "Could not read the file: {reason}": "Tiedostoa ei voitu lukea: {reason}", + "Could not reimport: {reason}": "Uudelleentuonti epäonnistui: {reason}", + "Could not send the file: {reason}": "Tiedostoa ei voitu lähettää: {reason}", + "Discard unsaved changes?": "Hylätäänkö tallentamattomat muutokset?", + "Draft": "Luonnos", + "Drop to import into the scene": "Pudota tuodaksesi kohtaukseen", + "Feet (ft)": "Jalat (ft)", + "Format": "Muoto", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot avaa yhden projektin kerrallaan; {n} muuta projektitiedostoa jätettiin avaamatta.", + "Frame the view after import": "Rajaa näkymä tuonnin jälkeen", + "High": "Korkea", + "Import": "Tuo", + "Import All": "Tuo kaikki", + "Import Files": "Tuo tiedostot", + "Import Model": "Tuo malli", + "Import Recent File": "Tuo viimeaikainen tiedosto", + "Imported {name}.": "{name} tuotu.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} tuotu: {parts} osaa, {triangles} kolmiota.", + "Imported {name}: {parts} parts.": "{name} tuotu: {parts} osaa.", + "Importing": "Tuodaan", + "In this file": "Tässä tiedostossa", + "Inches (in)": "Tuumat (in)", + "Making materials": "Luodaan materiaaleja", + "Materials": "Materiaalit", + "Medium": "Keskitaso", + "Merge into one group": "Yhdistä yhdeksi ryhmäksi", + "Metres (m)": "Metrit (m)", + "Millimetres (mm)": "Millimetrit (mm)", + "No Recent Imports": "Ei viimeisimpiä tuonteja", + "No warnings.": "Ei varoituksia.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Ei tuotavaa: FormShot tuo GLB-, glTF-, OBJ-, STL-, PLY-, 3MF-, FBX-, STEP- ja IGES-tiedostoja.", + "One file beside it": "Yksi tiedosto sen vieressä", + "Opening {name} will close the open project and discard its unsaved changes.": "Kohteen {name} avaaminen sulkee avoimen projektin ja hylkää sen tallentamattomat muutokset.", + "Options": "Valinnat", + "Parts": "Osat", + "Placing in the scene": "Sijoitetaan kohtaukseen", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Lue valittujen osien (tai kaikkien tuotujen osien) lähdetiedostot uudelleen ja säilytä niiden materiaalit.", + "Reading the file": "Luetaan tiedostoa", + "Reading the file...": "Luetaan tiedostoa...", + "Recent Imports": "Viimeisimmät tuonnit", + "Reimport": "Tuo uudelleen", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Tuotu uudelleen: päivitetty {matched}, uusia {added}, piilotettu {hidden}.", + "Send model files to FormShot and import them into the scene with options.": "Lähetä mallitiedostot FormShotiin ja tuo ne kohtaukseen asetusten kanssa.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Useat tiedostot tuodaan peräkkäin. Mallin vieressä olevat puskurit, materiaalit ja tekstuurit tulevat sen mukana.", + "Size": "Koko", + "Stand on the floor": "Aseta lattialle", + "Tessellating CAD surfaces": "Tesseloidaan CAD-pintoja", + "The engine decides from the file.": "Moottori päättää tiedoston perusteella.", + "The engine did not start an import job": "Moottori ei käynnistänyt tuontityötä", + "The engine did not start in time, so the files FormShot was given were not opened.": "Moottori ei käynnistynyt ajoissa, joten FormShotille annettuja tiedostoja ei avattu.", + "The file says it is in {unit}.": "Tiedoston ilmoittama yksikkö: {unit}.", + "The import failed": "Tuonti epäonnistui", + "The import goes on; the files after it were not imported.": "Tuonti jatkuu; sen jälkeisiä tiedostoja ei tuotu.", + "The import of {name} was cancelled.": "Kohteen {name} tuonti peruttiin.", + "The upload failed ({status})": "Lähetys epäonnistui ({status})", + "The upload was cancelled": "Lähetys peruttiin", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Tämä moottori ei voi katsoa tiedoston sisään ennen tuontia, joten yhteenveto jää tyhjäksi.", + "This engine cannot stop an import once it has started": "Tämä moottori ei voi pysäyttää tuontia sen alettua", + "This engine imports in one step, so there is no progress to show or stop.": "Tämä moottori tuo yhdessä vaiheessa, joten edistymistä ei voi näyttää eikä pysäyttää.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Tiedosto ei kerro yksikköjään. FormShotin koon perusteella arvaama yksikkö on {unit}; tarkista se ennen tuontia.", + "Triangles": "Kolmiot", + "Ultra": "Ultra", + "Units": "Yksiköt", + "Up axis": "Ylöspäin osoittava akseli", + "Up axis in file": "Ylöspäin osoittava akseli tiedostossa", + "Uploading": "Lähetetään", + "Y is up": "Y on ylös", + "Z is up": "Z on ylös", + "centimetres": "senttimetrit", + "feet": "jalat", + "inches": "tuumat", + "metres": "metrit", + "millimetres": "millimetrit", + "{i} of {n}": "{i} / {n}", + "{n} files beside it": "{n} tiedostoa sen vieressä", + "{n} files were not imported.": "{n} tiedostoa jäi tuomatta.", + "{n} warnings; the Scene page lists the parts.": "{n} varoitusta; Kohtaussivu luettelee osat." +} diff --git a/frontend/src/i18n/modules/import/fr-CA.json b/frontend/src/i18n/modules/import/fr-CA.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/import/fr-CA.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/import/fr.json b/frontend/src/i18n/modules/import/fr.json new file mode 100644 index 00000000..7d66f0c9 --- /dev/null +++ b/frontend/src/i18n/modules/import/fr.json @@ -0,0 +1,90 @@ +{ + "3D models": "Modèles 3D", + "Automatic": "Automatique", + "CAD quality": "Qualité CAO", + "Centimetres (cm)": "Centimètres (cm)", + "Centre on the origin": "Centrer sur l'origine", + "Choose model files and import them into the scene with options.": "Choisissez des fichiers de modèle et importez-les dans la scène avec des options.", + "Cleaning up meshes": "Nettoyage des maillages", + "Clear Recent Imports": "Effacer les imports récents", + "Could not import the file: {reason}": "Impossible d'importer le fichier : {reason}", + "Could not import {name}: {reason}": "Impossible d'importer {name} : {reason}", + "Could not open {name}: {reason}": "Impossible d'ouvrir {name} : {reason}", + "Could not read the file: {reason}": "Impossible de lire le fichier : {reason}", + "Could not reimport: {reason}": "Impossible de réimporter : {reason}", + "Could not send the file: {reason}": "Impossible d'envoyer le fichier : {reason}", + "Discard unsaved changes?": "Abandonner les modifications non enregistrées ?", + "Draft": "Brouillon", + "Drop to import into the scene": "Déposer pour importer dans la scène", + "Feet (ft)": "Pieds (ft)", + "Format": "Format", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot ouvre un seul projet à la fois ; {n} autres fichiers de projet n'ont pas été ouverts.", + "Frame the view after import": "Cadrer la vue après l'import", + "High": "Élevée", + "Import": "Importer", + "Import All": "Tout importer", + "Import Files": "Importer des fichiers", + "Import Model": "Importer un modèle", + "Import Recent File": "Importer un fichier récent", + "Imported {name}.": "{name} importé.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} importé : {parts} pièces, {triangles} triangles.", + "Imported {name}: {parts} parts.": "{name} importé : {parts} pièces.", + "Importing": "Import en cours", + "In this file": "Dans ce fichier", + "Inches (in)": "Pouces (in)", + "Making materials": "Création des matériaux", + "Materials": "Matériaux", + "Medium": "Moyenne", + "Merge into one group": "Fusionner en un seul groupe", + "Metres (m)": "Mètres (m)", + "Millimetres (mm)": "Millimètres (mm)", + "No Recent Imports": "Aucun import récent", + "No warnings.": "Aucun avertissement.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Rien à importer : FormShot importe les fichiers GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP et IGES.", + "One file beside it": "Un fichier à côté", + "Opening {name} will close the open project and discard its unsaved changes.": "L'ouverture de {name} fermera le projet ouvert et abandonnera ses modifications non enregistrées.", + "Options": "Options", + "Parts": "Pièces", + "Placing in the scene": "Placement dans la scène", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Relit les fichiers source des pièces sélectionnées (ou de toutes les pièces importées) en conservant leurs matériaux.", + "Reading the file": "Lecture du fichier", + "Reading the file...": "Lecture du fichier...", + "Recent Imports": "Imports récents", + "Reimport": "Réimporter", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Réimporté : {matched} mis à jour, {added} nouveaux, {hidden} masqués.", + "Send model files to FormShot and import them into the scene with options.": "Envoyez des fichiers de modèle à FormShot et importez-les dans la scène avec des options.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Plusieurs fichiers sont importés l'un après l'autre. Les tampons, matériaux et textures situés à côté d'un modèle l'accompagnent.", + "Size": "Taille", + "Stand on the floor": "Poser sur le sol", + "Tessellating CAD surfaces": "Tessellation des surfaces CAO", + "The engine decides from the file.": "Le moteur décide à partir du fichier.", + "The engine did not start an import job": "Le moteur n'a pas lancé de tâche d'import", + "The engine did not start in time, so the files FormShot was given were not opened.": "Le moteur n'a pas démarré à temps, les fichiers transmis à FormShot n'ont donc pas été ouverts.", + "The file says it is in {unit}.": "Le fichier indique être en {unit}.", + "The import failed": "L'import a échoué", + "The import goes on; the files after it were not imported.": "L'import se poursuit ; les fichiers suivants n'ont pas été importés.", + "The import of {name} was cancelled.": "L'import de {name} a été annulé.", + "The upload failed ({status})": "Le téléversement a échoué ({status})", + "The upload was cancelled": "Le téléversement a été annulé", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Ce moteur ne peut pas examiner un fichier avant de l'importer, le résumé reste donc vide.", + "This engine cannot stop an import once it has started": "Ce moteur ne peut pas arrêter un import une fois commencé", + "This engine imports in one step, so there is no progress to show or stop.": "Ce moteur importe en une seule étape, il n'y a donc aucune progression à afficher ni à arrêter.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Ce fichier n'indique pas ses unités. FormShot a estimé {unit} d'après sa taille ; vérifiez-le avant d'importer.", + "Triangles": "Triangles", + "Ultra": "Ultra", + "Units": "Unités", + "Up axis": "Axe vertical", + "Up axis in file": "Axe vertical dans le fichier", + "Uploading": "Téléversement en cours", + "Y is up": "Y est vers le haut", + "Z is up": "Z est vers le haut", + "centimetres": "centimètres", + "feet": "pieds", + "inches": "pouces", + "metres": "mètres", + "millimetres": "millimètres", + "{i} of {n}": "{i} sur {n}", + "{n} files beside it": "{n} fichiers à côté", + "{n} files were not imported.": "{n} fichiers n'ont pas été importés.", + "{n} warnings; the Scene page lists the parts.": "{n} avertissements ; la page Scène liste les pièces." +} diff --git a/frontend/src/i18n/modules/import/hu.json b/frontend/src/i18n/modules/import/hu.json new file mode 100644 index 00000000..ea519006 --- /dev/null +++ b/frontend/src/i18n/modules/import/hu.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D modellek", + "Automatic": "Automatikus", + "CAD quality": "CAD-minőség", + "Centimetres (cm)": "Centiméter (cm)", + "Centre on the origin": "Középre az origóba", + "Choose model files and import them into the scene with options.": "Válassza ki a modellfájlokat, és importálja őket a jelenetbe a beállítások megadásával.", + "Cleaning up meshes": "Hálók tisztítása", + "Clear Recent Imports": "Legutóbbi importálások törlése", + "Could not import the file: {reason}": "A fájlt nem sikerült importálni: {reason}", + "Could not import {name}: {reason}": "A(z) {name} importálása nem sikerült: {reason}", + "Could not open {name}: {reason}": "A(z) {name} megnyitása nem sikerült: {reason}", + "Could not read the file: {reason}": "A fájlt nem sikerült beolvasni: {reason}", + "Could not reimport: {reason}": "Az újraimportálás nem sikerült: {reason}", + "Could not send the file: {reason}": "A fájlt nem sikerült elküldeni: {reason}", + "Discard unsaved changes?": "Elveti a nem mentett módosításokat?", + "Draft": "Vázlat", + "Drop to import into the scene": "Engedje el az importáláshoz a jelenetbe", + "Feet (ft)": "Láb (ft)", + "Format": "Formátum", + "FormShot opens one project at a time; {n} other project files were left unopened.": "A FormShot egyszerre egy projektet nyit meg; {n} további projektfájl nyitatlan maradt.", + "Frame the view after import": "Nézet kadrírozása importálás után", + "High": "Magas", + "Import": "Importálás", + "Import All": "Összes importálása", + "Import Files": "Fájlok importálása", + "Import Model": "Modell importálása", + "Import Recent File": "Legutóbbi fájl importálása", + "Imported {name}.": "Importálva: {name}.", + "Imported {name}: {parts} parts, {triangles} triangles.": "Importálva: {name}, {parts} alkatrész, {triangles} háromszög.", + "Imported {name}: {parts} parts.": "Importálva: {name}, {parts} alkatrész.", + "Importing": "Importálás", + "In this file": "Ebben a fájlban", + "Inches (in)": "Hüvelyk (in)", + "Making materials": "Anyagok létrehozása", + "Materials": "Anyagok", + "Medium": "Közepes", + "Merge into one group": "Egyesítés egy csoportba", + "Metres (m)": "Méter (m)", + "Millimetres (mm)": "Milliméter (mm)", + "No Recent Imports": "Nincsenek legutóbbi importálások", + "No warnings.": "Nincsenek figyelmeztetések.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Nincs mit importálni: a FormShot GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP és IGES fájlokat importál.", + "One file beside it": "Egy fájl mellette", + "Opening {name} will close the open project and discard its unsaved changes.": "A(z) {name} megnyitása bezárja a megnyitott projektet, és elveti annak nem mentett módosításait.", + "Options": "Opciók", + "Parts": "Alkatrészek", + "Placing in the scene": "Elhelyezés a jelenetben", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "A kijelölt (vagy az összes importált) alkatrész forrásfájljainak újraolvasása az anyagok megtartásával.", + "Reading the file": "Fájl beolvasása", + "Reading the file...": "Fájl beolvasása...", + "Recent Imports": "Legutóbbi importálások", + "Reimport": "Újraimportálás", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Újraimportálva: frissítve {matched}, új {added}, elrejtve {hidden}.", + "Send model files to FormShot and import them into the scene with options.": "Küldje el a modellfájlokat a FormShotnak, és importálja őket a jelenetbe a beállítások megadásával.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Több fájl importálása egymás után történik. A modell melletti pufferek, anyagok és textúrák vele együtt kerülnek be.", + "Size": "Méret", + "Stand on the floor": "Padlóra állítás", + "Tessellating CAD surfaces": "CAD-felületek tesszellálása", + "The engine decides from the file.": "A motor a fájl alapján dönt.", + "The engine did not start an import job": "A motor nem indított importfeladatot", + "The engine did not start in time, so the files FormShot was given were not opened.": "A motor nem indult el időben, ezért a FormShotnak átadott fájlok nem nyíltak meg.", + "The file says it is in {unit}.": "A fájl szerint a mértékegység: {unit}.", + "The import failed": "Az importálás sikertelen", + "The import goes on; the files after it were not imported.": "Az importálás folytatódik; a következő fájlok nem lettek importálva.", + "The import of {name} was cancelled.": "A(z) {name} importálása megszakadt.", + "The upload failed ({status})": "A feltöltés sikertelen ({status})", + "The upload was cancelled": "A feltöltés megszakadt", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Ez a motor importálás előtt nem tud belenézni a fájlba, ezért az összegzés üres marad.", + "This engine cannot stop an import once it has started": "Ez a motor nem tudja leállítani az importálást, ha az már elindult", + "This engine imports in one step, so there is no progress to show or stop.": "Ez a motor egy lépésben importál, ezért nincs megjeleníthető vagy leállítható folyamat.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "A fájl nem adja meg a mértékegységét. A FormShot a méret alapján a következőt találta ki: {unit}; importálás előtt ellenőrizze.", + "Triangles": "Háromszögek", + "Ultra": "Ultra", + "Units": "Mértékegységek", + "Up axis": "Felfelé mutató tengely", + "Up axis in file": "Felfelé mutató tengely a fájlban", + "Uploading": "Feltöltés", + "Y is up": "Az Y felfelé mutat", + "Z is up": "A Z felfelé mutat", + "centimetres": "centiméter", + "feet": "láb", + "inches": "hüvelyk", + "metres": "méter", + "millimetres": "milliméter", + "{i} of {n}": "{i} / {n}", + "{n} files beside it": "{n} fájl mellette", + "{n} files were not imported.": "{n} fájl nem lett importálva.", + "{n} warnings; the Scene page lists the parts.": "{n} figyelmeztetés; az alkatrészeket a Jelenet oldal sorolja fel." +} diff --git a/frontend/src/i18n/modules/import/id.json b/frontend/src/i18n/modules/import/id.json new file mode 100644 index 00000000..7830fe30 --- /dev/null +++ b/frontend/src/i18n/modules/import/id.json @@ -0,0 +1,90 @@ +{ + "3D models": "Model 3D", + "Automatic": "Otomatis", + "CAD quality": "Kualitas CAD", + "Centimetres (cm)": "Sentimeter (cm)", + "Centre on the origin": "Pusatkan pada titik asal", + "Choose model files and import them into the scene with options.": "Pilih file model lalu impor ke scene dengan opsi.", + "Cleaning up meshes": "Membersihkan mesh", + "Clear Recent Imports": "Hapus Impor Terbaru", + "Could not import the file: {reason}": "Tidak dapat mengimpor file: {reason}", + "Could not import {name}: {reason}": "Tidak dapat mengimpor {name}: {reason}", + "Could not open {name}: {reason}": "Tidak dapat membuka {name}: {reason}", + "Could not read the file: {reason}": "Tidak dapat membaca file: {reason}", + "Could not reimport: {reason}": "Tidak dapat mengimpor ulang: {reason}", + "Could not send the file: {reason}": "Tidak dapat mengirim file: {reason}", + "Discard unsaved changes?": "Buang perubahan yang belum disimpan?", + "Draft": "Draf", + "Drop to import into the scene": "Lepas untuk mengimpor ke scene", + "Feet (ft)": "Kaki (ft)", + "Format": "Format", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot membuka satu proyek dalam satu waktu; {n} file proyek lain tidak dibuka.", + "Frame the view after import": "Bingkai tampilan setelah impor", + "High": "Tinggi", + "Import": "Impor", + "Import All": "Impor Semua", + "Import Files": "Impor File", + "Import Model": "Impor Model", + "Import Recent File": "Impor File Terbaru", + "Imported {name}.": "{name} diimpor.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} diimpor: {parts} bagian, {triangles} segitiga.", + "Imported {name}: {parts} parts.": "{name} diimpor: {parts} bagian.", + "Importing": "Mengimpor", + "In this file": "Dalam file ini", + "Inches (in)": "Inci (in)", + "Making materials": "Membuat material", + "Materials": "Material", + "Medium": "Sedang", + "Merge into one group": "Gabungkan menjadi satu grup", + "Metres (m)": "Meter (m)", + "Millimetres (mm)": "Milimeter (mm)", + "No Recent Imports": "Tidak Ada Impor Terbaru", + "No warnings.": "Tidak ada peringatan.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Tidak ada yang diimpor: FormShot mengimpor file GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP, dan IGES.", + "One file beside it": "Satu file di sebelahnya", + "Opening {name} will close the open project and discard its unsaved changes.": "Membuka {name} akan menutup proyek yang terbuka dan membuang perubahannya yang belum disimpan.", + "Options": "Opsi", + "Parts": "Bagian", + "Placing in the scene": "Menempatkan di scene", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Baca ulang file sumber dari bagian yang dipilih (atau dari semua bagian yang diimpor), dengan mempertahankan materialnya.", + "Reading the file": "Membaca file", + "Reading the file...": "Membaca file...", + "Recent Imports": "Impor Terbaru", + "Reimport": "Impor Ulang", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Diimpor ulang: {matched} diperbarui, {added} baru, {hidden} disembunyikan.", + "Send model files to FormShot and import them into the scene with options.": "Kirim file model ke FormShot lalu impor ke scene dengan opsi.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Beberapa file diimpor satu per satu. Buffer, material, dan tekstur di sebelah model ikut terbawa.", + "Size": "Ukuran", + "Stand on the floor": "Letakkan di lantai", + "Tessellating CAD surfaces": "Memecah permukaan CAD menjadi segitiga", + "The engine decides from the file.": "Mesin menentukan dari file.", + "The engine did not start an import job": "Mesin tidak memulai tugas impor", + "The engine did not start in time, so the files FormShot was given were not opened.": "Mesin tidak dimulai tepat waktu, sehingga file yang diberikan ke FormShot tidak dibuka.", + "The file says it is in {unit}.": "File menyatakan satuannya {unit}.", + "The import failed": "Impor gagal", + "The import goes on; the files after it were not imported.": "Impor berlanjut; file setelahnya tidak diimpor.", + "The import of {name} was cancelled.": "Impor {name} dibatalkan.", + "The upload failed ({status})": "Unggahan gagal ({status})", + "The upload was cancelled": "Unggahan dibatalkan", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Mesin ini tidak dapat melihat isi file sebelum diimpor, sehingga ringkasan tetap kosong.", + "This engine cannot stop an import once it has started": "Mesin ini tidak dapat menghentikan impor yang sudah dimulai", + "This engine imports in one step, so there is no progress to show or stop.": "Mesin ini mengimpor dalam satu langkah, sehingga tidak ada progres untuk ditampilkan atau dihentikan.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "File ini tidak menyebutkan satuannya. FormShot menebak {unit} dari ukurannya; periksa sebelum mengimpor.", + "Triangles": "Segitiga", + "Ultra": "Ultra", + "Units": "Satuan", + "Up axis": "Sumbu atas", + "Up axis in file": "Sumbu atas dalam file", + "Uploading": "Mengunggah", + "Y is up": "Y adalah atas", + "Z is up": "Z adalah atas", + "centimetres": "sentimeter", + "feet": "kaki", + "inches": "inci", + "metres": "meter", + "millimetres": "milimeter", + "{i} of {n}": "{i} dari {n}", + "{n} files beside it": "{n} file di sebelahnya", + "{n} files were not imported.": "{n} file tidak diimpor.", + "{n} warnings; the Scene page lists the parts.": "{n} peringatan; halaman Scene mencantumkan bagian-bagiannya." +} diff --git a/frontend/src/i18n/modules/import/it.json b/frontend/src/i18n/modules/import/it.json new file mode 100644 index 00000000..f7f54c58 --- /dev/null +++ b/frontend/src/i18n/modules/import/it.json @@ -0,0 +1,90 @@ +{ + "3D models": "Modelli 3D", + "Automatic": "Automatico", + "CAD quality": "Qualità CAD", + "Centimetres (cm)": "Centimetri (cm)", + "Centre on the origin": "Centra sull'origine", + "Choose model files and import them into the scene with options.": "Scegli i file dei modelli e importali nella scena con le opzioni.", + "Cleaning up meshes": "Pulizia delle mesh", + "Clear Recent Imports": "Cancella importazioni recenti", + "Could not import the file: {reason}": "Impossibile importare il file: {reason}", + "Could not import {name}: {reason}": "Impossibile importare {name}: {reason}", + "Could not open {name}: {reason}": "Impossibile aprire {name}: {reason}", + "Could not read the file: {reason}": "Impossibile leggere il file: {reason}", + "Could not reimport: {reason}": "Impossibile reimportare: {reason}", + "Could not send the file: {reason}": "Impossibile inviare il file: {reason}", + "Discard unsaved changes?": "Scartare le modifiche non salvate?", + "Draft": "Bozza", + "Drop to import into the scene": "Rilascia per importare nella scena", + "Feet (ft)": "Piedi (ft)", + "Format": "Formato", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot apre un solo progetto alla volta; {n} altri file di progetto non sono stati aperti.", + "Frame the view after import": "Inquadra la vista dopo l'importazione", + "High": "Alta", + "Import": "Importa", + "Import All": "Importa tutto", + "Import Files": "Importa file", + "Import Model": "Importa modello", + "Import Recent File": "Importa file recente", + "Imported {name}.": "{name} importato.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} importato: {parts} parti, {triangles} triangoli.", + "Imported {name}: {parts} parts.": "{name} importato: {parts} parti.", + "Importing": "Importazione in corso", + "In this file": "In questo file", + "Inches (in)": "Pollici (in)", + "Making materials": "Creazione dei materiali", + "Materials": "Materiali", + "Medium": "Media", + "Merge into one group": "Unisci in un solo gruppo", + "Metres (m)": "Metri (m)", + "Millimetres (mm)": "Millimetri (mm)", + "No Recent Imports": "Nessuna importazione recente", + "No warnings.": "Nessun avviso.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Niente da importare: FormShot importa file GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP e IGES.", + "One file beside it": "Un file accanto", + "Opening {name} will close the open project and discard its unsaved changes.": "Aprendo {name} verrà chiuso il progetto aperto e le sue modifiche non salvate andranno perse.", + "Options": "Opzioni", + "Parts": "Parti", + "Placing in the scene": "Posizionamento nella scena", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Rilegge i file sorgente delle parti selezionate (o di tutte le parti importate) mantenendone i materiali.", + "Reading the file": "Lettura del file", + "Reading the file...": "Lettura del file...", + "Recent Imports": "Importazioni recenti", + "Reimport": "Reimporta", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Reimportato: {matched} aggiornati, {added} nuovi, {hidden} nascosti.", + "Send model files to FormShot and import them into the scene with options.": "Invia i file dei modelli a FormShot e importali nella scena con le opzioni.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Più file vengono importati uno dopo l'altro. Buffer, materiali e texture accanto a un modello vengono importati con esso.", + "Size": "Dimensione", + "Stand on the floor": "Appoggia sul piano", + "Tessellating CAD surfaces": "Tassellazione delle superfici CAD", + "The engine decides from the file.": "Il motore decide in base al file.", + "The engine did not start an import job": "Il motore non ha avviato un processo di importazione", + "The engine did not start in time, so the files FormShot was given were not opened.": "Il motore non si è avviato in tempo, quindi i file passati a FormShot non sono stati aperti.", + "The file says it is in {unit}.": "Il file dichiara di essere in {unit}.", + "The import failed": "L'importazione non è riuscita", + "The import goes on; the files after it were not imported.": "L'importazione prosegue; i file successivi non sono stati importati.", + "The import of {name} was cancelled.": "L'importazione di {name} è stata annullata.", + "The upload failed ({status})": "Il caricamento non è riuscito ({status})", + "The upload was cancelled": "Il caricamento è stato annullato", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Questo motore non può guardare dentro un file prima di importarlo, quindi il riepilogo resta vuoto.", + "This engine cannot stop an import once it has started": "Questo motore non può interrompere un'importazione già avviata", + "This engine imports in one step, so there is no progress to show or stop.": "Questo motore importa in un unico passaggio, quindi non c'è alcun avanzamento da mostrare o interrompere.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Questo file non indica le sue unità. FormShot ha ipotizzato {unit} dalle dimensioni; controlla prima di importare.", + "Triangles": "Triangoli", + "Ultra": "Ultra", + "Units": "Unità", + "Up axis": "Asse verticale", + "Up axis in file": "Asse verticale nel file", + "Uploading": "Caricamento in corso", + "Y is up": "Y è verso l'alto", + "Z is up": "Z è verso l'alto", + "centimetres": "centimetri", + "feet": "piedi", + "inches": "pollici", + "metres": "metri", + "millimetres": "millimetri", + "{i} of {n}": "{i} di {n}", + "{n} files beside it": "{n} file accanto", + "{n} files were not imported.": "{n} file non sono stati importati.", + "{n} warnings; the Scene page lists the parts.": "{n} avvisi; la pagina Scena elenca le parti." +} diff --git a/frontend/src/i18n/modules/import/ja.json b/frontend/src/i18n/modules/import/ja.json new file mode 100644 index 00000000..666b4602 --- /dev/null +++ b/frontend/src/i18n/modules/import/ja.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D モデル", + "Automatic": "自動", + "CAD quality": "CAD 品質", + "Centimetres (cm)": "センチメートル (cm)", + "Centre on the origin": "原点を中心にする", + "Choose model files and import them into the scene with options.": "モデルファイルを選び、オプションを指定してシーンに読み込みます。", + "Cleaning up meshes": "メッシュを整理中", + "Clear Recent Imports": "最近の読み込みを消去", + "Could not import the file: {reason}": "ファイルを読み込めませんでした: {reason}", + "Could not import {name}: {reason}": "{name} を読み込めませんでした: {reason}", + "Could not open {name}: {reason}": "{name} を開けませんでした: {reason}", + "Could not read the file: {reason}": "ファイルを読み取れませんでした: {reason}", + "Could not reimport: {reason}": "再読み込みできませんでした: {reason}", + "Could not send the file: {reason}": "ファイルを送信できませんでした: {reason}", + "Discard unsaved changes?": "未保存の変更を破棄しますか?", + "Draft": "ドラフト", + "Drop to import into the scene": "ドロップしてシーンに読み込む", + "Feet (ft)": "フィート (ft)", + "Format": "フォーマット", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot では一度に 1 つのプロジェクトしか開けません。ほかの {n} 個のプロジェクトファイルは開かれませんでした。", + "Frame the view after import": "読み込み後にビューを合わせる", + "High": "高", + "Import": "読み込む", + "Import All": "すべて読み込む", + "Import Files": "ファイルを読み込む", + "Import Model": "モデルを読み込む", + "Import Recent File": "最近読み込んだファイルを読み込む", + "Imported {name}.": "{name} を読み込みました。", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} を読み込みました: {parts} 個のパーツ、{triangles} 個の三角形。", + "Imported {name}: {parts} parts.": "{name} を読み込みました: {parts} 個のパーツ。", + "Importing": "読み込み中", + "In this file": "このファイル内", + "Inches (in)": "インチ (in)", + "Making materials": "マテリアルを作成中", + "Materials": "マテリアル", + "Medium": "中", + "Merge into one group": "1 つのグループにまとめる", + "Metres (m)": "メートル (m)", + "Millimetres (mm)": "ミリメートル (mm)", + "No Recent Imports": "最近の読み込みはありません", + "No warnings.": "警告はありません。", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "読み込むものがありません。FormShot は GLB、glTF、OBJ、STL、PLY、3MF、FBX、STEP、IGES ファイルを読み込めます。", + "One file beside it": "隣にある 1 個のファイル", + "Opening {name} will close the open project and discard its unsaved changes.": "{name} を開くと、現在開いているプロジェクトが閉じ、未保存の変更は破棄されます。", + "Options": "オプション", + "Parts": "パーツ", + "Placing in the scene": "シーンに配置中", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "選択したパーツ (選択がなければ読み込んだすべてのパーツ) の元ファイルを、マテリアルを保ったまま読み直します。", + "Reading the file": "ファイルを読み取り中", + "Reading the file...": "ファイルを読み取り中...", + "Recent Imports": "最近の読み込み", + "Reimport": "再読み込み", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "再読み込み完了: 更新 {matched}、新規 {added}、非表示 {hidden}。", + "Send model files to FormShot and import them into the scene with options.": "モデルファイルを FormShot に送り、オプションを指定してシーンに読み込みます。", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "複数のファイルは順番に読み込まれます。モデルの隣にあるバッファ、マテリアル、テクスチャも一緒に読み込まれます。", + "Size": "サイズ", + "Stand on the floor": "床に置く", + "Tessellating CAD surfaces": "CAD サーフェスをテッセレート中", + "The engine decides from the file.": "エンジンがファイルから判断します。", + "The engine did not start an import job": "エンジンが読み込みジョブを開始しませんでした", + "The engine did not start in time, so the files FormShot was given were not opened.": "エンジンが時間内に起動しなかったため、FormShot に渡されたファイルは開かれませんでした。", + "The file says it is in {unit}.": "ファイルの単位は {unit} と記されています。", + "The import failed": "読み込みに失敗しました", + "The import goes on; the files after it were not imported.": "読み込みは続行されます。この後のファイルは読み込まれませんでした。", + "The import of {name} was cancelled.": "{name} の読み込みはキャンセルされました。", + "The upload failed ({status})": "アップロードに失敗しました ({status})", + "The upload was cancelled": "アップロードはキャンセルされました", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "このエンジンは読み込む前にファイルの中身を調べられないため、概要は空のままです。", + "This engine cannot stop an import once it has started": "このエンジンは読み込みを開始すると中止できません", + "This engine imports in one step, so there is no progress to show or stop.": "このエンジンは読み込みを 1 回で行うため、表示や中止できる進行状況はありません。", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "このファイルには単位が記されていません。FormShot は大きさから {unit} と推測しました。読み込む前に確認してください。", + "Triangles": "三角形", + "Ultra": "ウルトラ", + "Units": "単位", + "Up axis": "上方向の軸", + "Up axis in file": "ファイル内の上方向の軸", + "Uploading": "アップロード中", + "Y is up": "Y が上", + "Z is up": "Z が上", + "centimetres": "センチメートル", + "feet": "フィート", + "inches": "インチ", + "metres": "メートル", + "millimetres": "ミリメートル", + "{i} of {n}": "{n} 個中 {i} 個", + "{n} files beside it": "隣にある {n} 個のファイル", + "{n} files were not imported.": "{n} 個のファイルは読み込まれませんでした。", + "{n} warnings; the Scene page lists the parts.": "警告 {n} 件。パーツの一覧はシーンページにあります。" +} diff --git a/frontend/src/i18n/modules/import/ko.json b/frontend/src/i18n/modules/import/ko.json new file mode 100644 index 00000000..3f3988a1 --- /dev/null +++ b/frontend/src/i18n/modules/import/ko.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D 모델", + "Automatic": "자동", + "CAD quality": "CAD 품질", + "Centimetres (cm)": "센티미터 (cm)", + "Centre on the origin": "원점을 중심으로", + "Choose model files and import them into the scene with options.": "모델 파일을 선택하고 옵션을 지정해 장면으로 가져옵니다.", + "Cleaning up meshes": "메시 정리 중", + "Clear Recent Imports": "최근 가져오기 지우기", + "Could not import the file: {reason}": "파일을 가져오지 못했습니다: {reason}", + "Could not import {name}: {reason}": "{name}을(를) 가져오지 못했습니다: {reason}", + "Could not open {name}: {reason}": "{name}을(를) 열지 못했습니다: {reason}", + "Could not read the file: {reason}": "파일을 읽지 못했습니다: {reason}", + "Could not reimport: {reason}": "다시 가져오지 못했습니다: {reason}", + "Could not send the file: {reason}": "파일을 보내지 못했습니다: {reason}", + "Discard unsaved changes?": "저장하지 않은 변경 사항을 버리시겠습니까?", + "Draft": "초안", + "Drop to import into the scene": "놓아서 장면으로 가져오기", + "Feet (ft)": "피트 (ft)", + "Format": "형식", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot은 한 번에 프로젝트 하나만 엽니다. 다른 프로젝트 파일 {n}개는 열지 않았습니다.", + "Frame the view after import": "가져온 후 뷰 맞추기", + "High": "높음", + "Import": "가져오기", + "Import All": "모두 가져오기", + "Import Files": "파일 가져오기", + "Import Model": "모델 가져오기", + "Import Recent File": "최근 파일 가져오기", + "Imported {name}.": "{name}을(를) 가져왔습니다.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name}을(를) 가져왔습니다: 파트 {parts}개, 삼각형 {triangles}개.", + "Imported {name}: {parts} parts.": "{name}을(를) 가져왔습니다: 파트 {parts}개.", + "Importing": "가져오는 중", + "In this file": "이 파일 안", + "Inches (in)": "인치 (in)", + "Making materials": "머티리얼 만드는 중", + "Materials": "머티리얼", + "Medium": "보통", + "Merge into one group": "하나의 그룹으로 병합", + "Metres (m)": "미터 (m)", + "Millimetres (mm)": "밀리미터 (mm)", + "No Recent Imports": "최근 가져오기 없음", + "No warnings.": "경고가 없습니다.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "가져올 항목이 없습니다. FormShot은 GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP, IGES 파일을 가져올 수 있습니다.", + "One file beside it": "옆에 있는 파일 1개", + "Opening {name} will close the open project and discard its unsaved changes.": "{name}을(를) 열면 열려 있는 프로젝트가 닫히고 저장하지 않은 변경 사항은 버려집니다.", + "Options": "옵션", + "Parts": "파트", + "Placing in the scene": "장면에 배치하는 중", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "선택한 파트(또는 가져온 모든 파트)의 원본 파일을 머티리얼을 유지한 채 다시 읽습니다.", + "Reading the file": "파일 읽는 중", + "Reading the file...": "파일 읽는 중...", + "Recent Imports": "최근 가져오기", + "Reimport": "다시 가져오기", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "다시 가져옴: 업데이트 {matched}, 새로 추가 {added}, 숨김 {hidden}.", + "Send model files to FormShot and import them into the scene with options.": "모델 파일을 FormShot으로 보내 옵션을 지정해 장면으로 가져옵니다.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "여러 파일은 차례로 가져옵니다. 모델 옆에 있는 버퍼, 머티리얼, 텍스처도 함께 가져옵니다.", + "Size": "크기", + "Stand on the floor": "바닥에 놓기", + "Tessellating CAD surfaces": "CAD 서피스를 테셀레이션하는 중", + "The engine decides from the file.": "엔진이 파일을 보고 결정합니다.", + "The engine did not start an import job": "엔진이 가져오기 작업을 시작하지 않았습니다", + "The engine did not start in time, so the files FormShot was given were not opened.": "엔진이 제시간에 시작되지 않아 FormShot에 전달된 파일을 열지 못했습니다.", + "The file says it is in {unit}.": "파일에 단위가 {unit}(으)로 표기되어 있습니다.", + "The import failed": "가져오기에 실패했습니다", + "The import goes on; the files after it were not imported.": "가져오기는 계속됩니다. 이후의 파일은 가져오지 않았습니다.", + "The import of {name} was cancelled.": "{name} 가져오기가 취소되었습니다.", + "The upload failed ({status})": "업로드에 실패했습니다 ({status})", + "The upload was cancelled": "업로드가 취소되었습니다", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "이 엔진은 가져오기 전에 파일 내용을 확인할 수 없어 요약이 비어 있습니다.", + "This engine cannot stop an import once it has started": "이 엔진은 가져오기를 시작하면 중단할 수 없습니다", + "This engine imports in one step, so there is no progress to show or stop.": "이 엔진은 한 번에 가져오므로 표시하거나 중단할 진행 상황이 없습니다.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "이 파일에는 단위가 표기되어 있지 않습니다. FormShot이 크기를 보고 {unit}(으)로 추정했습니다. 가져오기 전에 확인하세요.", + "Triangles": "삼각형", + "Ultra": "울트라", + "Units": "단위", + "Up axis": "위쪽 축", + "Up axis in file": "파일의 위쪽 축", + "Uploading": "업로드 중", + "Y is up": "Y가 위쪽", + "Z is up": "Z가 위쪽", + "centimetres": "센티미터", + "feet": "피트", + "inches": "인치", + "metres": "미터", + "millimetres": "밀리미터", + "{i} of {n}": "{n}개 중 {i}개", + "{n} files beside it": "옆에 있는 파일 {n}개", + "{n} files were not imported.": "파일 {n}개를 가져오지 않았습니다.", + "{n} warnings; the Scene page lists the parts.": "경고 {n}개. 파트 목록은 장면 페이지에 있습니다." +} diff --git a/frontend/src/i18n/modules/import/nb.json b/frontend/src/i18n/modules/import/nb.json new file mode 100644 index 00000000..b36b38ad --- /dev/null +++ b/frontend/src/i18n/modules/import/nb.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D-modeller", + "Automatic": "Automatisk", + "CAD quality": "CAD-kvalitet", + "Centimetres (cm)": "Centimeter (cm)", + "Centre on the origin": "Sentrer på origo", + "Choose model files and import them into the scene with options.": "Velg modellfiler og importer dem til scenen med alternativer.", + "Cleaning up meshes": "Rydder opp i meshes", + "Clear Recent Imports": "Tøm nylige importer", + "Could not import the file: {reason}": "Kunne ikke importere filen: {reason}", + "Could not import {name}: {reason}": "Kunne ikke importere {name}: {reason}", + "Could not open {name}: {reason}": "Kunne ikke åpne {name}: {reason}", + "Could not read the file: {reason}": "Kunne ikke lese filen: {reason}", + "Could not reimport: {reason}": "Kunne ikke importere på nytt: {reason}", + "Could not send the file: {reason}": "Kunne ikke sende filen: {reason}", + "Discard unsaved changes?": "Forkaste ulagrede endringer?", + "Draft": "Utkast", + "Drop to import into the scene": "Slipp for å importere til scenen", + "Feet (ft)": "Fot (ft)", + "Format": "Format", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot åpner ett prosjekt om gangen; {n} andre prosjektfiler ble ikke åpnet.", + "Frame the view after import": "Ramm inn visningen etter import", + "High": "Høy", + "Import": "Importer", + "Import All": "Importer alle", + "Import Files": "Importer filer", + "Import Model": "Importer modell", + "Import Recent File": "Importer nylig fil", + "Imported {name}.": "{name} er importert.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} er importert: {parts} deler, {triangles} trekanter.", + "Imported {name}: {parts} parts.": "{name} er importert: {parts} deler.", + "Importing": "Importerer", + "In this file": "I denne filen", + "Inches (in)": "Tommer (in)", + "Making materials": "Lager materialer", + "Materials": "Materialer", + "Medium": "Middels", + "Merge into one group": "Slå sammen til én gruppe", + "Metres (m)": "Meter (m)", + "Millimetres (mm)": "Millimeter (mm)", + "No Recent Imports": "Ingen nylige importer", + "No warnings.": "Ingen advarsler.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Ingenting å importere: FormShot importerer GLB-, glTF-, OBJ-, STL-, PLY-, 3MF-, FBX-, STEP- og IGES-filer.", + "One file beside it": "Én fil ved siden av", + "Opening {name} will close the open project and discard its unsaved changes.": "Hvis du åpner {name}, lukkes det åpne prosjektet, og de ulagrede endringene forkastes.", + "Options": "Alternativer", + "Parts": "Deler", + "Placing in the scene": "Plasserer i scenen", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Leser kildefilene til de valgte delene (eller til alle importerte deler) på nytt og beholder materialene deres.", + "Reading the file": "Leser filen", + "Reading the file...": "Leser filen...", + "Recent Imports": "Nylige importer", + "Reimport": "Importer på nytt", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Importert på nytt: {matched} oppdatert, {added} nye, {hidden} skjult.", + "Send model files to FormShot and import them into the scene with options.": "Send modellfiler til FormShot og importer dem til scenen med alternativer.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Flere filer importeres etter hverandre. Buffere, materialer og teksturer ved siden av en modell følger med.", + "Size": "Størrelse", + "Stand on the floor": "Sett på gulvet", + "Tessellating CAD surfaces": "Tesselerer CAD-flater", + "The engine decides from the file.": "Motoren avgjør det ut fra filen.", + "The engine did not start an import job": "Motoren startet ikke noen importjobb", + "The engine did not start in time, so the files FormShot was given were not opened.": "Motoren startet ikke i tide, så filene FormShot fikk, ble ikke åpnet.", + "The file says it is in {unit}.": "Filen oppgir at den er i {unit}.", + "The import failed": "Importen mislyktes", + "The import goes on; the files after it were not imported.": "Importen fortsetter; filene etter den ble ikke importert.", + "The import of {name} was cancelled.": "Importen av {name} ble avbrutt.", + "The upload failed ({status})": "Opplastingen mislyktes ({status})", + "The upload was cancelled": "Opplastingen ble avbrutt", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Denne motoren kan ikke se inn i en fil før import, så oppsummeringen forblir tom.", + "This engine cannot stop an import once it has started": "Denne motoren kan ikke stoppe en import når den først har startet", + "This engine imports in one step, so there is no progress to show or stop.": "Denne motoren importerer i ett trinn, så det er ingen fremdrift å vise eller stoppe.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Denne filen oppgir ikke enhetene sine. FormShot gjettet {unit} ut fra størrelsen; kontroller det før importen.", + "Triangles": "Trekanter", + "Ultra": "Ultra", + "Units": "Enheter", + "Up axis": "Opp-akse", + "Up axis in file": "Opp-akse i filen", + "Uploading": "Laster opp", + "Y is up": "Y er opp", + "Z is up": "Z er opp", + "centimetres": "centimeter", + "feet": "fot", + "inches": "tommer", + "metres": "meter", + "millimetres": "millimeter", + "{i} of {n}": "{i} av {n}", + "{n} files beside it": "{n} filer ved siden av", + "{n} files were not imported.": "{n} filer ble ikke importert.", + "{n} warnings; the Scene page lists the parts.": "{n} advarsler; Scenesiden viser delene." +} diff --git a/frontend/src/i18n/modules/import/nl.json b/frontend/src/i18n/modules/import/nl.json new file mode 100644 index 00000000..01aed371 --- /dev/null +++ b/frontend/src/i18n/modules/import/nl.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D-modellen", + "Automatic": "Automatisch", + "CAD quality": "CAD-kwaliteit", + "Centimetres (cm)": "Centimeter (cm)", + "Centre on the origin": "Centreren op de oorsprong", + "Choose model files and import them into the scene with options.": "Kies modelbestanden en importeer ze met opties in de scène.", + "Cleaning up meshes": "Meshes opschonen", + "Clear Recent Imports": "Recente imports wissen", + "Could not import the file: {reason}": "Het bestand kon niet worden geïmporteerd: {reason}", + "Could not import {name}: {reason}": "{name} kon niet worden geïmporteerd: {reason}", + "Could not open {name}: {reason}": "{name} kon niet worden geopend: {reason}", + "Could not read the file: {reason}": "Het bestand kon niet worden gelezen: {reason}", + "Could not reimport: {reason}": "Opnieuw importeren is mislukt: {reason}", + "Could not send the file: {reason}": "Het bestand kon niet worden verzonden: {reason}", + "Discard unsaved changes?": "Niet-opgeslagen wijzigingen verwerpen?", + "Draft": "Concept", + "Drop to import into the scene": "Laat los om in de scène te importeren", + "Feet (ft)": "Voet (ft)", + "Format": "Indeling", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot opent één project tegelijk; {n} andere projectbestanden zijn niet geopend.", + "Frame the view after import": "Beeld framen na het importeren", + "High": "Hoog", + "Import": "Importeren", + "Import All": "Alles importeren", + "Import Files": "Bestanden importeren", + "Import Model": "Model importeren", + "Import Recent File": "Recent bestand importeren", + "Imported {name}.": "{name} is geïmporteerd.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} is geïmporteerd: {parts} onderdelen, {triangles} driehoeken.", + "Imported {name}: {parts} parts.": "{name} is geïmporteerd: {parts} onderdelen.", + "Importing": "Importeren", + "In this file": "In dit bestand", + "Inches (in)": "Inch (in)", + "Making materials": "Materialen maken", + "Materials": "Materialen", + "Medium": "Gemiddeld", + "Merge into one group": "Samenvoegen tot één groep", + "Metres (m)": "Meter (m)", + "Millimetres (mm)": "Millimeter (mm)", + "No Recent Imports": "Geen recente imports", + "No warnings.": "Geen waarschuwingen.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Niets te importeren: FormShot importeert GLB-, glTF-, OBJ-, STL-, PLY-, 3MF-, FBX-, STEP- en IGES-bestanden.", + "One file beside it": "Eén bestand ernaast", + "Opening {name} will close the open project and discard its unsaved changes.": "Als je {name} opent, wordt het geopende project gesloten en gaan de niet-opgeslagen wijzigingen verloren.", + "Options": "Opties", + "Parts": "Onderdelen", + "Placing in the scene": "In de scène plaatsen", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Leest de bronbestanden van de geselecteerde onderdelen (of van alle geïmporteerde onderdelen) opnieuw in en behoudt hun materialen.", + "Reading the file": "Het bestand lezen", + "Reading the file...": "Het bestand lezen...", + "Recent Imports": "Recente imports", + "Reimport": "Opnieuw importeren", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Opnieuw geïmporteerd: {matched} bijgewerkt, {added} nieuw, {hidden} verborgen.", + "Send model files to FormShot and import them into the scene with options.": "Stuur modelbestanden naar FormShot en importeer ze met opties in de scène.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Meerdere bestanden worden na elkaar geïmporteerd. Buffers, materialen en teksturen naast een model gaan mee.", + "Size": "Grootte", + "Stand on the floor": "Op de vloer zetten", + "Tessellating CAD surfaces": "CAD-oppervlakken tesselleren", + "The engine decides from the file.": "De engine bepaalt het aan de hand van het bestand.", + "The engine did not start an import job": "De engine heeft geen importtaak gestart", + "The engine did not start in time, so the files FormShot was given were not opened.": "De engine startte niet op tijd, dus de bestanden die FormShot kreeg zijn niet geopend.", + "The file says it is in {unit}.": "Het bestand geeft aan dat het in {unit} is.", + "The import failed": "De import is mislukt", + "The import goes on; the files after it were not imported.": "De import gaat door; de bestanden daarna zijn niet geïmporteerd.", + "The import of {name} was cancelled.": "De import van {name} is geannuleerd.", + "The upload failed ({status})": "Het uploaden is mislukt ({status})", + "The upload was cancelled": "Het uploaden is geannuleerd", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Deze engine kan niet in een bestand kijken vóór het importeren, dus de samenvatting blijft leeg.", + "This engine cannot stop an import once it has started": "Deze engine kan een import niet stoppen zodra die is gestart", + "This engine imports in one step, so there is no progress to show or stop.": "Deze engine importeert in één stap, dus er is geen voortgang om te tonen of te stoppen.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Dit bestand geeft zijn eenheden niet aan. FormShot heeft {unit} geraden op basis van de grootte; controleer dit vóór het importeren.", + "Triangles": "Driehoeken", + "Ultra": "Ultra", + "Units": "Eenheden", + "Up axis": "Bovenste as", + "Up axis in file": "Bovenste as in bestand", + "Uploading": "Uploaden", + "Y is up": "Y is boven", + "Z is up": "Z is boven", + "centimetres": "centimeter", + "feet": "voet", + "inches": "inch", + "metres": "meter", + "millimetres": "millimeter", + "{i} of {n}": "{i} van {n}", + "{n} files beside it": "{n} bestanden ernaast", + "{n} files were not imported.": "{n} bestanden zijn niet geïmporteerd.", + "{n} warnings; the Scene page lists the parts.": "{n} waarschuwingen; de Scènepagina toont de onderdelen." +} diff --git a/frontend/src/i18n/modules/import/pl.json b/frontend/src/i18n/modules/import/pl.json new file mode 100644 index 00000000..e94ff983 --- /dev/null +++ b/frontend/src/i18n/modules/import/pl.json @@ -0,0 +1,90 @@ +{ + "3D models": "Modele 3D", + "Automatic": "Automatyczne", + "CAD quality": "Jakość CAD", + "Centimetres (cm)": "Centymetry (cm)", + "Centre on the origin": "Wyśrodkuj na początku układu", + "Choose model files and import them into the scene with options.": "Wybierz pliki modeli i zaimportuj je do sceny z wybranymi opcjami.", + "Cleaning up meshes": "Czyszczenie siatek", + "Clear Recent Imports": "Wyczyść ostatnie importy", + "Could not import the file: {reason}": "Nie udało się zaimportować pliku: {reason}", + "Could not import {name}: {reason}": "Nie udało się zaimportować {name}: {reason}", + "Could not open {name}: {reason}": "Nie udało się otworzyć {name}: {reason}", + "Could not read the file: {reason}": "Nie udało się odczytać pliku: {reason}", + "Could not reimport: {reason}": "Nie udało się ponownie zaimportować: {reason}", + "Could not send the file: {reason}": "Nie udało się wysłać pliku: {reason}", + "Discard unsaved changes?": "Odrzucić niezapisane zmiany?", + "Draft": "Szkic", + "Drop to import into the scene": "Upuść, aby zaimportować do sceny", + "Feet (ft)": "Stopy (ft)", + "Format": "Format", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot otwiera jeden projekt naraz; pozostałe pliki projektów ({n}) zostały pominięte.", + "Frame the view after import": "Wyśrodkuj widok po imporcie", + "High": "Wysoka", + "Import": "Importuj", + "Import All": "Importuj wszystko", + "Import Files": "Importuj pliki", + "Import Model": "Importuj model", + "Import Recent File": "Importuj ostatni plik", + "Imported {name}.": "Zaimportowano {name}.", + "Imported {name}: {parts} parts, {triangles} triangles.": "Zaimportowano {name}: części: {parts}, trójkąty: {triangles}.", + "Imported {name}: {parts} parts.": "Zaimportowano {name}: części: {parts}.", + "Importing": "Importowanie", + "In this file": "W tym pliku", + "Inches (in)": "Cale (in)", + "Making materials": "Tworzenie materiałów", + "Materials": "Materiały", + "Medium": "Średnia", + "Merge into one group": "Scal w jedną grupę", + "Metres (m)": "Metry (m)", + "Millimetres (mm)": "Milimetry (mm)", + "No Recent Imports": "Brak ostatnich importów", + "No warnings.": "Brak ostrzeżeń.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Nie ma czego importować: FormShot importuje pliki GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP i IGES.", + "One file beside it": "Jeden plik obok niego", + "Opening {name} will close the open project and discard its unsaved changes.": "Otwarcie {name} zamknie otwarty projekt i odrzuci jego niezapisane zmiany.", + "Options": "Opcje", + "Parts": "Części", + "Placing in the scene": "Umieszczanie w scenie", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Odczytaj ponownie pliki źródłowe zaznaczonych części (lub wszystkich zaimportowanych części), zachowując ich materiały.", + "Reading the file": "Odczytywanie pliku", + "Reading the file...": "Odczytywanie pliku...", + "Recent Imports": "Ostatnie importy", + "Reimport": "Importuj ponownie", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Zaimportowano ponownie: zaktualizowano {matched}, nowe {added}, ukryte {hidden}.", + "Send model files to FormShot and import them into the scene with options.": "Wyślij pliki modeli do FormShot i zaimportuj je do sceny z opcjami.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Kilka plików jest importowanych jeden po drugim. Bufory, materiały i tekstury leżące obok modelu są importowane razem z nim.", + "Size": "Rozmiar", + "Stand on the floor": "Postaw na podłodze", + "Tessellating CAD surfaces": "Teselacja powierzchni CAD", + "The engine decides from the file.": "Silnik zdecyduje na podstawie pliku.", + "The engine did not start an import job": "Silnik nie rozpoczął zadania importu", + "The engine did not start in time, so the files FormShot was given were not opened.": "Silnik nie uruchomił się na czas, więc pliki przekazane FormShot nie zostały otwarte.", + "The file says it is in {unit}.": "Plik podaje jednostkę: {unit}.", + "The import failed": "Import nie powiódł się", + "The import goes on; the files after it were not imported.": "Import trwa dalej; kolejne pliki nie zostały zaimportowane.", + "The import of {name} was cancelled.": "Anulowano import {name}.", + "The upload failed ({status})": "Przesyłanie nie powiodło się ({status})", + "The upload was cancelled": "Przesyłanie zostało anulowane", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Ten silnik nie potrafi zajrzeć do pliku przed importem, więc podsumowanie pozostaje puste.", + "This engine cannot stop an import once it has started": "Ten silnik nie może zatrzymać importu po jego rozpoczęciu", + "This engine imports in one step, so there is no progress to show or stop.": "Ten silnik importuje w jednym kroku, więc nie ma postępu do pokazania ani do zatrzymania.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Plik nie podaje jednostek. FormShot odgadł jednostkę ({unit}) na podstawie rozmiaru; sprawdź ją przed importem.", + "Triangles": "Trójkąty", + "Ultra": "Ultra", + "Units": "Jednostki", + "Up axis": "Oś pionowa", + "Up axis in file": "Oś pionowa w pliku", + "Uploading": "Przesyłanie", + "Y is up": "Y jest osią pionową", + "Z is up": "Z jest osią pionową", + "centimetres": "centymetry", + "feet": "stopy", + "inches": "cale", + "metres": "metry", + "millimetres": "milimetry", + "{i} of {n}": "{i} z {n}", + "{n} files beside it": "{n} plików obok niego", + "{n} files were not imported.": "Nie zaimportowano plików: {n}.", + "{n} warnings; the Scene page lists the parts.": "Ostrzeżenia: {n}; części wymienia strona sceny." +} diff --git a/frontend/src/i18n/modules/import/pt-BR.json b/frontend/src/i18n/modules/import/pt-BR.json new file mode 100644 index 00000000..0759f64d --- /dev/null +++ b/frontend/src/i18n/modules/import/pt-BR.json @@ -0,0 +1,90 @@ +{ + "3D models": "Modelos 3D", + "Automatic": "Automático", + "CAD quality": "Qualidade CAD", + "Centimetres (cm)": "Centímetros (cm)", + "Centre on the origin": "Centralizar na origem", + "Choose model files and import them into the scene with options.": "Escolha arquivos de modelo e importe-os para a cena com opções.", + "Cleaning up meshes": "Limpando malhas", + "Clear Recent Imports": "Limpar importações recentes", + "Could not import the file: {reason}": "Não foi possível importar o arquivo: {reason}", + "Could not import {name}: {reason}": "Não foi possível importar {name}: {reason}", + "Could not open {name}: {reason}": "Não foi possível abrir {name}: {reason}", + "Could not read the file: {reason}": "Não foi possível ler o arquivo: {reason}", + "Could not reimport: {reason}": "Não foi possível reimportar: {reason}", + "Could not send the file: {reason}": "Não foi possível enviar o arquivo: {reason}", + "Discard unsaved changes?": "Descartar alterações não salvas?", + "Draft": "Rascunho", + "Drop to import into the scene": "Solte para importar para a cena", + "Feet (ft)": "Pés (ft)", + "Format": "Formato", + "FormShot opens one project at a time; {n} other project files were left unopened.": "O FormShot abre um projeto por vez; os outros {n} arquivos de projeto não foram abertos.", + "Frame the view after import": "Enquadrar a vista após importar", + "High": "Alta", + "Import": "Importar", + "Import All": "Importar tudo", + "Import Files": "Importar arquivos", + "Import Model": "Importar modelo", + "Import Recent File": "Importar arquivo recente", + "Imported {name}.": "{name} importado.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} importado: {parts} peças, {triangles} triângulos.", + "Imported {name}: {parts} parts.": "{name} importado: {parts} peças.", + "Importing": "Importando", + "In this file": "Neste arquivo", + "Inches (in)": "Polegadas (in)", + "Making materials": "Criando materiais", + "Materials": "Materiais", + "Medium": "Média", + "Merge into one group": "Mesclar em um grupo", + "Metres (m)": "Metros (m)", + "Millimetres (mm)": "Milímetros (mm)", + "No Recent Imports": "Nenhuma importação recente", + "No warnings.": "Nenhum aviso.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Nada para importar: o FormShot importa arquivos GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP e IGES.", + "One file beside it": "Um arquivo ao lado", + "Opening {name} will close the open project and discard its unsaved changes.": "Abrir {name} fechará o projeto aberto e descartará as alterações não salvas dele.", + "Options": "Opções", + "Parts": "Peças", + "Placing in the scene": "Posicionando na cena", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Lê novamente os arquivos de origem das peças selecionadas (ou de todas as peças importadas), mantendo os materiais delas.", + "Reading the file": "Lendo o arquivo", + "Reading the file...": "Lendo o arquivo...", + "Recent Imports": "Importações recentes", + "Reimport": "Reimportar", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Reimportado: {matched} atualizadas, {added} novas, {hidden} ocultas.", + "Send model files to FormShot and import them into the scene with options.": "Envie arquivos de modelo ao FormShot e importe-os para a cena com opções.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Vários arquivos são importados um após o outro. Buffers, materiais e texturas ao lado de um modelo vão junto com ele.", + "Size": "Tamanho", + "Stand on the floor": "Apoiar no chão", + "Tessellating CAD surfaces": "Tesselando superfícies CAD", + "The engine decides from the file.": "O motor decide com base no arquivo.", + "The engine did not start an import job": "O motor não iniciou uma tarefa de importação", + "The engine did not start in time, so the files FormShot was given were not opened.": "O motor não iniciou a tempo, então os arquivos entregues ao FormShot não foram abertos.", + "The file says it is in {unit}.": "O arquivo informa que está em {unit}.", + "The import failed": "A importação falhou", + "The import goes on; the files after it were not imported.": "A importação continua; os arquivos seguintes não foram importados.", + "The import of {name} was cancelled.": "A importação de {name} foi cancelada.", + "The upload failed ({status})": "O envio falhou ({status})", + "The upload was cancelled": "O envio foi cancelado", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Este motor não consegue olhar dentro de um arquivo antes de importar, então o resumo fica vazio.", + "This engine cannot stop an import once it has started": "Este motor não pode interromper uma importação depois de iniciada", + "This engine imports in one step, so there is no progress to show or stop.": "Este motor importa em uma única etapa, então não há progresso para mostrar ou interromper.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Este arquivo não informa suas unidades. O FormShot estimou {unit} pelo tamanho; confira antes de importar.", + "Triangles": "Triângulos", + "Ultra": "Ultra", + "Units": "Unidades", + "Up axis": "Eixo para cima", + "Up axis in file": "Eixo para cima no arquivo", + "Uploading": "Enviando", + "Y is up": "Y é para cima", + "Z is up": "Z é para cima", + "centimetres": "centímetros", + "feet": "pés", + "inches": "polegadas", + "metres": "metros", + "millimetres": "milímetros", + "{i} of {n}": "{i} de {n}", + "{n} files beside it": "{n} arquivos ao lado", + "{n} files were not imported.": "{n} arquivos não foram importados.", + "{n} warnings; the Scene page lists the parts.": "{n} avisos; a página Cena lista as peças." +} diff --git a/frontend/src/i18n/modules/import/ru.json b/frontend/src/i18n/modules/import/ru.json new file mode 100644 index 00000000..9bdbd9ea --- /dev/null +++ b/frontend/src/i18n/modules/import/ru.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D-модели", + "Automatic": "Автоматически", + "CAD quality": "Качество CAD", + "Centimetres (cm)": "Сантиметры (cm)", + "Centre on the origin": "Центрировать по началу координат", + "Choose model files and import them into the scene with options.": "Выберите файлы моделей и импортируйте их в сцену с настройками.", + "Cleaning up meshes": "Очистка мешей", + "Clear Recent Imports": "Очистить недавние импорты", + "Could not import the file: {reason}": "Не удалось импортировать файл: {reason}", + "Could not import {name}: {reason}": "Не удалось импортировать {name}: {reason}", + "Could not open {name}: {reason}": "Не удалось открыть {name}: {reason}", + "Could not read the file: {reason}": "Не удалось прочитать файл: {reason}", + "Could not reimport: {reason}": "Не удалось выполнить повторный импорт: {reason}", + "Could not send the file: {reason}": "Не удалось передать файл: {reason}", + "Discard unsaved changes?": "Отбросить несохранённые изменения?", + "Draft": "Черновик", + "Drop to import into the scene": "Отпустите, чтобы импортировать в сцену", + "Feet (ft)": "Футы (ft)", + "Format": "Формат", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot открывает один проект за раз; остальные файлы проектов ({n}) оставлены закрытыми.", + "Frame the view after import": "Показать вид после импорта", + "High": "Высокое", + "Import": "Импорт", + "Import All": "Импортировать все", + "Import Files": "Импортировать файлы", + "Import Model": "Импорт модели", + "Import Recent File": "Импортировать недавний файл", + "Imported {name}.": "Импортировано: {name}.", + "Imported {name}: {parts} parts, {triangles} triangles.": "Импортировано {name}: деталей {parts}, треугольников {triangles}.", + "Imported {name}: {parts} parts.": "Импортировано {name}: деталей {parts}.", + "Importing": "Импорт", + "In this file": "В этом файле", + "Inches (in)": "Дюймы (in)", + "Making materials": "Создание материалов", + "Materials": "Материалы", + "Medium": "Среднее", + "Merge into one group": "Объединить в одну группу", + "Metres (m)": "Метры (m)", + "Millimetres (mm)": "Миллиметры (mm)", + "No Recent Imports": "Нет недавних импортов", + "No warnings.": "Предупреждений нет.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Импортировать нечего: FormShot импортирует файлы GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP и IGES.", + "One file beside it": "Один файл рядом", + "Opening {name} will close the open project and discard its unsaved changes.": "Открытие {name} закроет текущий проект и отбросит его несохранённые изменения.", + "Options": "Параметры", + "Parts": "Детали", + "Placing in the scene": "Размещение в сцене", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Заново прочитать исходные файлы выбранных деталей (или всех импортированных), сохранив их материалы.", + "Reading the file": "Чтение файла", + "Reading the file...": "Чтение файла...", + "Recent Imports": "Недавние импорты", + "Reimport": "Импортировать заново", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Повторный импорт: обновлено {matched}, новых {added}, скрыто {hidden}.", + "Send model files to FormShot and import them into the scene with options.": "Отправьте файлы моделей в FormShot и импортируйте их в сцену с настройками.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Несколько файлов импортируются по очереди. Буферы, материалы и текстуры рядом с моделью импортируются вместе с ней.", + "Size": "Размер", + "Stand on the floor": "Поставить на пол", + "Tessellating CAD surfaces": "Тесселяция CAD-поверхностей", + "The engine decides from the file.": "Движок определит по файлу.", + "The engine did not start an import job": "Движок не запустил задачу импорта", + "The engine did not start in time, so the files FormShot was given were not opened.": "Движок не запустился вовремя, поэтому файлы, переданные FormShot, не были открыты.", + "The file says it is in {unit}.": "В файле указано: {unit}.", + "The import failed": "Импорт не удался", + "The import goes on; the files after it were not imported.": "Импорт продолжается; следующие за ним файлы не были импортированы.", + "The import of {name} was cancelled.": "Импорт {name} отменён.", + "The upload failed ({status})": "Не удалось загрузить ({status})", + "The upload was cancelled": "Загрузка отменена", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Этот движок не умеет заглядывать в файл перед импортом, поэтому сводка остаётся пустой.", + "This engine cannot stop an import once it has started": "Этот движок не может остановить импорт после его запуска", + "This engine imports in one step, so there is no progress to show or stop.": "Этот движок импортирует за один шаг, поэтому показывать и останавливать нечего.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "В этом файле не указаны единицы измерения. FormShot предположил {unit} по размеру; проверьте перед импортом.", + "Triangles": "Треугольники", + "Ultra": "Ультра", + "Units": "Единицы", + "Up axis": "Верхняя ось", + "Up axis in file": "Верхняя ось в файле", + "Uploading": "Загрузка", + "Y is up": "Вверх направлена ось Y", + "Z is up": "Вверх направлена ось Z", + "centimetres": "сантиметры", + "feet": "футы", + "inches": "дюймы", + "metres": "метры", + "millimetres": "миллиметры", + "{i} of {n}": "{i} из {n}", + "{n} files beside it": "Файлов рядом: {n}", + "{n} files were not imported.": "Не импортировано файлов: {n}.", + "{n} warnings; the Scene page lists the parts.": "Предупреждений: {n}; страница «Сцена» перечисляет детали." +} diff --git a/frontend/src/i18n/modules/import/strings.json b/frontend/src/i18n/modules/import/strings.json new file mode 100644 index 00000000..7dbdf376 --- /dev/null +++ b/frontend/src/i18n/modules/import/strings.json @@ -0,0 +1,90 @@ +[ + "3D models", + "Automatic", + "CAD quality", + "Centimetres (cm)", + "Centre on the origin", + "Choose model files and import them into the scene with options.", + "Cleaning up meshes", + "Clear Recent Imports", + "Could not import the file: {reason}", + "Could not import {name}: {reason}", + "Could not open {name}: {reason}", + "Could not read the file: {reason}", + "Could not reimport: {reason}", + "Could not send the file: {reason}", + "Discard unsaved changes?", + "Draft", + "Drop to import into the scene", + "Feet (ft)", + "Format", + "FormShot opens one project at a time; {n} other project files were left unopened.", + "Frame the view after import", + "High", + "Import", + "Import All", + "Import Files", + "Import Model", + "Import Recent File", + "Imported {name}.", + "Imported {name}: {parts} parts, {triangles} triangles.", + "Imported {name}: {parts} parts.", + "Importing", + "In this file", + "Inches (in)", + "Making materials", + "Materials", + "Medium", + "Merge into one group", + "Metres (m)", + "Millimetres (mm)", + "No Recent Imports", + "No warnings.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.", + "One file beside it", + "Opening {name} will close the open project and discard its unsaved changes.", + "Options", + "Parts", + "Placing in the scene", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.", + "Reading the file", + "Reading the file...", + "Recent Imports", + "Reimport", + "Reimported: updated {matched}, new {added}, hidden {hidden}.", + "Send model files to FormShot and import them into the scene with options.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.", + "Size", + "Stand on the floor", + "Tessellating CAD surfaces", + "The engine decides from the file.", + "The engine did not start an import job", + "The engine did not start in time, so the files FormShot was given were not opened.", + "The file says it is in {unit}.", + "The import failed", + "The import goes on; the files after it were not imported.", + "The import of {name} was cancelled.", + "The upload failed ({status})", + "The upload was cancelled", + "This engine cannot look inside a file before importing it, so the summary stays empty.", + "This engine cannot stop an import once it has started", + "This engine imports in one step, so there is no progress to show or stop.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.", + "Triangles", + "Ultra", + "Units", + "Up axis", + "Up axis in file", + "Uploading", + "Y is up", + "Z is up", + "centimetres", + "feet", + "inches", + "metres", + "millimetres", + "{i} of {n}", + "{n} files beside it", + "{n} files were not imported.", + "{n} warnings; the Scene page lists the parts." +] diff --git a/frontend/src/i18n/modules/import/sv.json b/frontend/src/i18n/modules/import/sv.json new file mode 100644 index 00000000..09f81787 --- /dev/null +++ b/frontend/src/i18n/modules/import/sv.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D-modeller", + "Automatic": "Automatisk", + "CAD quality": "CAD-kvalitet", + "Centimetres (cm)": "Centimeter (cm)", + "Centre on the origin": "Centrera på origo", + "Choose model files and import them into the scene with options.": "Välj modellfiler och importera dem till scenen med alternativ.", + "Cleaning up meshes": "Rensar meshar", + "Clear Recent Imports": "Rensa senaste importer", + "Could not import the file: {reason}": "Det gick inte att importera filen: {reason}", + "Could not import {name}: {reason}": "Det gick inte att importera {name}: {reason}", + "Could not open {name}: {reason}": "Det gick inte att öppna {name}: {reason}", + "Could not read the file: {reason}": "Det gick inte att läsa filen: {reason}", + "Could not reimport: {reason}": "Det gick inte att importera om: {reason}", + "Could not send the file: {reason}": "Det gick inte att skicka filen: {reason}", + "Discard unsaved changes?": "Förkasta osparade ändringar?", + "Draft": "Utkast", + "Drop to import into the scene": "Släpp för att importera till scenen", + "Feet (ft)": "Fot (ft)", + "Format": "Format", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot öppnar ett projekt i taget; {n} andra projektfiler lämnades oöppnade.", + "Frame the view after import": "Rama in vyn efter importen", + "High": "Hög", + "Import": "Importera", + "Import All": "Importera alla", + "Import Files": "Importera filer", + "Import Model": "Importera modell", + "Import Recent File": "Importera senaste fil", + "Imported {name}.": "{name} har importerats.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} har importerats: {parts} delar, {triangles} trianglar.", + "Imported {name}: {parts} parts.": "{name} har importerats: {parts} delar.", + "Importing": "Importerar", + "In this file": "I den här filen", + "Inches (in)": "Tum (in)", + "Making materials": "Skapar material", + "Materials": "Material", + "Medium": "Medel", + "Merge into one group": "Slå ihop till en grupp", + "Metres (m)": "Meter (m)", + "Millimetres (mm)": "Millimeter (mm)", + "No Recent Imports": "Inga senaste importer", + "No warnings.": "Inga varningar.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Inget att importera: FormShot importerar GLB-, glTF-, OBJ-, STL-, PLY-, 3MF-, FBX-, STEP- och IGES-filer.", + "One file beside it": "En fil bredvid", + "Opening {name} will close the open project and discard its unsaved changes.": "Om du öppnar {name} stängs det öppna projektet och dess osparade ändringar förkastas.", + "Options": "Alternativ", + "Parts": "Delar", + "Placing in the scene": "Placerar i scenen", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Läser källfilerna för de markerade delarna (eller för alla importerade delar) igen och behåller deras material.", + "Reading the file": "Läser filen", + "Reading the file...": "Läser filen...", + "Recent Imports": "Senaste importer", + "Reimport": "Importera om", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Omimporterat: {matched} uppdaterade, {added} nya, {hidden} dolda.", + "Send model files to FormShot and import them into the scene with options.": "Skicka modellfiler till FormShot och importera dem till scenen med alternativ.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Flera filer importeras efter varandra. Buffertar, material och texturer bredvid en modell följer med.", + "Size": "Storlek", + "Stand on the floor": "Ställ på golvet", + "Tessellating CAD surfaces": "Tesselerar CAD-ytor", + "The engine decides from the file.": "Motorn avgör utifrån filen.", + "The engine did not start an import job": "Motorn startade inget importjobb", + "The engine did not start in time, so the files FormShot was given were not opened.": "Motorn startade inte i tid, så filerna som FormShot fick öppnades inte.", + "The file says it is in {unit}.": "Filen anger att den är i {unit}.", + "The import failed": "Importen misslyckades", + "The import goes on; the files after it were not imported.": "Importen fortsätter; filerna efter den importerades inte.", + "The import of {name} was cancelled.": "Importen av {name} avbröts.", + "The upload failed ({status})": "Uppladdningen misslyckades ({status})", + "The upload was cancelled": "Uppladdningen avbröts", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Den här motorn kan inte titta i en fil före importen, så sammanfattningen förblir tom.", + "This engine cannot stop an import once it has started": "Den här motorn kan inte stoppa en import när den har startat", + "This engine imports in one step, so there is no progress to show or stop.": "Den här motorn importerar i ett enda steg, så det finns inget förlopp att visa eller stoppa.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Den här filen anger inte sina enheter. FormShot gissade {unit} utifrån storleken; kontrollera det före importen.", + "Triangles": "Trianglar", + "Ultra": "Ultra", + "Units": "Enheter", + "Up axis": "Uppåtaxel", + "Up axis in file": "Uppåtaxel i filen", + "Uploading": "Laddar upp", + "Y is up": "Y är uppåt", + "Z is up": "Z är uppåt", + "centimetres": "centimeter", + "feet": "fot", + "inches": "tum", + "metres": "meter", + "millimetres": "millimeter", + "{i} of {n}": "{i} av {n}", + "{n} files beside it": "{n} filer bredvid", + "{n} files were not imported.": "{n} filer importerades inte.", + "{n} warnings; the Scene page lists the parts.": "{n} varningar; Scensidan listar delarna." +} diff --git a/frontend/src/i18n/modules/import/th.json b/frontend/src/i18n/modules/import/th.json new file mode 100644 index 00000000..9153beae --- /dev/null +++ b/frontend/src/i18n/modules/import/th.json @@ -0,0 +1,90 @@ +{ + "3D models": "โมเดล 3D", + "Automatic": "อัตโนมัติ", + "CAD quality": "คุณภาพ CAD", + "Centimetres (cm)": "เซนติเมตร (cm)", + "Centre on the origin": "จัดกึ่งกลางที่จุดกำเนิด", + "Choose model files and import them into the scene with options.": "เลือกไฟล์โมเดลแล้วนำเข้าสู่ซีนพร้อมตัวเลือก", + "Cleaning up meshes": "กำลังทำความสะอาดเมช", + "Clear Recent Imports": "ล้างรายการนำเข้าล่าสุด", + "Could not import the file: {reason}": "ไม่สามารถนำเข้าไฟล์: {reason}", + "Could not import {name}: {reason}": "ไม่สามารถนำเข้า {name}: {reason}", + "Could not open {name}: {reason}": "ไม่สามารถเปิด {name}: {reason}", + "Could not read the file: {reason}": "ไม่สามารถอ่านไฟล์: {reason}", + "Could not reimport: {reason}": "ไม่สามารถนำเข้าซ้ำ: {reason}", + "Could not send the file: {reason}": "ไม่สามารถส่งไฟล์: {reason}", + "Discard unsaved changes?": "ละทิ้งการเปลี่ยนแปลงที่ยังไม่ได้บันทึกหรือไม่?", + "Draft": "ร่าง", + "Drop to import into the scene": "วางเพื่อนำเข้าสู่ซีน", + "Feet (ft)": "ฟุต (ft)", + "Format": "รูปแบบ", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot เปิดได้ครั้งละหนึ่งโปรเจกต์ จึงไม่ได้เปิดไฟล์โปรเจกต์อื่นอีก {n} ไฟล์", + "Frame the view after import": "จัดเฟรมมุมมองหลังนำเข้า", + "High": "สูง", + "Import": "นำเข้า", + "Import All": "นำเข้าทั้งหมด", + "Import Files": "นำเข้าไฟล์", + "Import Model": "นำเข้าโมเดล", + "Import Recent File": "นำเข้าไฟล์ล่าสุด", + "Imported {name}.": "นำเข้า {name} แล้ว", + "Imported {name}: {parts} parts, {triangles} triangles.": "นำเข้า {name} แล้ว: {parts} ชิ้นส่วน, {triangles} สามเหลี่ยม", + "Imported {name}: {parts} parts.": "นำเข้า {name} แล้ว: {parts} ชิ้นส่วน", + "Importing": "กำลังนำเข้า", + "In this file": "ในไฟล์นี้", + "Inches (in)": "นิ้ว (in)", + "Making materials": "กำลังสร้างแมทีเรียล", + "Materials": "แมทีเรียล", + "Medium": "ปานกลาง", + "Merge into one group": "รวมเป็นกลุ่มเดียว", + "Metres (m)": "เมตร (m)", + "Millimetres (mm)": "มิลลิเมตร (mm)", + "No Recent Imports": "ไม่มีรายการนำเข้าล่าสุด", + "No warnings.": "ไม่มีคำเตือน", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "ไม่มีอะไรให้นำเข้า: FormShot นำเข้าไฟล์ GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP และ IGES", + "One file beside it": "หนึ่งไฟล์ข้างเคียง", + "Opening {name} will close the open project and discard its unsaved changes.": "การเปิด {name} จะปิดโปรเจกต์ที่เปิดอยู่และละทิ้งการเปลี่ยนแปลงที่ยังไม่ได้บันทึก", + "Options": "ตัวเลือก", + "Parts": "ชิ้นส่วน", + "Placing in the scene": "กำลังวางในซีน", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "อ่านไฟล์ต้นฉบับของชิ้นส่วนที่เลือก (หรือของทุกชิ้นส่วนที่นำเข้า) ใหม่ โดยคงแมทีเรียลไว้", + "Reading the file": "กำลังอ่านไฟล์", + "Reading the file...": "กำลังอ่านไฟล์...", + "Recent Imports": "นำเข้าล่าสุด", + "Reimport": "นำเข้าซ้ำ", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "นำเข้าซ้ำแล้ว: อัปเดต {matched}, ใหม่ {added}, ซ่อน {hidden}", + "Send model files to FormShot and import them into the scene with options.": "ส่งไฟล์โมเดลไปยัง FormShot แล้วนำเข้าสู่ซีนพร้อมตัวเลือก", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "หลายไฟล์จะนำเข้าทีละไฟล์ต่อกัน บัฟเฟอร์ แมทีเรียล และเท็กซ์เจอร์ที่อยู่ข้างโมเดลจะตามมาด้วย", + "Size": "ขนาด", + "Stand on the floor": "วางบนพื้น", + "Tessellating CAD surfaces": "กำลังแปลงพื้นผิว CAD เป็นสามเหลี่ยม", + "The engine decides from the file.": "เอนจินจะตัดสินจากไฟล์", + "The engine did not start an import job": "เอนจินไม่ได้เริ่มงานนำเข้า", + "The engine did not start in time, so the files FormShot was given were not opened.": "เอนจินเริ่มไม่ทันเวลา จึงไม่ได้เปิดไฟล์ที่ส่งให้ FormShot", + "The file says it is in {unit}.": "ไฟล์ระบุว่าใช้หน่วย {unit}", + "The import failed": "การนำเข้าล้มเหลว", + "The import goes on; the files after it were not imported.": "การนำเข้ายังดำเนินต่อไป แต่ไฟล์ที่ตามหลังไม่ได้ถูกนำเข้า", + "The import of {name} was cancelled.": "ยกเลิกการนำเข้า {name} แล้ว", + "The upload failed ({status})": "การอัปโหลดล้มเหลว ({status})", + "The upload was cancelled": "ยกเลิกการอัปโหลดแล้ว", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "เอนจินนี้ดูภายในไฟล์ก่อนนำเข้าไม่ได้ สรุปจึงว่างเปล่า", + "This engine cannot stop an import once it has started": "เอนจินนี้หยุดการนำเข้าที่เริ่มแล้วไม่ได้", + "This engine imports in one step, so there is no progress to show or stop.": "เอนจินนี้นำเข้าในขั้นตอนเดียว จึงไม่มีความคืบหน้าให้แสดงหรือหยุด", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "ไฟล์นี้ไม่ได้ระบุหน่วย FormShot เดาจากขนาดว่าเป็น {unit} โปรดตรวจสอบก่อนนำเข้า", + "Triangles": "สามเหลี่ยม", + "Ultra": "สูงพิเศษ", + "Units": "หน่วย", + "Up axis": "แกนขึ้น", + "Up axis in file": "แกนขึ้นในไฟล์", + "Uploading": "กำลังอัปโหลด", + "Y is up": "Y คือแกนขึ้น", + "Z is up": "Z คือแกนขึ้น", + "centimetres": "เซนติเมตร", + "feet": "ฟุต", + "inches": "นิ้ว", + "metres": "เมตร", + "millimetres": "มิลลิเมตร", + "{i} of {n}": "{i} จาก {n}", + "{n} files beside it": "{n} ไฟล์ข้างเคียง", + "{n} files were not imported.": "ไม่ได้นำเข้า {n} ไฟล์", + "{n} warnings; the Scene page lists the parts.": "{n} คำเตือน; หน้าซีนแสดงรายการชิ้นส่วน" +} diff --git a/frontend/src/i18n/modules/import/tr.json b/frontend/src/i18n/modules/import/tr.json new file mode 100644 index 00000000..6cfa53c3 --- /dev/null +++ b/frontend/src/i18n/modules/import/tr.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D modeller", + "Automatic": "Otomatik", + "CAD quality": "CAD kalitesi", + "Centimetres (cm)": "Santimetre (cm)", + "Centre on the origin": "Başlangıç noktasına ortala", + "Choose model files and import them into the scene with options.": "Model dosyalarını seçin ve seçeneklerle sahneye içe aktarın.", + "Cleaning up meshes": "Mesh'ler temizleniyor", + "Clear Recent Imports": "Son İçe Aktarmaları Temizle", + "Could not import the file: {reason}": "Dosya içe aktarılamadı: {reason}", + "Could not import {name}: {reason}": "{name} içe aktarılamadı: {reason}", + "Could not open {name}: {reason}": "{name} açılamadı: {reason}", + "Could not read the file: {reason}": "Dosya okunamadı: {reason}", + "Could not reimport: {reason}": "Yeniden içe aktarılamadı: {reason}", + "Could not send the file: {reason}": "Dosya gönderilemedi: {reason}", + "Discard unsaved changes?": "Kaydedilmemiş değişiklikler silinsin mi?", + "Draft": "Taslak", + "Drop to import into the scene": "Sahneye içe aktarmak için bırakın", + "Feet (ft)": "Fit (ft)", + "Format": "Biçim", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot aynı anda tek proje açar; diğer {n} proje dosyası açılmadı.", + "Frame the view after import": "İçe aktarmadan sonra görünümü çerçevele", + "High": "Yüksek", + "Import": "İçe aktar", + "Import All": "Tümünü İçe Aktar", + "Import Files": "Dosyaları İçe Aktar", + "Import Model": "Model İçe Aktar", + "Import Recent File": "Son Dosyayı İçe Aktar", + "Imported {name}.": "{name} içe aktarıldı.", + "Imported {name}: {parts} parts, {triangles} triangles.": "{name} içe aktarıldı: {parts} parça, {triangles} üçgen.", + "Imported {name}: {parts} parts.": "{name} içe aktarıldı: {parts} parça.", + "Importing": "İçe aktarılıyor", + "In this file": "Bu dosyada", + "Inches (in)": "İnç (in)", + "Making materials": "Malzemeler oluşturuluyor", + "Materials": "Malzemeler", + "Medium": "Orta", + "Merge into one group": "Tek bir grupta birleştir", + "Metres (m)": "Metre (m)", + "Millimetres (mm)": "Milimetre (mm)", + "No Recent Imports": "Son İçe Aktarma Yok", + "No warnings.": "Uyarı yok.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "İçe aktarılacak bir şey yok: FormShot GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP ve IGES dosyalarını içe aktarır.", + "One file beside it": "Yanında bir dosya", + "Opening {name} will close the open project and discard its unsaved changes.": "{name} dosyasını açmak, açık projeyi kapatır ve kaydedilmemiş değişikliklerini siler.", + "Options": "Seçenekler", + "Parts": "Parçalar", + "Placing in the scene": "Sahneye yerleştiriliyor", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Seçili parçaların (veya içe aktarılan tüm parçaların) kaynak dosyalarını malzemelerini koruyarak yeniden okuyun.", + "Reading the file": "Dosya okunuyor", + "Reading the file...": "Dosya okunuyor...", + "Recent Imports": "Son İçe Aktarmalar", + "Reimport": "Yeniden İçe Aktar", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Yeniden içe aktarıldı: {matched} güncellendi, {added} yeni, {hidden} gizlendi.", + "Send model files to FormShot and import them into the scene with options.": "Model dosyalarını FormShot'a gönderin ve seçeneklerle sahneye içe aktarın.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Birden çok dosya sırayla içe aktarılır. Modelin yanındaki arabellekler, malzemeler ve dokular onunla birlikte gelir.", + "Size": "Boyut", + "Stand on the floor": "Zemine yerleştir", + "Tessellating CAD surfaces": "CAD yüzeyleri üçgenlere bölünüyor", + "The engine decides from the file.": "Motor dosyaya bakarak karar verir.", + "The engine did not start an import job": "Motor bir içe aktarma işi başlatmadı", + "The engine did not start in time, so the files FormShot was given were not opened.": "Motor zamanında başlamadığı için FormShot'a verilen dosyalar açılmadı.", + "The file says it is in {unit}.": "Dosyada birim {unit} olarak belirtilmiş.", + "The import failed": "İçe aktarma başarısız oldu", + "The import goes on; the files after it were not imported.": "İçe aktarma sürüyor; ondan sonraki dosyalar içe aktarılmadı.", + "The import of {name} was cancelled.": "{name} içe aktarma işlemi iptal edildi.", + "The upload failed ({status})": "Yükleme başarısız oldu ({status})", + "The upload was cancelled": "Yükleme iptal edildi", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Bu motor içe aktarmadan önce dosyanın içine bakamaz, bu yüzden özet boş kalır.", + "This engine cannot stop an import once it has started": "Bu motor başladıktan sonra bir içe aktarmayı durduramaz", + "This engine imports in one step, so there is no progress to show or stop.": "Bu motor tek adımda içe aktarır, bu yüzden gösterilecek veya durdurulacak bir ilerleme yoktur.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Bu dosya birimlerini belirtmiyor. FormShot boyutuna bakarak {unit} tahmin etti; içe aktarmadan önce kontrol edin.", + "Triangles": "Üçgenler", + "Ultra": "Ultra", + "Units": "Birimler", + "Up axis": "Yukarı ekseni", + "Up axis in file": "Dosyadaki yukarı ekseni", + "Uploading": "Yükleniyor", + "Y is up": "Y yukarıdır", + "Z is up": "Z yukarıdır", + "centimetres": "santimetre", + "feet": "fit", + "inches": "inç", + "metres": "metre", + "millimetres": "milimetre", + "{i} of {n}": "{i} / {n}", + "{n} files beside it": "Yanında {n} dosya", + "{n} files were not imported.": "{n} dosya içe aktarılmadı.", + "{n} warnings; the Scene page lists the parts.": "{n} uyarı; Sahne sayfası parçaları listeler." +} diff --git a/frontend/src/i18n/modules/import/uk.json b/frontend/src/i18n/modules/import/uk.json new file mode 100644 index 00000000..65e6d90e --- /dev/null +++ b/frontend/src/i18n/modules/import/uk.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D-моделі", + "Automatic": "Автоматично", + "CAD quality": "Якість CAD", + "Centimetres (cm)": "Сантиметри (cm)", + "Centre on the origin": "Центрувати за початком координат", + "Choose model files and import them into the scene with options.": "Виберіть файли моделей та імпортуйте їх у сцену з параметрами.", + "Cleaning up meshes": "Очищення мешів", + "Clear Recent Imports": "Очистити нещодавні імпорти", + "Could not import the file: {reason}": "Не вдалося імпортувати файл: {reason}", + "Could not import {name}: {reason}": "Не вдалося імпортувати {name}: {reason}", + "Could not open {name}: {reason}": "Не вдалося відкрити {name}: {reason}", + "Could not read the file: {reason}": "Не вдалося прочитати файл: {reason}", + "Could not reimport: {reason}": "Не вдалося виконати повторний імпорт: {reason}", + "Could not send the file: {reason}": "Не вдалося передати файл: {reason}", + "Discard unsaved changes?": "Відкинути незбережені зміни?", + "Draft": "Чернетка", + "Drop to import into the scene": "Відпустіть, щоб імпортувати в сцену", + "Feet (ft)": "Фути (ft)", + "Format": "Формат", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot відкриває один проєкт за раз; решту файлів проєктів ({n}) залишено закритими.", + "Frame the view after import": "Показати вигляд після імпорту", + "High": "Високе", + "Import": "Імпорт", + "Import All": "Імпортувати все", + "Import Files": "Імпортувати файли", + "Import Model": "Імпорт моделі", + "Import Recent File": "Імпортувати нещодавній файл", + "Imported {name}.": "Імпортовано: {name}.", + "Imported {name}: {parts} parts, {triangles} triangles.": "Імпортовано {name}: деталей {parts}, трикутників {triangles}.", + "Imported {name}: {parts} parts.": "Імпортовано {name}: деталей {parts}.", + "Importing": "Імпорт", + "In this file": "У цьому файлі", + "Inches (in)": "Дюйми (in)", + "Making materials": "Створення матеріалів", + "Materials": "Матеріали", + "Medium": "Середнє", + "Merge into one group": "Об'єднати в одну групу", + "Metres (m)": "Метри (m)", + "Millimetres (mm)": "Міліметри (mm)", + "No Recent Imports": "Немає нещодавніх імпортів", + "No warnings.": "Попереджень немає.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Імпортувати нічого: FormShot імпортує файли GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP та IGES.", + "One file beside it": "Один файл поруч", + "Opening {name} will close the open project and discard its unsaved changes.": "Відкриття {name} закриє поточний проєкт і відкине його незбережені зміни.", + "Options": "Параметри", + "Parts": "Деталі", + "Placing in the scene": "Розміщення в сцені", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Заново прочитати вихідні файли вибраних деталей (або всіх імпортованих), зберігши їхні матеріали.", + "Reading the file": "Читання файлу", + "Reading the file...": "Читання файлу...", + "Recent Imports": "Нещодавні імпорти", + "Reimport": "Імпортувати заново", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Повторний імпорт: оновлено {matched}, нових {added}, приховано {hidden}.", + "Send model files to FormShot and import them into the scene with options.": "Надішліть файли моделей до FormShot та імпортуйте їх у сцену з параметрами.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Кілька файлів імпортуються по черзі. Буфери, матеріали та текстури поруч із моделлю імпортуються разом із нею.", + "Size": "Розмір", + "Stand on the floor": "Поставити на підлогу", + "Tessellating CAD surfaces": "Тесселяція CAD-поверхонь", + "The engine decides from the file.": "Рушій визначить за файлом.", + "The engine did not start an import job": "Рушій не запустив завдання імпорту", + "The engine did not start in time, so the files FormShot was given were not opened.": "Рушій не запустився вчасно, тому файли, передані FormShot, не було відкрито.", + "The file says it is in {unit}.": "У файлі вказано: {unit}.", + "The import failed": "Імпорт не вдався", + "The import goes on; the files after it were not imported.": "Імпорт триває; наступні за ним файли не було імпортовано.", + "The import of {name} was cancelled.": "Імпорт {name} скасовано.", + "The upload failed ({status})": "Не вдалося завантажити ({status})", + "The upload was cancelled": "Завантаження скасовано", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Цей рушій не вміє заглядати у файл перед імпортом, тому підсумок залишається порожнім.", + "This engine cannot stop an import once it has started": "Цей рушій не може зупинити імпорт після його запуску", + "This engine imports in one step, so there is no progress to show or stop.": "Цей рушій імпортує за один крок, тому показувати й зупиняти нічого.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "У цьому файлі не вказано одиниць вимірювання. FormShot припустив {unit} за розміром; перевірте перед імпортом.", + "Triangles": "Трикутники", + "Ultra": "Ультра", + "Units": "Одиниці", + "Up axis": "Верхня вісь", + "Up axis in file": "Верхня вісь у файлі", + "Uploading": "Завантаження", + "Y is up": "Угору спрямована вісь Y", + "Z is up": "Угору спрямована вісь Z", + "centimetres": "сантиметри", + "feet": "фути", + "inches": "дюйми", + "metres": "метри", + "millimetres": "міліметри", + "{i} of {n}": "{i} із {n}", + "{n} files beside it": "Файлів поруч: {n}", + "{n} files were not imported.": "Не імпортовано файлів: {n}.", + "{n} warnings; the Scene page lists the parts.": "Попереджень: {n}; сторінка «Сцена» перелічує деталі." +} diff --git a/frontend/src/i18n/modules/import/vi.json b/frontend/src/i18n/modules/import/vi.json new file mode 100644 index 00000000..760a2c64 --- /dev/null +++ b/frontend/src/i18n/modules/import/vi.json @@ -0,0 +1,90 @@ +{ + "3D models": "Mô hình 3D", + "Automatic": "Tự động", + "CAD quality": "Chất lượng CAD", + "Centimetres (cm)": "Xentimét (cm)", + "Centre on the origin": "Căn giữa tại gốc tọa độ", + "Choose model files and import them into the scene with options.": "Chọn tệp mô hình và nhập vào cảnh với các tùy chọn.", + "Cleaning up meshes": "Đang dọn dẹp mesh", + "Clear Recent Imports": "Xóa danh sách nhập gần đây", + "Could not import the file: {reason}": "Không thể nhập tệp: {reason}", + "Could not import {name}: {reason}": "Không thể nhập {name}: {reason}", + "Could not open {name}: {reason}": "Không thể mở {name}: {reason}", + "Could not read the file: {reason}": "Không thể đọc tệp: {reason}", + "Could not reimport: {reason}": "Không thể nhập lại: {reason}", + "Could not send the file: {reason}": "Không thể gửi tệp: {reason}", + "Discard unsaved changes?": "Bỏ các thay đổi chưa lưu?", + "Draft": "Bản nháp", + "Drop to import into the scene": "Thả vào để nhập vào cảnh", + "Feet (ft)": "Foot (ft)", + "Format": "Định dạng", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot mở từng dự án một nên {n} tệp dự án khác chưa được mở.", + "Frame the view after import": "Căn khung nhìn sau khi nhập", + "High": "Cao", + "Import": "Nhập", + "Import All": "Nhập tất cả", + "Import Files": "Nhập tệp", + "Import Model": "Nhập mô hình", + "Import Recent File": "Nhập tệp gần đây", + "Imported {name}.": "Đã nhập {name}.", + "Imported {name}: {parts} parts, {triangles} triangles.": "Đã nhập {name}: {parts} bộ phận, {triangles} tam giác.", + "Imported {name}: {parts} parts.": "Đã nhập {name}: {parts} bộ phận.", + "Importing": "Đang nhập", + "In this file": "Trong tệp này", + "Inches (in)": "Inch (in)", + "Making materials": "Đang tạo vật liệu", + "Materials": "Vật liệu", + "Medium": "Trung bình", + "Merge into one group": "Gộp thành một nhóm", + "Metres (m)": "Mét (m)", + "Millimetres (mm)": "Milimét (mm)", + "No Recent Imports": "Chưa có tệp nhập gần đây", + "No warnings.": "Không có cảnh báo.", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "Không có gì để nhập: FormShot nhập các tệp GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP và IGES.", + "One file beside it": "Một tệp đi kèm", + "Opening {name} will close the open project and discard its unsaved changes.": "Mở {name} sẽ đóng dự án đang mở và bỏ các thay đổi chưa lưu của dự án đó.", + "Options": "Tùy chọn", + "Parts": "Bộ phận", + "Placing in the scene": "Đang đặt vào cảnh", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "Đọc lại các tệp nguồn của những bộ phận đã chọn (hoặc của mọi bộ phận đã nhập), giữ nguyên vật liệu.", + "Reading the file": "Đang đọc tệp", + "Reading the file...": "Đang đọc tệp...", + "Recent Imports": "Nhập gần đây", + "Reimport": "Nhập lại", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "Đã nhập lại: cập nhật {matched}, mới {added}, ẩn {hidden}.", + "Send model files to FormShot and import them into the scene with options.": "Gửi tệp mô hình tới FormShot và nhập vào cảnh với các tùy chọn.", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "Nhiều tệp sẽ được nhập lần lượt. Bộ đệm, vật liệu và kết cấu nằm cạnh mô hình sẽ đi kèm theo.", + "Size": "Kích thước", + "Stand on the floor": "Đặt lên sàn", + "Tessellating CAD surfaces": "Đang chia bề mặt CAD thành tam giác", + "The engine decides from the file.": "Công cụ tự quyết định dựa trên tệp.", + "The engine did not start an import job": "Công cụ không bắt đầu tác vụ nhập", + "The engine did not start in time, so the files FormShot was given were not opened.": "Công cụ không khởi động kịp thời nên các tệp gửi cho FormShot chưa được mở.", + "The file says it is in {unit}.": "Tệp cho biết đơn vị là {unit}.", + "The import failed": "Nhập không thành công", + "The import goes on; the files after it were not imported.": "Quá trình nhập vẫn tiếp tục; các tệp phía sau chưa được nhập.", + "The import of {name} was cancelled.": "Đã hủy việc nhập {name}.", + "The upload failed ({status})": "Tải lên không thành công ({status})", + "The upload was cancelled": "Đã hủy tải lên", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "Công cụ này không thể xem bên trong tệp trước khi nhập nên phần tóm tắt để trống.", + "This engine cannot stop an import once it has started": "Công cụ này không thể dừng việc nhập khi đã bắt đầu", + "This engine imports in one step, so there is no progress to show or stop.": "Công cụ này nhập trong một bước nên không có tiến trình để hiển thị hay dừng.", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "Tệp này không ghi đơn vị. FormShot đoán là {unit} theo kích thước; hãy kiểm tra trước khi nhập.", + "Triangles": "Tam giác", + "Ultra": "Cực cao", + "Units": "Đơn vị", + "Up axis": "Trục hướng lên", + "Up axis in file": "Trục hướng lên trong tệp", + "Uploading": "Đang tải lên", + "Y is up": "Y hướng lên", + "Z is up": "Z hướng lên", + "centimetres": "xentimét", + "feet": "foot", + "inches": "inch", + "metres": "mét", + "millimetres": "milimét", + "{i} of {n}": "{i} trên {n}", + "{n} files beside it": "{n} tệp đi kèm", + "{n} files were not imported.": "{n} tệp chưa được nhập.", + "{n} warnings; the Scene page lists the parts.": "{n} cảnh báo; trang Cảnh liệt kê các bộ phận." +} diff --git a/frontend/src/i18n/modules/import/zh-CN.json b/frontend/src/i18n/modules/import/zh-CN.json new file mode 100644 index 00000000..2ad1ae86 --- /dev/null +++ b/frontend/src/i18n/modules/import/zh-CN.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D 模型", + "Automatic": "自动", + "CAD quality": "CAD 质量", + "Centimetres (cm)": "厘米 (cm)", + "Centre on the origin": "以原点为中心", + "Choose model files and import them into the scene with options.": "选择模型文件,并通过选项将其导入场景。", + "Cleaning up meshes": "正在清理网格", + "Clear Recent Imports": "清除最近导入", + "Could not import the file: {reason}": "无法导入文件:{reason}", + "Could not import {name}: {reason}": "无法导入 {name}:{reason}", + "Could not open {name}: {reason}": "无法打开 {name}:{reason}", + "Could not read the file: {reason}": "无法读取文件:{reason}", + "Could not reimport: {reason}": "无法重新导入:{reason}", + "Could not send the file: {reason}": "无法发送文件:{reason}", + "Discard unsaved changes?": "要放弃未保存的更改吗?", + "Draft": "草稿", + "Drop to import into the scene": "拖放以导入场景", + "Feet (ft)": "英尺 (ft)", + "Format": "格式", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot 一次只能打开一个项目,其他 {n} 个项目文件未打开。", + "Frame the view after import": "导入后调整视图", + "High": "高", + "Import": "导入", + "Import All": "全部导入", + "Import Files": "导入文件", + "Import Model": "导入模型", + "Import Recent File": "导入最近的文件", + "Imported {name}.": "已导入 {name}。", + "Imported {name}: {parts} parts, {triangles} triangles.": "已导入 {name}:{parts} 个部件,{triangles} 个三角形。", + "Imported {name}: {parts} parts.": "已导入 {name}:{parts} 个部件。", + "Importing": "正在导入", + "In this file": "此文件中", + "Inches (in)": "英寸 (in)", + "Making materials": "正在创建材质", + "Materials": "材质", + "Medium": "中", + "Merge into one group": "合并为一个组", + "Metres (m)": "米 (m)", + "Millimetres (mm)": "毫米 (mm)", + "No Recent Imports": "没有最近导入", + "No warnings.": "没有警告。", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "没有可导入的内容:FormShot 可导入 GLB、glTF、OBJ、STL、PLY、3MF、FBX、STEP 和 IGES 文件。", + "One file beside it": "旁边的 1 个文件", + "Opening {name} will close the open project and discard its unsaved changes.": "打开 {name} 将关闭当前打开的项目,并放弃其中未保存的更改。", + "Options": "选项", + "Parts": "部件", + "Placing in the scene": "正在放入场景", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "重新读取所选部件(或所有已导入部件)的源文件,并保留其材质。", + "Reading the file": "正在读取文件", + "Reading the file...": "正在读取文件...", + "Recent Imports": "最近导入", + "Reimport": "重新导入", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "已重新导入:更新 {matched} 个,新增 {added} 个,隐藏 {hidden} 个。", + "Send model files to FormShot and import them into the scene with options.": "将模型文件发送到 FormShot,并通过选项导入场景。", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "多个文件会依次导入。模型旁边的缓冲区、材质和纹理会一并导入。", + "Size": "尺寸", + "Stand on the floor": "放在地面上", + "Tessellating CAD surfaces": "正在对 CAD 曲面进行细分", + "The engine decides from the file.": "由引擎根据文件决定。", + "The engine did not start an import job": "引擎没有启动导入任务", + "The engine did not start in time, so the files FormShot was given were not opened.": "引擎未能及时启动,因此交给 FormShot 的文件没有被打开。", + "The file says it is in {unit}.": "文件中注明的单位是 {unit}。", + "The import failed": "导入失败", + "The import goes on; the files after it were not imported.": "导入仍在继续,其后的文件没有导入。", + "The import of {name} was cancelled.": "已取消导入 {name}。", + "The upload failed ({status})": "上传失败 ({status})", + "The upload was cancelled": "上传已取消", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "此引擎无法在导入前查看文件内部,因此摘要保持为空。", + "This engine cannot stop an import once it has started": "此引擎在导入开始后无法停止", + "This engine imports in one step, so there is no progress to show or stop.": "此引擎一次性完成导入,因此没有可显示或可停止的进度。", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "此文件没有注明单位。FormShot 根据其尺寸推测为 {unit},请在导入前确认。", + "Triangles": "三角形", + "Ultra": "超高", + "Units": "单位", + "Up axis": "向上轴", + "Up axis in file": "文件中的向上轴", + "Uploading": "正在上传", + "Y is up": "Y 轴向上", + "Z is up": "Z 轴向上", + "centimetres": "厘米", + "feet": "英尺", + "inches": "英寸", + "metres": "米", + "millimetres": "毫米", + "{i} of {n}": "第 {i} 个,共 {n} 个", + "{n} files beside it": "旁边的 {n} 个文件", + "{n} files were not imported.": "有 {n} 个文件未导入。", + "{n} warnings; the Scene page lists the parts.": "{n} 条警告;场景页列出了这些部件。" +} diff --git a/frontend/src/i18n/modules/import/zh-TW.json b/frontend/src/i18n/modules/import/zh-TW.json new file mode 100644 index 00000000..8656d4a3 --- /dev/null +++ b/frontend/src/i18n/modules/import/zh-TW.json @@ -0,0 +1,90 @@ +{ + "3D models": "3D 模型", + "Automatic": "自動", + "CAD quality": "CAD 品質", + "Centimetres (cm)": "公分 (cm)", + "Centre on the origin": "以原點為中心", + "Choose model files and import them into the scene with options.": "選擇模型檔案,並透過選項將其匯入場景。", + "Cleaning up meshes": "正在整理網格", + "Clear Recent Imports": "清除最近匯入", + "Could not import the file: {reason}": "無法匯入檔案:{reason}", + "Could not import {name}: {reason}": "無法匯入 {name}:{reason}", + "Could not open {name}: {reason}": "無法開啟 {name}:{reason}", + "Could not read the file: {reason}": "無法讀取檔案:{reason}", + "Could not reimport: {reason}": "無法重新匯入:{reason}", + "Could not send the file: {reason}": "無法傳送檔案:{reason}", + "Discard unsaved changes?": "要捨棄未儲存的變更嗎?", + "Draft": "草稿", + "Drop to import into the scene": "拖放以匯入場景", + "Feet (ft)": "英尺 (ft)", + "Format": "格式", + "FormShot opens one project at a time; {n} other project files were left unopened.": "FormShot 一次只能開啟一個專案,其他 {n} 個專案檔案未開啟。", + "Frame the view after import": "匯入後調整檢視", + "High": "高", + "Import": "匯入", + "Import All": "全部匯入", + "Import Files": "匯入檔案", + "Import Model": "匯入模型", + "Import Recent File": "匯入最近的檔案", + "Imported {name}.": "已匯入 {name}。", + "Imported {name}: {parts} parts, {triangles} triangles.": "已匯入 {name}:{parts} 個零件,{triangles} 個三角形。", + "Imported {name}: {parts} parts.": "已匯入 {name}:{parts} 個零件。", + "Importing": "正在匯入", + "In this file": "此檔案中", + "Inches (in)": "英吋 (in)", + "Making materials": "正在建立材質", + "Materials": "材質", + "Medium": "中", + "Merge into one group": "合併為一個群組", + "Metres (m)": "公尺 (m)", + "Millimetres (mm)": "公釐 (mm)", + "No Recent Imports": "沒有最近匯入", + "No warnings.": "沒有警告。", + "Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.": "沒有可匯入的內容:FormShot 可匯入 GLB、glTF、OBJ、STL、PLY、3MF、FBX、STEP 和 IGES 檔案。", + "One file beside it": "旁邊的 1 個檔案", + "Opening {name} will close the open project and discard its unsaved changes.": "開啟 {name} 將關閉目前開啟的專案,並捨棄其中未儲存的變更。", + "Options": "選項", + "Parts": "零件", + "Placing in the scene": "正在放入場景", + "Read the source files of the selected parts (or of every imported part) again, keeping their materials.": "重新讀取所選零件(或所有已匯入零件)的來源檔案,並保留其材質。", + "Reading the file": "正在讀取檔案", + "Reading the file...": "正在讀取檔案...", + "Recent Imports": "最近匯入", + "Reimport": "重新匯入", + "Reimported: updated {matched}, new {added}, hidden {hidden}.": "已重新匯入:更新 {matched} 個,新增 {added} 個,隱藏 {hidden} 個。", + "Send model files to FormShot and import them into the scene with options.": "將模型檔案傳送到 FormShot,並透過選項匯入場景。", + "Several files import one after another. Buffers, materials and textures beside a model go with it.": "多個檔案會依序匯入。模型旁邊的緩衝區、材質和紋理會一併匯入。", + "Size": "尺寸", + "Stand on the floor": "放在地面上", + "Tessellating CAD surfaces": "正在細分 CAD 曲面", + "The engine decides from the file.": "由引擎根據檔案決定。", + "The engine did not start an import job": "引擎沒有啟動匯入工作", + "The engine did not start in time, so the files FormShot was given were not opened.": "引擎未能及時啟動,因此交給 FormShot 的檔案沒有被開啟。", + "The file says it is in {unit}.": "檔案中註明的單位是 {unit}。", + "The import failed": "匯入失敗", + "The import goes on; the files after it were not imported.": "匯入仍在繼續,其後的檔案沒有匯入。", + "The import of {name} was cancelled.": "已取消匯入 {name}。", + "The upload failed ({status})": "上傳失敗 ({status})", + "The upload was cancelled": "上傳已取消", + "This engine cannot look inside a file before importing it, so the summary stays empty.": "此引擎無法在匯入前查看檔案內部,因此摘要保持為空。", + "This engine cannot stop an import once it has started": "此引擎在匯入開始後無法停止", + "This engine imports in one step, so there is no progress to show or stop.": "此引擎一次完成匯入,因此沒有可顯示或可停止的進度。", + "This file does not say its units. FormShot guessed {unit} from its size; check it before importing.": "此檔案沒有註明單位。FormShot 根據其尺寸推測為 {unit},請在匯入前確認。", + "Triangles": "三角形", + "Ultra": "超高", + "Units": "單位", + "Up axis": "向上軸", + "Up axis in file": "檔案中的向上軸", + "Uploading": "正在上傳", + "Y is up": "Y 軸向上", + "Z is up": "Z 軸向上", + "centimetres": "公分", + "feet": "英尺", + "inches": "英吋", + "metres": "公尺", + "millimetres": "公釐", + "{i} of {n}": "第 {i} 個,共 {n} 個", + "{n} files beside it": "旁邊的 {n} 個檔案", + "{n} files were not imported.": "有 {n} 個檔案未匯入。", + "{n} warnings; the Scene page lists the parts.": "{n} 則警告;場景頁列出了這些零件。" +} diff --git a/frontend/src/i18n/modules/labels/cs.json b/frontend/src/i18n/modules/labels/cs.json new file mode 100644 index 00000000..8c2d4d80 --- /dev/null +++ b/frontend/src/i18n/modules/labels/cs.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Přidat štítek ze souboru s obrázkem", + "Add from Image": "Přidat z obrázku", + "Choose": "Vybrat", + "Choose Label Image": "Vybrat obrázek štítku", + "Choose a material to edit its labels.": "Vyberte materiál, jehož štítky chcete upravit.", + "Choose an image first": "Nejprve vyberte obrázek", + "Choose the label image": "Vyberte obrázek štítku", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Výběr obrázku v prohlížeči vyžaduje nahrávání textur službou (POST /api/textures), které tato služba zatím nenabízí.", + "Click a point on the part to put the label there": "Klikněte na bod na dílu, kam se má štítek umístit", + "Click the part where the label goes. Escape cancels.": "Klikněte na díl, kam štítek patří. Esc zruší akci.", + "Depth": "Hloubka", + "Drag to reorder": "Přetažením změníte pořadí", + "Height": "Výška", + "Hide Label": "Skrýt štítek", + "Image": "Obrázek", + "Images": "Obrázky", + "Keep the image proportions": "Zachovat poměr stran obrázku", + "Label": "Štítek", + "Label added. Use Place on Surface to put it on the part.": "Štítek byl přidán. Pomocí Umístit na povrch jej položíte na díl.", + "Label placed.": "Štítek byl umístěn.", + "Labels": "Štítky", + "Metalness": "Kovovost", + "Name": "Název", + "No image": "Žádný obrázek", + "No labels yet. Add an image, then place it on the part.": "Zatím žádné štítky. Přidejte obrázek a umístěte ho na díl.", + "Nothing under the pointer; click a part that wears this material.": "Pod ukazatelem nic není; klikněte na díl s tímto materiálem.", + "Opacity": "Neprůhlednost", + "Own metalness": "Vlastní kovovost", + "Own roughness": "Vlastní drsnost", + "Place on Surface": "Umístit na povrch", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Umístění vyžaduje viewport a příkazy enginu view.pick a scene.meshes.", + "Print on both sides": "Tisk na obě strany", + "Remove Label": "Odebrat štítek", + "Rotation": "Rotace", + "Roughness": "Drsnost", + "Show Label": "Zobrazit štítek", + "That part does not wear this material.": "Tento díl tento materiál nemá.", + "The image could not be uploaded": "Obrázek se nepodařilo nahrát", + "The picked part could not be read.": "Vybraný díl se nepodařilo přečíst.", + "Width": "Šířka" +} diff --git a/frontend/src/i18n/modules/labels/da.json b/frontend/src/i18n/modules/labels/da.json new file mode 100644 index 00000000..2d0415c5 --- /dev/null +++ b/frontend/src/i18n/modules/labels/da.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Tilføj en etiket fra en billedfil", + "Add from Image": "Tilføj fra billede", + "Choose": "Vælg", + "Choose Label Image": "Vælg etiketbillede", + "Choose a material to edit its labels.": "Vælg et materiale for at redigere dets etiketter.", + "Choose an image first": "Vælg et billede først", + "Choose the label image": "Vælg etiketbilledet", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "At vælge et billede i browseren kræver tjenestens teksturupload (POST /api/textures), som denne tjeneste endnu ikke tilbyder.", + "Click a point on the part to put the label there": "Klik på et punkt på delen for at placere etiketten der", + "Click the part where the label goes. Escape cancels.": "Klik på den del, hvor etiketten skal sidde. Esc annullerer.", + "Depth": "Dybde", + "Drag to reorder": "Træk for at ændre rækkefølgen", + "Height": "Højde", + "Hide Label": "Skjul etiket", + "Image": "Billede", + "Images": "Billeder", + "Keep the image proportions": "Behold billedets proportioner", + "Label": "Etiket", + "Label added. Use Place on Surface to put it on the part.": "Etiket tilføjet. Brug Placer på overflade for at sætte den på delen.", + "Label placed.": "Etiket placeret.", + "Labels": "Etiketter", + "Metalness": "Metalness", + "Name": "Navn", + "No image": "Intet billede", + "No labels yet. Add an image, then place it on the part.": "Ingen etiketter endnu. Tilføj et billede, og placer det derefter på delen.", + "Nothing under the pointer; click a part that wears this material.": "Intet under markøren; klik på en del, der har dette materiale.", + "Opacity": "Opacitet", + "Own metalness": "Egen metalness", + "Own roughness": "Egen ruhed", + "Place on Surface": "Placer på overflade", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Placering kræver viewporten og motorkommandoerne view.pick og scene.meshes.", + "Print on both sides": "Udskriv på begge sider", + "Remove Label": "Fjern etiket", + "Rotation": "Rotation", + "Roughness": "Ruhed", + "Show Label": "Vis etiket", + "That part does not wear this material.": "Den del har ikke dette materiale.", + "The image could not be uploaded": "Billedet kunne ikke uploades", + "The picked part could not be read.": "Den valgte del kunne ikke læses.", + "Width": "Bredde" +} diff --git a/frontend/src/i18n/modules/labels/de.json b/frontend/src/i18n/modules/labels/de.json new file mode 100644 index 00000000..81e0607a --- /dev/null +++ b/frontend/src/i18n/modules/labels/de.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Eine Beschriftung aus einer Bilddatei hinzufügen", + "Add from Image": "Aus Bild hinzufügen", + "Choose": "Auswählen", + "Choose Label Image": "Beschriftungsbild auswählen", + "Choose a material to edit its labels.": "Wähle ein Material, um seine Beschriftungen zu bearbeiten.", + "Choose an image first": "Wähle zuerst ein Bild", + "Choose the label image": "Wähle das Beschriftungsbild", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Für die Bildauswahl im Browser wird der Textur-Upload des Dienstes (POST /api/textures) benötigt, den dieser Dienst noch nicht anbietet.", + "Click a point on the part to put the label there": "Klicke auf einen Punkt des Teils, um die Beschriftung dort zu platzieren", + "Click the part where the label goes. Escape cancels.": "Klicke auf das Teil, auf das die Beschriftung kommt. Esc bricht ab.", + "Depth": "Tiefe", + "Drag to reorder": "Zum Umsortieren ziehen", + "Height": "Höhe", + "Hide Label": "Beschriftung ausblenden", + "Image": "Bild", + "Images": "Bilder", + "Keep the image proportions": "Bildproportionen beibehalten", + "Label": "Beschriftung", + "Label added. Use Place on Surface to put it on the part.": "Beschriftung hinzugefügt. Mit „Auf Oberfläche platzieren“ bringst du sie auf das Teil.", + "Label placed.": "Beschriftung platziert.", + "Labels": "Beschriftungen", + "Metalness": "Metallizität", + "Name": "Name", + "No image": "Kein Bild", + "No labels yet. Add an image, then place it on the part.": "Noch keine Beschriftungen. Füge ein Bild hinzu und platziere es dann auf dem Teil.", + "Nothing under the pointer; click a part that wears this material.": "Unter dem Zeiger ist nichts; klicke auf ein Teil mit diesem Material.", + "Opacity": "Deckkraft", + "Own metalness": "Eigene Metallizität", + "Own roughness": "Eigene Rauheit", + "Place on Surface": "Auf Oberfläche platzieren", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Zum Platzieren werden der Viewport und die Engine-Befehle view.pick und scene.meshes benötigt.", + "Print on both sides": "Beidseitig bedrucken", + "Remove Label": "Beschriftung entfernen", + "Rotation": "Drehung", + "Roughness": "Rauheit", + "Show Label": "Beschriftung anzeigen", + "That part does not wear this material.": "Dieses Teil hat dieses Material nicht.", + "The image could not be uploaded": "Das Bild konnte nicht hochgeladen werden", + "The picked part could not be read.": "Das gewählte Teil konnte nicht gelesen werden.", + "Width": "Breite" +} diff --git a/frontend/src/i18n/modules/labels/es-MX.json b/frontend/src/i18n/modules/labels/es-MX.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/labels/es-MX.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/labels/es.json b/frontend/src/i18n/modules/labels/es.json new file mode 100644 index 00000000..ad109b49 --- /dev/null +++ b/frontend/src/i18n/modules/labels/es.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Añadir una etiqueta desde un archivo de imagen", + "Add from Image": "Añadir desde imagen", + "Choose": "Elegir", + "Choose Label Image": "Elegir imagen de la etiqueta", + "Choose a material to edit its labels.": "Elige un material para editar sus etiquetas.", + "Choose an image first": "Elige primero una imagen", + "Choose the label image": "Elige la imagen de la etiqueta", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Elegir una imagen en el navegador requiere la subida de texturas del servicio (POST /api/textures), que este servicio aún no ofrece.", + "Click a point on the part to put the label there": "Haz clic en un punto de la pieza para colocar allí la etiqueta", + "Click the part where the label goes. Escape cancels.": "Haz clic en la pieza donde va la etiqueta. Esc cancela.", + "Depth": "Profundidad", + "Drag to reorder": "Arrastra para reordenar", + "Height": "Altura", + "Hide Label": "Ocultar etiqueta", + "Image": "Imagen", + "Images": "Imágenes", + "Keep the image proportions": "Mantener las proporciones de la imagen", + "Label": "Etiqueta", + "Label added. Use Place on Surface to put it on the part.": "Etiqueta añadida. Usa Colocar en la superficie para ponerla en la pieza.", + "Label placed.": "Etiqueta colocada.", + "Labels": "Etiquetas", + "Metalness": "Metalicidad", + "Name": "Nombre", + "No image": "Sin imagen", + "No labels yet. Add an image, then place it on the part.": "Aún no hay etiquetas. Añade una imagen y colócala en la pieza.", + "Nothing under the pointer; click a part that wears this material.": "No hay nada bajo el puntero; haz clic en una pieza que lleve este material.", + "Opacity": "Opacidad", + "Own metalness": "Metalicidad propia", + "Own roughness": "Rugosidad propia", + "Place on Surface": "Colocar en la superficie", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Colocar requiere el viewport y los comandos del motor view.pick y scene.meshes.", + "Print on both sides": "Imprimir por ambas caras", + "Remove Label": "Quitar etiqueta", + "Rotation": "Rotación", + "Roughness": "Rugosidad", + "Show Label": "Mostrar etiqueta", + "That part does not wear this material.": "Esa pieza no lleva este material.", + "The image could not be uploaded": "No se pudo subir la imagen", + "The picked part could not be read.": "No se pudo leer la pieza elegida.", + "Width": "Anchura" +} diff --git a/frontend/src/i18n/modules/labels/fi.json b/frontend/src/i18n/modules/labels/fi.json new file mode 100644 index 00000000..a0f8515d --- /dev/null +++ b/frontend/src/i18n/modules/labels/fi.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Lisää tarra kuvatiedostosta", + "Add from Image": "Lisää kuvasta", + "Choose": "Valitse", + "Choose Label Image": "Valitse tarrakuva", + "Choose a material to edit its labels.": "Valitse materiaali muokataksesi sen tarroja.", + "Choose an image first": "Valitse ensin kuva", + "Choose the label image": "Valitse tarran kuva", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Kuvan valinta selaimessa vaatii palvelun tekstuurilatauksen (POST /api/textures), jota tämä palvelu ei vielä tarjoa.", + "Click a point on the part to put the label there": "Napsauta kappaleen pistettä sijoittaaksesi tarran siihen", + "Click the part where the label goes. Escape cancels.": "Napsauta kappaletta, johon tarra tulee. Esc peruu.", + "Depth": "Syvyys", + "Drag to reorder": "Järjestä vetämällä", + "Height": "Korkeus", + "Hide Label": "Piilota tarra", + "Image": "Kuva", + "Images": "Kuvat", + "Keep the image proportions": "Säilytä kuvan mittasuhteet", + "Label": "Tarra", + "Label added. Use Place on Surface to put it on the part.": "Tarra lisätty. Käytä toimintoa Sijoita pinnalle asettaaksesi sen kappaleeseen.", + "Label placed.": "Tarra sijoitettu.", + "Labels": "Tarrat", + "Metalness": "Metallisuus", + "Name": "Nimi", + "No image": "Ei kuvaa", + "No labels yet. Add an image, then place it on the part.": "Ei vielä tarroja. Lisää kuva ja sijoita se sitten kappaleeseen.", + "Nothing under the pointer; click a part that wears this material.": "Osoittimen alla ei ole mitään; napsauta kappaletta, jolla on tämä materiaali.", + "Opacity": "Peittävyys", + "Own metalness": "Oma metallisuus", + "Own roughness": "Oma karheus", + "Place on Surface": "Sijoita pinnalle", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Sijoittaminen vaatii näkymän ja moottorin komennot view.pick ja scene.meshes.", + "Print on both sides": "Tulosta molemmille puolille", + "Remove Label": "Poista tarra", + "Rotation": "Kierto", + "Roughness": "Karheus", + "Show Label": "Näytä tarra", + "That part does not wear this material.": "Tällä kappaleella ei ole tätä materiaalia.", + "The image could not be uploaded": "Kuvaa ei voitu ladata", + "The picked part could not be read.": "Valittua kappaletta ei voitu lukea.", + "Width": "Leveys" +} diff --git a/frontend/src/i18n/modules/labels/fr-CA.json b/frontend/src/i18n/modules/labels/fr-CA.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/labels/fr-CA.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/labels/fr.json b/frontend/src/i18n/modules/labels/fr.json new file mode 100644 index 00000000..437b4186 --- /dev/null +++ b/frontend/src/i18n/modules/labels/fr.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Ajouter une étiquette à partir d'un fichier image", + "Add from Image": "Ajouter depuis une image", + "Choose": "Choisir", + "Choose Label Image": "Choisir l'image de l'étiquette", + "Choose a material to edit its labels.": "Choisissez un matériau pour modifier ses étiquettes.", + "Choose an image first": "Choisissez d'abord une image", + "Choose the label image": "Choisir l'image de l'étiquette", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Le choix d'une image dans le navigateur nécessite l'envoi de texture du service (POST /api/textures), que ce service ne propose pas encore.", + "Click a point on the part to put the label there": "Cliquez sur un point de la pièce pour y placer l'étiquette", + "Click the part where the label goes. Escape cancels.": "Cliquez sur la pièce qui doit recevoir l'étiquette. Échap annule.", + "Depth": "Profondeur", + "Drag to reorder": "Glisser pour réordonner", + "Height": "Hauteur", + "Hide Label": "Masquer l'étiquette", + "Image": "Image", + "Images": "Images", + "Keep the image proportions": "Conserver les proportions de l'image", + "Label": "Étiquette", + "Label added. Use Place on Surface to put it on the part.": "Étiquette ajoutée. Utilisez Placer sur la surface pour la poser sur la pièce.", + "Label placed.": "Étiquette placée.", + "Labels": "Étiquettes", + "Metalness": "Métallicité", + "Name": "Nom", + "No image": "Aucune image", + "No labels yet. Add an image, then place it on the part.": "Aucune étiquette pour l'instant. Ajoutez une image, puis placez-la sur la pièce.", + "Nothing under the pointer; click a part that wears this material.": "Rien sous le pointeur ; cliquez sur une pièce qui porte ce matériau.", + "Opacity": "Opacité", + "Own metalness": "Métallicité propre", + "Own roughness": "Rugosité propre", + "Place on Surface": "Placer sur la surface", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Le placement nécessite le viewport et les commandes du moteur view.pick et scene.meshes.", + "Print on both sides": "Imprimer des deux côtés", + "Remove Label": "Supprimer l'étiquette", + "Rotation": "Rotation", + "Roughness": "Rugosité", + "Show Label": "Afficher l'étiquette", + "That part does not wear this material.": "Cette pièce ne porte pas ce matériau.", + "The image could not be uploaded": "L'image n'a pas pu être envoyée", + "The picked part could not be read.": "La pièce choisie n'a pas pu être lue.", + "Width": "Largeur" +} diff --git a/frontend/src/i18n/modules/labels/hu.json b/frontend/src/i18n/modules/labels/hu.json new file mode 100644 index 00000000..8c7ca721 --- /dev/null +++ b/frontend/src/i18n/modules/labels/hu.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Címke hozzáadása képfájlból", + "Add from Image": "Hozzáadás képből", + "Choose": "Kiválasztás", + "Choose Label Image": "Címkekép kiválasztása", + "Choose a material to edit its labels.": "Válasszon anyagot a címkéinek szerkesztéséhez.", + "Choose an image first": "Először válasszon képet", + "Choose the label image": "Válassza ki a címke képét", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "A kép böngészőből való kiválasztásához a szolgáltatás textúrafeltöltésére (POST /api/textures) van szükség, amelyet ez a szolgáltatás még nem kínál.", + "Click a point on the part to put the label there": "Kattintson az alkatrész egy pontjára, hogy ott helyezze el a címkét", + "Click the part where the label goes. Escape cancels.": "Kattintson arra az alkatrészre, ahová a címke kerül. Az Esc megszakítja.", + "Depth": "Mélység", + "Drag to reorder": "Húzással átrendezhető", + "Height": "Magasság", + "Hide Label": "Címke elrejtése", + "Image": "Kép", + "Images": "Képek", + "Keep the image proportions": "A kép arányainak megtartása", + "Label": "Címke", + "Label added. Use Place on Surface to put it on the part.": "A címke hozzáadva. A Felületre helyezés paranccsal teheti az alkatrészre.", + "Label placed.": "A címke elhelyezve.", + "Labels": "Címkék", + "Metalness": "Fémesség", + "Name": "Név", + "No image": "Nincs kép", + "No labels yet. Add an image, then place it on the part.": "Még nincsenek címkék. Adjon hozzá egy képet, majd helyezze az alkatrészre.", + "Nothing under the pointer; click a part that wears this material.": "Nincs semmi a mutató alatt; kattintson egy olyan alkatrészre, amely ezt az anyagot viseli.", + "Opacity": "Átlátszatlanság", + "Own metalness": "Saját fémesség", + "Own roughness": "Saját érdesség", + "Place on Surface": "Felületre helyezés", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Az elhelyezéshez a nézetablak és a view.pick, valamint a scene.meshes motorparancsok szükségesek.", + "Print on both sides": "Nyomtatás mindkét oldalra", + "Remove Label": "Címke eltávolítása", + "Rotation": "Elforgatás", + "Roughness": "Érdesség", + "Show Label": "Címke megjelenítése", + "That part does not wear this material.": "Ez az alkatrész nem viseli ezt az anyagot.", + "The image could not be uploaded": "A képet nem sikerült feltölteni", + "The picked part could not be read.": "A kiválasztott alkatrészt nem sikerült beolvasni.", + "Width": "Szélesség" +} diff --git a/frontend/src/i18n/modules/labels/id.json b/frontend/src/i18n/modules/labels/id.json new file mode 100644 index 00000000..b493a5fa --- /dev/null +++ b/frontend/src/i18n/modules/labels/id.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Tambahkan label dari file gambar", + "Add from Image": "Tambah dari Gambar", + "Choose": "Pilih", + "Choose Label Image": "Pilih Gambar Label", + "Choose a material to edit its labels.": "Pilih material untuk mengedit labelnya.", + "Choose an image first": "Pilih gambar terlebih dahulu", + "Choose the label image": "Pilih gambar label", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Memilih gambar di browser memerlukan unggahan tekstur layanan (POST /api/textures), yang belum disediakan layanan ini.", + "Click a point on the part to put the label there": "Klik satu titik pada bagian untuk menempatkan label di sana", + "Click the part where the label goes. Escape cancels.": "Klik bagian tempat label dipasang. Esc membatalkan.", + "Depth": "Kedalaman", + "Drag to reorder": "Seret untuk mengurutkan ulang", + "Height": "Tinggi", + "Hide Label": "Sembunyikan Label", + "Image": "Gambar", + "Images": "Gambar", + "Keep the image proportions": "Pertahankan proporsi gambar", + "Label": "Label", + "Label added. Use Place on Surface to put it on the part.": "Label ditambahkan. Gunakan Tempatkan pada Permukaan untuk memasangnya pada bagian.", + "Label placed.": "Label ditempatkan.", + "Labels": "Label", + "Metalness": "Metalness", + "Name": "Nama", + "No image": "Tanpa gambar", + "No labels yet. Add an image, then place it on the part.": "Belum ada label. Tambahkan gambar, lalu tempatkan pada bagian.", + "Nothing under the pointer; click a part that wears this material.": "Tidak ada apa pun di bawah penunjuk; klik bagian yang memakai material ini.", + "Opacity": "Opasitas", + "Own metalness": "Metalness sendiri", + "Own roughness": "Roughness sendiri", + "Place on Surface": "Tempatkan pada Permukaan", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Penempatan memerlukan viewport dan perintah engine view.pick dan scene.meshes.", + "Print on both sides": "Cetak di kedua sisi", + "Remove Label": "Hapus Label", + "Rotation": "Rotasi", + "Roughness": "Roughness", + "Show Label": "Tampilkan Label", + "That part does not wear this material.": "Bagian itu tidak memakai material ini.", + "The image could not be uploaded": "Gambar tidak dapat diunggah", + "The picked part could not be read.": "Bagian yang dipilih tidak dapat dibaca.", + "Width": "Lebar" +} diff --git a/frontend/src/i18n/modules/labels/it.json b/frontend/src/i18n/modules/labels/it.json new file mode 100644 index 00000000..72271808 --- /dev/null +++ b/frontend/src/i18n/modules/labels/it.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Aggiungi un'etichetta da un file immagine", + "Add from Image": "Aggiungi da immagine", + "Choose": "Scegli", + "Choose Label Image": "Scegli immagine dell'etichetta", + "Choose a material to edit its labels.": "Scegli un materiale per modificarne le etichette.", + "Choose an image first": "Scegli prima un'immagine", + "Choose the label image": "Scegli l'immagine dell'etichetta", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "La scelta di un'immagine nel browser richiede il caricamento delle texture del servizio (POST /api/textures), che questo servizio non offre ancora.", + "Click a point on the part to put the label there": "Fai clic su un punto del pezzo per applicarvi l'etichetta", + "Click the part where the label goes. Escape cancels.": "Fai clic sul pezzo dove va l'etichetta. Esc annulla.", + "Depth": "Profondità", + "Drag to reorder": "Trascina per riordinare", + "Height": "Altezza", + "Hide Label": "Nascondi etichetta", + "Image": "Immagine", + "Images": "Immagini", + "Keep the image proportions": "Mantieni le proporzioni dell'immagine", + "Label": "Etichetta", + "Label added. Use Place on Surface to put it on the part.": "Etichetta aggiunta. Usa Posiziona sulla superficie per applicarla al pezzo.", + "Label placed.": "Etichetta posizionata.", + "Labels": "Etichette", + "Metalness": "Metallicità", + "Name": "Nome", + "No image": "Nessuna immagine", + "No labels yet. Add an image, then place it on the part.": "Nessuna etichetta per ora. Aggiungi un'immagine, poi posizionala sul pezzo.", + "Nothing under the pointer; click a part that wears this material.": "Niente sotto il puntatore; fai clic su un pezzo che ha questo materiale.", + "Opacity": "Opacità", + "Own metalness": "Metallicità propria", + "Own roughness": "Rugosità propria", + "Place on Surface": "Posiziona sulla superficie", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Il posizionamento richiede il viewport e i comandi del motore view.pick e scene.meshes.", + "Print on both sides": "Stampa su entrambi i lati", + "Remove Label": "Rimuovi etichetta", + "Rotation": "Rotazione", + "Roughness": "Rugosità", + "Show Label": "Mostra etichetta", + "That part does not wear this material.": "Quel pezzo non ha questo materiale.", + "The image could not be uploaded": "Impossibile caricare l'immagine", + "The picked part could not be read.": "Impossibile leggere il pezzo scelto.", + "Width": "Larghezza" +} diff --git a/frontend/src/i18n/modules/labels/ja.json b/frontend/src/i18n/modules/labels/ja.json new file mode 100644 index 00000000..2d4379fe --- /dev/null +++ b/frontend/src/i18n/modules/labels/ja.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "画像ファイルからラベルを追加します", + "Add from Image": "画像から追加", + "Choose": "選択", + "Choose Label Image": "ラベル画像を選択", + "Choose a material to edit its labels.": "ラベルを編集するマテリアルを選択してください。", + "Choose an image first": "先に画像を選択してください", + "Choose the label image": "ラベルの画像を選択してください", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "ブラウザーで画像を選択するには、サービスのテクスチャアップロード (POST /api/textures) が必要ですが、このサービスはまだ対応していません。", + "Click a point on the part to put the label there": "パーツ上の点をクリックして、ラベルを配置します", + "Click the part where the label goes. Escape cancels.": "ラベルを貼るパーツをクリックします。Esc でキャンセルします。", + "Depth": "深度", + "Drag to reorder": "ドラッグして並べ替え", + "Height": "高さ", + "Hide Label": "ラベルを非表示", + "Image": "画像", + "Images": "画像", + "Keep the image proportions": "画像の縦横比を保持", + "Label": "ラベル", + "Label added. Use Place on Surface to put it on the part.": "ラベルを追加しました。「サーフェスに配置」でパーツに貼り付けます。", + "Label placed.": "ラベルを配置しました。", + "Labels": "ラベル", + "Metalness": "メタルネス", + "Name": "名前", + "No image": "画像なし", + "No labels yet. Add an image, then place it on the part.": "ラベルはまだありません。画像を追加して、パーツに配置してください。", + "Nothing under the pointer; click a part that wears this material.": "ポインターの下に何もありません。このマテリアルを使うパーツをクリックしてください。", + "Opacity": "不透明度", + "Own metalness": "個別のメタルネス", + "Own roughness": "個別のラフネス", + "Place on Surface": "サーフェスに配置", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "配置にはビューポートと、エンジンのコマンド view.pick および scene.meshes が必要です。", + "Print on both sides": "両面に印刷", + "Remove Label": "ラベルを削除", + "Rotation": "回転", + "Roughness": "ラフネス", + "Show Label": "ラベルを表示", + "That part does not wear this material.": "そのパーツはこのマテリアルを使っていません。", + "The image could not be uploaded": "画像をアップロードできませんでした", + "The picked part could not be read.": "選択したパーツを読み取れませんでした。", + "Width": "幅" +} diff --git a/frontend/src/i18n/modules/labels/ko.json b/frontend/src/i18n/modules/labels/ko.json new file mode 100644 index 00000000..3ca418b3 --- /dev/null +++ b/frontend/src/i18n/modules/labels/ko.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "이미지 파일에서 라벨을 추가합니다", + "Add from Image": "이미지에서 추가", + "Choose": "선택", + "Choose Label Image": "라벨 이미지 선택", + "Choose a material to edit its labels.": "라벨을 편집할 머티리얼을 선택하세요.", + "Choose an image first": "먼저 이미지를 선택하세요", + "Choose the label image": "라벨 이미지를 선택하세요", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "브라우저에서 이미지를 선택하려면 서비스의 텍스처 업로드(POST /api/textures)가 필요하지만 이 서비스는 아직 제공하지 않습니다.", + "Click a point on the part to put the label there": "부품의 한 지점을 클릭해 라벨을 그곳에 배치합니다", + "Click the part where the label goes. Escape cancels.": "라벨을 붙일 부품을 클릭하세요. Esc로 취소합니다.", + "Depth": "깊이", + "Drag to reorder": "끌어서 순서 변경", + "Height": "높이", + "Hide Label": "라벨 숨기기", + "Image": "이미지", + "Images": "이미지", + "Keep the image proportions": "이미지 비율 유지", + "Label": "라벨", + "Label added. Use Place on Surface to put it on the part.": "라벨을 추가했습니다. 표면에 배치로 부품에 붙이세요.", + "Label placed.": "라벨을 배치했습니다.", + "Labels": "라벨", + "Metalness": "메탈니스", + "Name": "이름", + "No image": "이미지 없음", + "No labels yet. Add an image, then place it on the part.": "아직 라벨이 없습니다. 이미지를 추가한 다음 부품에 배치하세요.", + "Nothing under the pointer; click a part that wears this material.": "포인터 아래에 아무것도 없습니다. 이 머티리얼을 사용하는 부품을 클릭하세요.", + "Opacity": "불투명도", + "Own metalness": "자체 메탈니스", + "Own roughness": "자체 러프니스", + "Place on Surface": "표면에 배치", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "배치하려면 뷰포트와 엔진 명령 view.pick 및 scene.meshes가 필요합니다.", + "Print on both sides": "양면 인쇄", + "Remove Label": "라벨 삭제", + "Rotation": "회전", + "Roughness": "러프니스", + "Show Label": "라벨 표시", + "That part does not wear this material.": "그 부품은 이 머티리얼을 사용하지 않습니다.", + "The image could not be uploaded": "이미지를 업로드할 수 없습니다", + "The picked part could not be read.": "선택한 부품을 읽을 수 없습니다.", + "Width": "너비" +} diff --git a/frontend/src/i18n/modules/labels/nb.json b/frontend/src/i18n/modules/labels/nb.json new file mode 100644 index 00000000..64bb9b51 --- /dev/null +++ b/frontend/src/i18n/modules/labels/nb.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Legg til en etikett fra en bildefil", + "Add from Image": "Legg til fra bilde", + "Choose": "Velg", + "Choose Label Image": "Velg etikettbilde", + "Choose a material to edit its labels.": "Velg et materiale for å redigere etikettene.", + "Choose an image first": "Velg et bilde først", + "Choose the label image": "Velg etikettbildet", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Å velge et bilde i nettleseren krever tjenestens teksturopplasting (POST /api/textures), som denne tjenesten ikke tilbyr ennå.", + "Click a point on the part to put the label there": "Klikk på et punkt på delen for å plassere etiketten der", + "Click the part where the label goes. Escape cancels.": "Klikk på delen der etiketten skal sitte. Esc avbryter.", + "Depth": "Dybde", + "Drag to reorder": "Dra for å endre rekkefølge", + "Height": "Høyde", + "Hide Label": "Skjul etikett", + "Image": "Bilde", + "Images": "Bilder", + "Keep the image proportions": "Behold bildets proporsjoner", + "Label": "Etikett", + "Label added. Use Place on Surface to put it on the part.": "Etikett lagt til. Bruk Plasser på overflaten for å sette den på delen.", + "Label placed.": "Etikett plassert.", + "Labels": "Etiketter", + "Metalness": "Metalness", + "Name": "Navn", + "No image": "Ingen bilde", + "No labels yet. Add an image, then place it on the part.": "Ingen etiketter ennå. Legg til et bilde, og plasser det deretter på delen.", + "Nothing under the pointer; click a part that wears this material.": "Ingenting under pekeren; klikk på en del som har dette materialet.", + "Opacity": "Opasitet", + "Own metalness": "Egen metalness", + "Own roughness": "Egen ruhet", + "Place on Surface": "Plasser på overflaten", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Plassering krever visningsfeltet og motorkommandoene view.pick og scene.meshes.", + "Print on both sides": "Skriv ut på begge sider", + "Remove Label": "Fjern etikett", + "Rotation": "Rotasjon", + "Roughness": "Ruhet", + "Show Label": "Vis etikett", + "That part does not wear this material.": "Den delen har ikke dette materialet.", + "The image could not be uploaded": "Bildet kunne ikke lastes opp", + "The picked part could not be read.": "Den valgte delen kunne ikke leses.", + "Width": "Bredde" +} diff --git a/frontend/src/i18n/modules/labels/nl.json b/frontend/src/i18n/modules/labels/nl.json new file mode 100644 index 00000000..4fa23e67 --- /dev/null +++ b/frontend/src/i18n/modules/labels/nl.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Een label toevoegen vanuit een afbeeldingsbestand", + "Add from Image": "Toevoegen uit afbeelding", + "Choose": "Kiezen", + "Choose Label Image": "Labelafbeelding kiezen", + "Choose a material to edit its labels.": "Kies een materiaal om de labels ervan te bewerken.", + "Choose an image first": "Kies eerst een afbeelding", + "Choose the label image": "Kies de labelafbeelding", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Een afbeelding kiezen in de browser vereist de textuurupload van de service (POST /api/textures), die deze service nog niet biedt.", + "Click a point on the part to put the label there": "Klik op een punt van het onderdeel om het label daar te plaatsen", + "Click the part where the label goes. Escape cancels.": "Klik op het onderdeel waar het label op moet. Esc annuleert.", + "Depth": "Diepte", + "Drag to reorder": "Sleep om te herschikken", + "Height": "Hoogte", + "Hide Label": "Label verbergen", + "Image": "Afbeelding", + "Images": "Afbeeldingen", + "Keep the image proportions": "Beeldverhouding van de afbeelding behouden", + "Label": "Label", + "Label added. Use Place on Surface to put it on the part.": "Label toegevoegd. Gebruik Op oppervlak plaatsen om het op het onderdeel te zetten.", + "Label placed.": "Label geplaatst.", + "Labels": "Labels", + "Metalness": "Metalness", + "Name": "Naam", + "No image": "Geen afbeelding", + "No labels yet. Add an image, then place it on the part.": "Nog geen labels. Voeg een afbeelding toe en plaats die op het onderdeel.", + "Nothing under the pointer; click a part that wears this material.": "Niets onder de aanwijzer; klik op een onderdeel met dit materiaal.", + "Opacity": "Dekking", + "Own metalness": "Eigen metalness", + "Own roughness": "Eigen ruwheid", + "Place on Surface": "Op oppervlak plaatsen", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Plaatsen vereist de viewport en de enginecommando's view.pick en scene.meshes.", + "Print on both sides": "Aan beide zijden bedrukken", + "Remove Label": "Label verwijderen", + "Rotation": "Rotatie", + "Roughness": "Ruwheid", + "Show Label": "Label tonen", + "That part does not wear this material.": "Dat onderdeel heeft dit materiaal niet.", + "The image could not be uploaded": "De afbeelding kon niet worden geüpload", + "The picked part could not be read.": "Het gekozen onderdeel kon niet worden gelezen.", + "Width": "Breedte" +} diff --git a/frontend/src/i18n/modules/labels/pl.json b/frontend/src/i18n/modules/labels/pl.json new file mode 100644 index 00000000..3ede3074 --- /dev/null +++ b/frontend/src/i18n/modules/labels/pl.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Dodaj etykietę z pliku obrazu", + "Add from Image": "Dodaj z obrazu", + "Choose": "Wybierz", + "Choose Label Image": "Wybierz obraz etykiety", + "Choose a material to edit its labels.": "Wybierz materiał, aby edytować jego etykiety.", + "Choose an image first": "Najpierw wybierz obraz", + "Choose the label image": "Wybierz obraz etykiety", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Wybór obrazu w przeglądarce wymaga przesyłania tekstur przez usługę (POST /api/textures), której ta usługa jeszcze nie oferuje.", + "Click a point on the part to put the label there": "Kliknij punkt na części, aby umieścić tam etykietę", + "Click the part where the label goes. Escape cancels.": "Kliknij część, na której ma się znaleźć etykieta. Esc anuluje.", + "Depth": "Głębokość", + "Drag to reorder": "Przeciągnij, aby zmienić kolejność", + "Height": "Wysokość", + "Hide Label": "Ukryj etykietę", + "Image": "Obraz", + "Images": "Obrazy", + "Keep the image proportions": "Zachowaj proporcje obrazu", + "Label": "Etykieta", + "Label added. Use Place on Surface to put it on the part.": "Dodano etykietę. Użyj Umieść na powierzchni, aby położyć ją na części.", + "Label placed.": "Umieszczono etykietę.", + "Labels": "Etykiety", + "Metalness": "Metaliczność", + "Name": "Nazwa", + "No image": "Brak obrazu", + "No labels yet. Add an image, then place it on the part.": "Brak etykiet. Dodaj obraz, a potem umieść go na części.", + "Nothing under the pointer; click a part that wears this material.": "Pod wskaźnikiem nic nie ma; kliknij część z tym materiałem.", + "Opacity": "Nieprzezroczystość", + "Own metalness": "Własna metaliczność", + "Own roughness": "Własna chropowatość", + "Place on Surface": "Umieść na powierzchni", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Umieszczanie wymaga widoku oraz poleceń silnika view.pick i scene.meshes.", + "Print on both sides": "Drukuj po obu stronach", + "Remove Label": "Usuń etykietę", + "Rotation": "Obrót", + "Roughness": "Chropowatość", + "Show Label": "Pokaż etykietę", + "That part does not wear this material.": "Ta część nie ma tego materiału.", + "The image could not be uploaded": "Nie udało się przesłać obrazu", + "The picked part could not be read.": "Nie udało się odczytać wybranej części.", + "Width": "Szerokość" +} diff --git a/frontend/src/i18n/modules/labels/pt-BR.json b/frontend/src/i18n/modules/labels/pt-BR.json new file mode 100644 index 00000000..f659f28f --- /dev/null +++ b/frontend/src/i18n/modules/labels/pt-BR.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Adicionar um rótulo a partir de um arquivo de imagem", + "Add from Image": "Adicionar de imagem", + "Choose": "Escolher", + "Choose Label Image": "Escolher imagem do rótulo", + "Choose a material to edit its labels.": "Escolha um material para editar seus rótulos.", + "Choose an image first": "Escolha uma imagem primeiro", + "Choose the label image": "Escolha a imagem do rótulo", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Escolher uma imagem no navegador exige o envio de texturas do serviço (POST /api/textures), que este serviço ainda não oferece.", + "Click a point on the part to put the label there": "Clique em um ponto da peça para colocar o rótulo ali", + "Click the part where the label goes. Escape cancels.": "Clique na peça onde o rótulo vai. Esc cancela.", + "Depth": "Profundidade", + "Drag to reorder": "Arraste para reordenar", + "Height": "Altura", + "Hide Label": "Ocultar rótulo", + "Image": "Imagem", + "Images": "Imagens", + "Keep the image proportions": "Manter as proporções da imagem", + "Label": "Rótulo", + "Label added. Use Place on Surface to put it on the part.": "Rótulo adicionado. Use Colocar na superfície para aplicá-lo na peça.", + "Label placed.": "Rótulo colocado.", + "Labels": "Rótulos", + "Metalness": "Metalicidade", + "Name": "Nome", + "No image": "Sem imagem", + "No labels yet. Add an image, then place it on the part.": "Ainda não há rótulos. Adicione uma imagem e depois coloque-a na peça.", + "Nothing under the pointer; click a part that wears this material.": "Nada sob o ponteiro; clique em uma peça que use este material.", + "Opacity": "Opacidade", + "Own metalness": "Metalicidade própria", + "Own roughness": "Rugosidade própria", + "Place on Surface": "Colocar na superfície", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Colocar exige o viewport e os comandos do motor view.pick e scene.meshes.", + "Print on both sides": "Imprimir nos dois lados", + "Remove Label": "Remover rótulo", + "Rotation": "Rotação", + "Roughness": "Rugosidade", + "Show Label": "Mostrar rótulo", + "That part does not wear this material.": "Essa peça não usa este material.", + "The image could not be uploaded": "Não foi possível enviar a imagem", + "The picked part could not be read.": "Não foi possível ler a peça escolhida.", + "Width": "Largura" +} diff --git a/frontend/src/i18n/modules/labels/ru.json b/frontend/src/i18n/modules/labels/ru.json new file mode 100644 index 00000000..fc84250f --- /dev/null +++ b/frontend/src/i18n/modules/labels/ru.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Добавить этикетку из файла изображения", + "Add from Image": "Добавить из изображения", + "Choose": "Выбрать", + "Choose Label Image": "Выбрать изображение этикетки", + "Choose a material to edit its labels.": "Выберите материал, чтобы изменить его этикетки.", + "Choose an image first": "Сначала выберите изображение", + "Choose the label image": "Выберите изображение этикетки", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Для выбора изображения в браузере нужна загрузка текстур сервисом (POST /api/textures), которой этот сервис пока не предлагает.", + "Click a point on the part to put the label there": "Щёлкните точку на детали, чтобы разместить там этикетку", + "Click the part where the label goes. Escape cancels.": "Щёлкните деталь, на которой будет этикетка. Esc отменяет.", + "Depth": "Глубина", + "Drag to reorder": "Перетащите, чтобы изменить порядок", + "Height": "Высота", + "Hide Label": "Скрыть этикетку", + "Image": "Изображение", + "Images": "Изображения", + "Keep the image proportions": "Сохранять пропорции изображения", + "Label": "Этикетка", + "Label added. Use Place on Surface to put it on the part.": "Этикетка добавлена. Используйте «Разместить на поверхности», чтобы поместить её на деталь.", + "Label placed.": "Этикетка размещена.", + "Labels": "Этикетки", + "Metalness": "Металличность", + "Name": "Название", + "No image": "Нет изображения", + "No labels yet. Add an image, then place it on the part.": "Этикеток пока нет. Добавьте изображение и разместите его на детали.", + "Nothing under the pointer; click a part that wears this material.": "Под указателем ничего нет; щёлкните деталь с этим материалом.", + "Opacity": "Непрозрачность", + "Own metalness": "Собственная металличность", + "Own roughness": "Собственная шероховатость", + "Place on Surface": "Разместить на поверхности", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Для размещения нужны вьюпорт и команды движка view.pick и scene.meshes.", + "Print on both sides": "Печать с обеих сторон", + "Remove Label": "Удалить этикетку", + "Rotation": "Поворот", + "Roughness": "Шероховатость", + "Show Label": "Показать этикетку", + "That part does not wear this material.": "У этой детали нет этого материала.", + "The image could not be uploaded": "Не удалось загрузить изображение", + "The picked part could not be read.": "Не удалось прочитать выбранную деталь.", + "Width": "Ширина" +} diff --git a/frontend/src/i18n/modules/labels/strings.json b/frontend/src/i18n/modules/labels/strings.json new file mode 100644 index 00000000..aaf54c43 --- /dev/null +++ b/frontend/src/i18n/modules/labels/strings.json @@ -0,0 +1,42 @@ +[ + "Add a label from an image file", + "Add from Image", + "Choose", + "Choose Label Image", + "Choose a material to edit its labels.", + "Choose an image first", + "Choose the label image", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.", + "Click a point on the part to put the label there", + "Click the part where the label goes. Escape cancels.", + "Depth", + "Drag to reorder", + "Height", + "Hide Label", + "Image", + "Images", + "Keep the image proportions", + "Label", + "Label added. Use Place on Surface to put it on the part.", + "Label placed.", + "Labels", + "Metalness", + "Name", + "No image", + "No labels yet. Add an image, then place it on the part.", + "Nothing under the pointer; click a part that wears this material.", + "Opacity", + "Own metalness", + "Own roughness", + "Place on Surface", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.", + "Print on both sides", + "Remove Label", + "Rotation", + "Roughness", + "Show Label", + "That part does not wear this material.", + "The image could not be uploaded", + "The picked part could not be read.", + "Width" +] diff --git a/frontend/src/i18n/modules/labels/sv.json b/frontend/src/i18n/modules/labels/sv.json new file mode 100644 index 00000000..f9bf7cbe --- /dev/null +++ b/frontend/src/i18n/modules/labels/sv.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Lägg till en etikett från en bildfil", + "Add from Image": "Lägg till från bild", + "Choose": "Välj", + "Choose Label Image": "Välj etikettbild", + "Choose a material to edit its labels.": "Välj ett material för att redigera dess etiketter.", + "Choose an image first": "Välj en bild först", + "Choose the label image": "Välj etikettbilden", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Att välja en bild i webbläsaren kräver tjänstens texturuppladdning (POST /api/textures), som den här tjänsten inte erbjuder ännu.", + "Click a point on the part to put the label there": "Klicka på en punkt på delen för att placera etiketten där", + "Click the part where the label goes. Escape cancels.": "Klicka på delen där etiketten ska sitta. Esc avbryter.", + "Depth": "Djup", + "Drag to reorder": "Dra för att ändra ordning", + "Height": "Höjd", + "Hide Label": "Dölj etikett", + "Image": "Bild", + "Images": "Bilder", + "Keep the image proportions": "Behåll bildens proportioner", + "Label": "Etikett", + "Label added. Use Place on Surface to put it on the part.": "Etikett tillagd. Använd Placera på ytan för att sätta den på delen.", + "Label placed.": "Etikett placerad.", + "Labels": "Etiketter", + "Metalness": "Metallighet", + "Name": "Namn", + "No image": "Ingen bild", + "No labels yet. Add an image, then place it on the part.": "Inga etiketter ännu. Lägg till en bild och placera den sedan på delen.", + "Nothing under the pointer; click a part that wears this material.": "Inget under pekaren; klicka på en del som har det här materialet.", + "Opacity": "Opacitet", + "Own metalness": "Egen metallighet", + "Own roughness": "Egen råhet", + "Place on Surface": "Placera på ytan", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Placering kräver vyn och motorkommandona view.pick och scene.meshes.", + "Print on both sides": "Skriv ut på båda sidor", + "Remove Label": "Ta bort etikett", + "Rotation": "Rotation", + "Roughness": "Råhet", + "Show Label": "Visa etikett", + "That part does not wear this material.": "Den delen har inte det här materialet.", + "The image could not be uploaded": "Bilden kunde inte laddas upp", + "The picked part could not be read.": "Den valda delen kunde inte läsas.", + "Width": "Bredd" +} diff --git a/frontend/src/i18n/modules/labels/th.json b/frontend/src/i18n/modules/labels/th.json new file mode 100644 index 00000000..563ccd8f --- /dev/null +++ b/frontend/src/i18n/modules/labels/th.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "เพิ่มป้ายจากไฟล์ภาพ", + "Add from Image": "เพิ่มจากภาพ", + "Choose": "เลือก", + "Choose Label Image": "เลือกภาพป้าย", + "Choose a material to edit its labels.": "เลือกแมทีเรียลเพื่อแก้ไขป้ายของมัน", + "Choose an image first": "เลือกภาพก่อน", + "Choose the label image": "เลือกภาพป้าย", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "การเลือกภาพในเบราว์เซอร์ต้องใช้การอัปโหลดเท็กซ์เจอร์ของบริการ (POST /api/textures) ซึ่งบริการนี้ยังไม่รองรับ", + "Click a point on the part to put the label there": "คลิกจุดบนชิ้นส่วนเพื่อวางป้ายตรงนั้น", + "Click the part where the label goes. Escape cancels.": "คลิกชิ้นส่วนที่จะติดป้าย กด Esc เพื่อยกเลิก", + "Depth": "ความลึก", + "Drag to reorder": "ลากเพื่อจัดลำดับใหม่", + "Height": "ความสูง", + "Hide Label": "ซ่อนป้าย", + "Image": "ภาพ", + "Images": "ภาพ", + "Keep the image proportions": "คงสัดส่วนของภาพ", + "Label": "ป้าย", + "Label added. Use Place on Surface to put it on the part.": "เพิ่มป้ายแล้ว ใช้ วางบนพื้นผิว เพื่อติดป้ายลงบนชิ้นส่วน", + "Label placed.": "วางป้ายแล้ว", + "Labels": "ป้าย", + "Metalness": "ความเป็นโลหะ", + "Name": "ชื่อ", + "No image": "ไม่มีภาพ", + "No labels yet. Add an image, then place it on the part.": "ยังไม่มีป้าย เพิ่มภาพ แล้ววางบนชิ้นส่วน", + "Nothing under the pointer; click a part that wears this material.": "ไม่มีอะไรอยู่ใต้ตัวชี้ คลิกชิ้นส่วนที่ใช้แมทีเรียลนี้", + "Opacity": "ความทึบ", + "Own metalness": "ความเป็นโลหะของป้ายเอง", + "Own roughness": "ความหยาบของป้ายเอง", + "Place on Surface": "วางบนพื้นผิว", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "การวางต้องใช้วิวพอร์ตและคำสั่งเอนจิน view.pick และ scene.meshes", + "Print on both sides": "พิมพ์ทั้งสองด้าน", + "Remove Label": "ลบป้าย", + "Rotation": "การหมุน", + "Roughness": "ความหยาบ", + "Show Label": "แสดงป้าย", + "That part does not wear this material.": "ชิ้นส่วนนั้นไม่ได้ใช้แมทีเรียลนี้", + "The image could not be uploaded": "ไม่สามารถอัปโหลดภาพได้", + "The picked part could not be read.": "ไม่สามารถอ่านชิ้นส่วนที่เลือกได้", + "Width": "ความกว้าง" +} diff --git a/frontend/src/i18n/modules/labels/tr.json b/frontend/src/i18n/modules/labels/tr.json new file mode 100644 index 00000000..fabb9d66 --- /dev/null +++ b/frontend/src/i18n/modules/labels/tr.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Bir görüntü dosyasından etiket ekle", + "Add from Image": "Görüntüden Ekle", + "Choose": "Seç", + "Choose Label Image": "Etiket Görüntüsünü Seç", + "Choose a material to edit its labels.": "Etiketlerini düzenlemek için bir malzeme seçin.", + "Choose an image first": "Önce bir görüntü seçin", + "Choose the label image": "Etiket görüntüsünü seçin", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Tarayıcıda görüntü seçmek için hizmetin doku yüklemesi (POST /api/textures) gerekir; bu hizmet bunu henüz sunmuyor.", + "Click a point on the part to put the label there": "Etiketi yerleştirmek için parça üzerinde bir noktaya tıklayın", + "Click the part where the label goes. Escape cancels.": "Etiketin gideceği parçaya tıklayın. Esc iptal eder.", + "Depth": "Derinlik", + "Drag to reorder": "Sıralamak için sürükleyin", + "Height": "Yükseklik", + "Hide Label": "Etiketi Gizle", + "Image": "Görüntü", + "Images": "Görüntüler", + "Keep the image proportions": "Görüntü oranlarını koru", + "Label": "Etiket", + "Label added. Use Place on Surface to put it on the part.": "Etiket eklendi. Parçaya koymak için Yüzeye Yerleştir'i kullanın.", + "Label placed.": "Etiket yerleştirildi.", + "Labels": "Etiketler", + "Metalness": "Metaliklik", + "Name": "Ad", + "No image": "Görüntü yok", + "No labels yet. Add an image, then place it on the part.": "Henüz etiket yok. Bir görüntü ekleyin, sonra parçaya yerleştirin.", + "Nothing under the pointer; click a part that wears this material.": "İşaretçinin altında bir şey yok; bu malzemeyi taşıyan bir parçaya tıklayın.", + "Opacity": "Opaklık", + "Own metalness": "Kendi metaliklik", + "Own roughness": "Kendi pürüzlülük", + "Place on Surface": "Yüzeye Yerleştir", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Yerleştirme için görünüm alanı ile view.pick ve scene.meshes motor komutları gerekir.", + "Print on both sides": "Her iki yüze yazdır", + "Remove Label": "Etiketi Kaldır", + "Rotation": "Döndürme", + "Roughness": "Pürüzlülük", + "Show Label": "Etiketi Göster", + "That part does not wear this material.": "Bu parça bu malzemeyi taşımıyor.", + "The image could not be uploaded": "Görüntü yüklenemedi", + "The picked part could not be read.": "Seçilen parça okunamadı.", + "Width": "Genişlik" +} diff --git a/frontend/src/i18n/modules/labels/uk.json b/frontend/src/i18n/modules/labels/uk.json new file mode 100644 index 00000000..b70b55ee --- /dev/null +++ b/frontend/src/i18n/modules/labels/uk.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Додати етикетку з файлу зображення", + "Add from Image": "Додати із зображення", + "Choose": "Вибрати", + "Choose Label Image": "Вибрати зображення етикетки", + "Choose a material to edit its labels.": "Виберіть матеріал, щоб змінити його етикетки.", + "Choose an image first": "Спершу виберіть зображення", + "Choose the label image": "Виберіть зображення етикетки", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Для вибору зображення в браузері потрібне завантаження текстур службою (POST /api/textures), якої ця служба поки не пропонує.", + "Click a point on the part to put the label there": "Клацніть точку на деталі, щоб розмістити там етикетку", + "Click the part where the label goes. Escape cancels.": "Клацніть деталь, на якій буде етикетка. Esc скасовує.", + "Depth": "Глибина", + "Drag to reorder": "Перетягніть, щоб змінити порядок", + "Height": "Висота", + "Hide Label": "Сховати етикетку", + "Image": "Зображення", + "Images": "Зображення", + "Keep the image proportions": "Зберігати пропорції зображення", + "Label": "Етикетка", + "Label added. Use Place on Surface to put it on the part.": "Етикетку додано. Скористайтеся «Розмістити на поверхні», щоб помістити її на деталь.", + "Label placed.": "Етикетку розміщено.", + "Labels": "Етикетки", + "Metalness": "Металевість", + "Name": "Назва", + "No image": "Немає зображення", + "No labels yet. Add an image, then place it on the part.": "Етикеток поки немає. Додайте зображення й розмістіть його на деталі.", + "Nothing under the pointer; click a part that wears this material.": "Під вказівником нічого немає; клацніть деталь із цим матеріалом.", + "Opacity": "Непрозорість", + "Own metalness": "Власна металевість", + "Own roughness": "Власна шорсткість", + "Place on Surface": "Розмістити на поверхні", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Для розміщення потрібні в'юпорт і команди рушія view.pick та scene.meshes.", + "Print on both sides": "Друк з обох боків", + "Remove Label": "Видалити етикетку", + "Rotation": "Обертання", + "Roughness": "Шорсткість", + "Show Label": "Показати етикетку", + "That part does not wear this material.": "Ця деталь не має цього матеріалу.", + "The image could not be uploaded": "Не вдалося завантажити зображення", + "The picked part could not be read.": "Не вдалося прочитати вибрану деталь.", + "Width": "Ширина" +} diff --git a/frontend/src/i18n/modules/labels/vi.json b/frontend/src/i18n/modules/labels/vi.json new file mode 100644 index 00000000..e1daa31e --- /dev/null +++ b/frontend/src/i18n/modules/labels/vi.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "Thêm nhãn từ một tệp ảnh", + "Add from Image": "Thêm từ ảnh", + "Choose": "Chọn", + "Choose Label Image": "Chọn ảnh nhãn", + "Choose a material to edit its labels.": "Chọn một vật liệu để chỉnh sửa nhãn của nó.", + "Choose an image first": "Hãy chọn ảnh trước", + "Choose the label image": "Chọn ảnh nhãn", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "Chọn ảnh trong trình duyệt cần tính năng tải kết cấu lên của dịch vụ (POST /api/textures), mà dịch vụ này chưa cung cấp.", + "Click a point on the part to put the label there": "Nhấp vào một điểm trên chi tiết để đặt nhãn tại đó", + "Click the part where the label goes. Escape cancels.": "Nhấp vào chi tiết nơi đặt nhãn. Nhấn Esc để hủy.", + "Depth": "Độ sâu", + "Drag to reorder": "Kéo để sắp xếp lại", + "Height": "Chiều cao", + "Hide Label": "Ẩn nhãn", + "Image": "Ảnh", + "Images": "Ảnh", + "Keep the image proportions": "Giữ nguyên tỷ lệ ảnh", + "Label": "Nhãn", + "Label added. Use Place on Surface to put it on the part.": "Đã thêm nhãn. Dùng Đặt lên bề mặt để đặt nó lên chi tiết.", + "Label placed.": "Đã đặt nhãn.", + "Labels": "Nhãn", + "Metalness": "Độ kim loại", + "Name": "Tên", + "No image": "Không có ảnh", + "No labels yet. Add an image, then place it on the part.": "Chưa có nhãn nào. Thêm một ảnh rồi đặt lên chi tiết.", + "Nothing under the pointer; click a part that wears this material.": "Không có gì dưới con trỏ; hãy nhấp vào chi tiết dùng vật liệu này.", + "Opacity": "Độ đục", + "Own metalness": "Độ kim loại riêng", + "Own roughness": "Độ nhám riêng", + "Place on Surface": "Đặt lên bề mặt", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "Việc đặt cần khung nhìn và các lệnh công cụ view.pick và scene.meshes.", + "Print on both sides": "In cả hai mặt", + "Remove Label": "Xóa nhãn", + "Rotation": "Xoay", + "Roughness": "Độ nhám", + "Show Label": "Hiện nhãn", + "That part does not wear this material.": "Chi tiết đó không dùng vật liệu này.", + "The image could not be uploaded": "Không thể tải ảnh lên", + "The picked part could not be read.": "Không thể đọc chi tiết đã chọn.", + "Width": "Chiều rộng" +} diff --git a/frontend/src/i18n/modules/labels/zh-CN.json b/frontend/src/i18n/modules/labels/zh-CN.json new file mode 100644 index 00000000..a215024e --- /dev/null +++ b/frontend/src/i18n/modules/labels/zh-CN.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "从图像文件添加标签", + "Add from Image": "从图像添加", + "Choose": "选择", + "Choose Label Image": "选择标签图像", + "Choose a material to edit its labels.": "选择一个材质以编辑其标签。", + "Choose an image first": "请先选择图像", + "Choose the label image": "选择标签图像", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "在浏览器中选择图像需要服务的纹理上传功能(POST /api/textures),此服务尚未提供。", + "Click a point on the part to put the label there": "点击零件上的一点,将标签放在那里", + "Click the part where the label goes. Escape cancels.": "点击要贴标签的零件。按 Esc 取消。", + "Depth": "深度", + "Drag to reorder": "拖动以重新排序", + "Height": "高度", + "Hide Label": "隐藏标签", + "Image": "图像", + "Images": "图像", + "Keep the image proportions": "保持图像比例", + "Label": "标签", + "Label added. Use Place on Surface to put it on the part.": "已添加标签。使用“放置到表面”将其贴到零件上。", + "Label placed.": "标签已放置。", + "Labels": "标签", + "Metalness": "金属度", + "Name": "名称", + "No image": "无图像", + "No labels yet. Add an image, then place it on the part.": "还没有标签。请添加图像,然后将其放置到零件上。", + "Nothing under the pointer; click a part that wears this material.": "指针下没有内容;请点击使用此材质的零件。", + "Opacity": "不透明度", + "Own metalness": "自有金属度", + "Own roughness": "自有粗糙度", + "Place on Surface": "放置到表面", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "放置需要视口以及引擎命令 view.pick 和 scene.meshes。", + "Print on both sides": "双面打印", + "Remove Label": "移除标签", + "Rotation": "旋转", + "Roughness": "粗糙度", + "Show Label": "显示标签", + "That part does not wear this material.": "该零件未使用此材质。", + "The image could not be uploaded": "无法上传图像", + "The picked part could not be read.": "无法读取所选零件。", + "Width": "宽度" +} diff --git a/frontend/src/i18n/modules/labels/zh-TW.json b/frontend/src/i18n/modules/labels/zh-TW.json new file mode 100644 index 00000000..451c6c87 --- /dev/null +++ b/frontend/src/i18n/modules/labels/zh-TW.json @@ -0,0 +1,42 @@ +{ + "Add a label from an image file": "從影像檔案新增標籤", + "Add from Image": "從影像新增", + "Choose": "選擇", + "Choose Label Image": "選擇標籤影像", + "Choose a material to edit its labels.": "選擇一個材質以編輯其標籤。", + "Choose an image first": "請先選擇影像", + "Choose the label image": "選擇標籤影像", + "Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.": "在瀏覽器中選擇影像需要服務的紋理上傳功能(POST /api/textures),此服務尚未提供。", + "Click a point on the part to put the label there": "點擊零件上的一點,將標籤放在那裡", + "Click the part where the label goes. Escape cancels.": "點擊要貼標籤的零件。按 Esc 取消。", + "Depth": "深度", + "Drag to reorder": "拖曳以重新排序", + "Height": "高度", + "Hide Label": "隱藏標籤", + "Image": "影像", + "Images": "影像", + "Keep the image proportions": "保持影像比例", + "Label": "標籤", + "Label added. Use Place on Surface to put it on the part.": "已新增標籤。使用「放置到表面」將其貼到零件上。", + "Label placed.": "標籤已放置。", + "Labels": "標籤", + "Metalness": "金屬度", + "Name": "名稱", + "No image": "無影像", + "No labels yet. Add an image, then place it on the part.": "尚無標籤。請新增影像,然後將其放置到零件上。", + "Nothing under the pointer; click a part that wears this material.": "指標下沒有內容;請點擊使用此材質的零件。", + "Opacity": "不透明度", + "Own metalness": "自有金屬度", + "Own roughness": "自有粗糙度", + "Place on Surface": "放置到表面", + "Placing needs the viewport and the engine commands view.pick and scene.meshes.": "放置需要視埠以及引擎命令 view.pick 和 scene.meshes。", + "Print on both sides": "雙面列印", + "Remove Label": "移除標籤", + "Rotation": "旋轉", + "Roughness": "粗糙度", + "Show Label": "顯示標籤", + "That part does not wear this material.": "該零件未使用此材質。", + "The image could not be uploaded": "無法上傳影像", + "The picked part could not be read.": "無法讀取所選零件。", + "Width": "寬度" +} diff --git a/frontend/src/i18n/modules/library/cs.json b/frontend/src/i18n/modules/library/cs.json new file mode 100644 index 00000000..4a96fc6d --- /dev/null +++ b/frontend/src/i18n/modules/library/cs.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 materiál", + "Abbe number": "Abbeho číslo", + "All": "Vše", + "Alt: whole group. Shift: same material.": "Alt: celá skupina. Shift: stejný materiál.", + "Anisotropy": "Anizotropie", + "Applied {name} to every part with the material of {part}": "Materiál {name} byl použit na všechny části s materiálem části {part}", + "Applied {name} to every part with the same material": "Materiál {name} byl použit na všechny části se stejným materiálem", + "Applied {name} to the group of {part}": "Materiál {name} byl použit na skupinu části {part}", + "Applied {name} to the selected parts": "Materiál {name} byl použit na vybrané části", + "Applied {name} to their groups": "Materiál {name} byl použit na jejich skupiny", + "Applied {name} to {part}": "Materiál {name} byl použit na část {part}", + "Apply to Every Part with the Same Material": "Použít na všechny části se stejným materiálem", + "Apply to Selected Parts": "Použít na vybrané části", + "Apply to Their Groups": "Použít na jejich skupiny", + "Apply to every part with the material of {name}": "Použít na všechny části s materiálem části {name}", + "Apply to the group of {name}": "Použít na skupinu části {name}", + "Apply to {name}": "Použít na {name}", + "Authored": "Vlastní tvorba", + "Base color": "Základní barva", + "Brushed metal": "Broušený kov", + "Cancel": "Zrušit", + "Categories": "Kategorie", + "Category": "Kategorie", + "Ceramic": "Keramika", + "Clear plastic": "Čirý plast", + "Coat": "Lak", + "Coat roughness": "Drsnost laku", + "Details": "Podrobnosti", + "Diffuse": "Difuzní", + "Drop on a part in the viewport": "Pusťte na část v pohledu", + "Drop the material on a part": "Pusťte materiál na část", + "Emission": "Emise", + "Emissive": "Emisivní", + "Fabric": "Látka", + "Favorite": "Oblíbený", + "Favorites": "Oblíbené", + "Fuzz": "Chmýří", + "Gem": "Drahokam", + "Generic": "Obecný", + "Give the material a name": "Pojmenujte materiál", + "Glass": "Sklo", + "In project": "V projektu", + "Index of refraction": "Index lomu", + "Keeps the material of the selected part as one of your own presets.": "Uloží materiál vybrané části jako jednu z vašich vlastních předvoleb.", + "Library": "Knihovna", + "Liquid": "Kapalina", + "Loading": "Načítání", + "Material details": "Podrobnosti materiálu", + "Materials": "Materiály", + "Materials you apply appear here.": "Materiály, které použijete, se zobrazí zde.", + "Materials you save from the selection appear here.": "Materiály, které uložíte z výběru, se zobrazí zde.", + "Measured": "Změřeno", + "Metal": "Kov", + "Metallic paint": "Metalický lak", + "Metalness": "Kovovost", + "Name": "Název", + "No": "Ne", + "No favorites yet. Right-click a material to add one.": "Zatím žádné oblíbené. Klepnutím pravým tlačítkem na materiál nějaký přidáte.", + "No materials match {query}": "Hledání {query} neodpovídá žádný materiál", + "No part here": "Zde není žádná část", + "Nothing in {category} here": "V kategorii {category} tu nic není", + "Opacity": "Neprůhlednost", + "Paint": "Barva", + "Plastic": "Plast", + "Published": "Publikováno", + "Recent": "Nedávné", + "Remove": "Odebrat", + "Remove from Library": "Odebrat z knihovny", + "Remove {name} from your library? Documents that use it keep their material.": "Odebrat {name} z vaší knihovny? Dokumenty, které jej používají, si ponechají svůj materiál.", + "Resize the library": "Změnit velikost knihovny", + "Roughness": "Drsnost", + "Rubber": "Guma", + "Save": "Uložit", + "Save Material to Library": "Uložit materiál do knihovny", + "Save Selected Material to Library": "Uložit vybraný materiál do knihovny", + "Saved {name} to your library": "{name} bylo uloženo do vaší knihovny", + "Search materials": "Hledat materiály", + "Select a part first": "Nejprve vyberte část", + "Select a part with a material first": "Nejprve vyberte část s materiálem", + "Shelves": "Police", + "Source": "Zdroj", + "Stone": "Kámen", + "Subsurface": "Podpovrchový rozptyl", + "The engine sent the preset in an unknown shape": "Engine poslal předvolbu v neznámém tvaru", + "The library is empty": "Knihovna je prázdná", + "Thin film thickness": "Tloušťka tenkého filmu", + "Thin glass": "Tenké sklo", + "Thin walled": "Tenkostěnný", + "This project has no materials yet.": "Tento projekt zatím nemá žádné materiály.", + "Tile size": "Velikost dlaždic", + "Transmission": "Propustnost", + "Transmission depth": "Hloubka propustnosti", + "User": "Uživatel", + "Wood": "Dřevo", + "Yes": "Ano", + "{n} materials": "{n} materiálů" +} diff --git a/frontend/src/i18n/modules/library/da.json b/frontend/src/i18n/modules/library/da.json new file mode 100644 index 00000000..dba8b32b --- /dev/null +++ b/frontend/src/i18n/modules/library/da.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 materiale", + "Abbe number": "Abbetal", + "All": "Alle", + "Alt: whole group. Shift: same material.": "Alt: hele gruppen. Shift: samme materiale.", + "Anisotropy": "Anisotropi", + "Applied {name} to every part with the material of {part}": "Anvendte {name} på alle dele med materialet fra {part}", + "Applied {name} to every part with the same material": "Anvendte {name} på alle dele med samme materiale", + "Applied {name} to the group of {part}": "Anvendte {name} på gruppen for {part}", + "Applied {name} to the selected parts": "Anvendte {name} på de valgte dele", + "Applied {name} to their groups": "Anvendte {name} på deres grupper", + "Applied {name} to {part}": "Anvendte {name} på {part}", + "Apply to Every Part with the Same Material": "Anvend på alle dele med samme materiale", + "Apply to Selected Parts": "Anvend på valgte dele", + "Apply to Their Groups": "Anvend på deres grupper", + "Apply to every part with the material of {name}": "Anvend på alle dele med materialet fra {name}", + "Apply to the group of {name}": "Anvend på gruppen for {name}", + "Apply to {name}": "Anvend på {name}", + "Authored": "Håndlavet", + "Base color": "Basisfarve", + "Brushed metal": "Børstet metal", + "Cancel": "Annuller", + "Categories": "Kategorier", + "Category": "Kategori", + "Ceramic": "Keramik", + "Clear plastic": "Klar plast", + "Coat": "Coating", + "Coat roughness": "Coatingruhed", + "Details": "Detaljer", + "Diffuse": "Diffus", + "Drop on a part in the viewport": "Slip på en del i viewporten", + "Drop the material on a part": "Slip materialet på en del", + "Emission": "Emission", + "Emissive": "Emissiv", + "Fabric": "Stof", + "Favorite": "Favorit", + "Favorites": "Favoritter", + "Fuzz": "Fuzz", + "Gem": "Ædelsten", + "Generic": "Generelt", + "Give the material a name": "Giv materialet et navn", + "Glass": "Glas", + "In project": "I projekt", + "Index of refraction": "Brydningsindeks", + "Keeps the material of the selected part as one of your own presets.": "Gemmer materialet for den valgte del som en af dine egne forudindstillinger.", + "Library": "Bibliotek", + "Liquid": "Væske", + "Loading": "Indlæser", + "Material details": "Materialedetaljer", + "Materials": "Materialer", + "Materials you apply appear here.": "Materialer, du anvender, vises her.", + "Materials you save from the selection appear here.": "Materialer, du gemmer fra markeringen, vises her.", + "Measured": "Målt", + "Metal": "Metal", + "Metallic paint": "Metallic lak", + "Metalness": "Metalness", + "Name": "Navn", + "No": "Nej", + "No favorites yet. Right-click a material to add one.": "Ingen favoritter endnu. Højreklik på et materiale for at tilføje en.", + "No materials match {query}": "Ingen materialer matcher {query}", + "No part here": "Ingen del her", + "Nothing in {category} here": "Intet i {category} her", + "Opacity": "Opacitet", + "Paint": "Maling", + "Plastic": "Plast", + "Published": "Udgivet", + "Recent": "Seneste", + "Remove": "Fjern", + "Remove from Library": "Fjern fra biblioteket", + "Remove {name} from your library? Documents that use it keep their material.": "Fjern {name} fra dit bibliotek? Dokumenter, der bruger det, beholder deres materiale.", + "Resize the library": "Ændr bibliotekets størrelse", + "Roughness": "Ruhed", + "Rubber": "Gummi", + "Save": "Gem", + "Save Material to Library": "Gem materiale i biblioteket", + "Save Selected Material to Library": "Gem valgt materiale i biblioteket", + "Saved {name} to your library": "{name} er gemt i dit bibliotek", + "Search materials": "Søg i materialer", + "Select a part first": "Vælg først en del", + "Select a part with a material first": "Vælg først en del med et materiale", + "Shelves": "Hylder", + "Source": "Kilde", + "Stone": "Sten", + "Subsurface": "Subsurface", + "The engine sent the preset in an unknown shape": "Motoren sendte forudindstillingen i en ukendt form", + "The library is empty": "Biblioteket er tomt", + "Thin film thickness": "Tykkelse af tynd film", + "Thin glass": "Tyndt glas", + "Thin walled": "Tyndvægget", + "This project has no materials yet.": "Dette projekt har endnu ingen materialer.", + "Tile size": "Miniaturestørrelse", + "Transmission": "Transmission", + "Transmission depth": "Transmissionsdybde", + "User": "Bruger", + "Wood": "Træ", + "Yes": "Ja", + "{n} materials": "{n} materialer" +} diff --git a/frontend/src/i18n/modules/library/de.json b/frontend/src/i18n/modules/library/de.json new file mode 100644 index 00000000..2cd328ad --- /dev/null +++ b/frontend/src/i18n/modules/library/de.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 Material", + "Abbe number": "Abbe-Zahl", + "All": "Alle", + "Alt: whole group. Shift: same material.": "Alt: ganze Gruppe. Umschalt: gleiches Material.", + "Anisotropy": "Anisotropie", + "Applied {name} to every part with the material of {part}": "{name} auf alle Teile mit dem Material von {part} angewendet", + "Applied {name} to every part with the same material": "{name} auf alle Teile mit demselben Material angewendet", + "Applied {name} to the group of {part}": "{name} auf die Gruppe von {part} angewendet", + "Applied {name} to the selected parts": "{name} auf die ausgewählten Teile angewendet", + "Applied {name} to their groups": "{name} auf ihre Gruppen angewendet", + "Applied {name} to {part}": "{name} auf {part} angewendet", + "Apply to Every Part with the Same Material": "Auf alle Teile mit demselben Material anwenden", + "Apply to Selected Parts": "Auf ausgewählte Teile anwenden", + "Apply to Their Groups": "Auf ihre Gruppen anwenden", + "Apply to every part with the material of {name}": "Auf alle Teile mit dem Material von {name} anwenden", + "Apply to the group of {name}": "Auf die Gruppe von {name} anwenden", + "Apply to {name}": "Auf {name} anwenden", + "Authored": "Gestaltet", + "Base color": "Basisfarbe", + "Brushed metal": "Gebürstetes Metall", + "Cancel": "Abbrechen", + "Categories": "Kategorien", + "Category": "Kategorie", + "Ceramic": "Keramik", + "Clear plastic": "Klarer Kunststoff", + "Coat": "Klarlack", + "Coat roughness": "Klarlack-Rauheit", + "Details": "Details", + "Diffuse": "Diffus", + "Drop on a part in the viewport": "Auf ein Teil im Viewport ablegen", + "Drop the material on a part": "Das Material auf einem Teil ablegen", + "Emission": "Emission", + "Emissive": "Emissiv", + "Fabric": "Stoff", + "Favorite": "Favorit", + "Favorites": "Favoriten", + "Fuzz": "Flaum", + "Gem": "Edelstein", + "Generic": "Allgemein", + "Give the material a name": "Gib dem Material einen Namen", + "Glass": "Glas", + "In project": "Im Projekt", + "Index of refraction": "Brechungsindex", + "Keeps the material of the selected part as one of your own presets.": "Behält das Material des ausgewählten Teils als eigene Vorgabe.", + "Library": "Bibliothek", + "Liquid": "Flüssigkeit", + "Loading": "Wird geladen", + "Material details": "Materialdetails", + "Materials": "Materialien", + "Materials you apply appear here.": "Hier erscheinen Materialien, die du anwendest.", + "Materials you save from the selection appear here.": "Hier erscheinen Materialien, die du aus der Auswahl speicherst.", + "Measured": "Gemessen", + "Metal": "Metall", + "Metallic paint": "Metallic-Lack", + "Metalness": "Metallizität", + "Name": "Name", + "No": "Nein", + "No favorites yet. Right-click a material to add one.": "Noch keine Favoriten. Klicke mit der rechten Maustaste auf ein Material, um eines hinzuzufügen.", + "No materials match {query}": "Kein Material passt zu {query}", + "No part here": "Hier ist kein Teil", + "Nothing in {category} here": "Hier gibt es nichts in {category}", + "Opacity": "Deckkraft", + "Paint": "Lack", + "Plastic": "Kunststoff", + "Published": "Veröffentlicht", + "Recent": "Zuletzt", + "Remove": "Entfernen", + "Remove from Library": "Aus der Bibliothek entfernen", + "Remove {name} from your library? Documents that use it keep their material.": "{name} aus deiner Bibliothek entfernen? Dokumente, die es verwenden, behalten ihr Material.", + "Resize the library": "Größe der Bibliothek ändern", + "Roughness": "Rauheit", + "Rubber": "Gummi", + "Save": "Speichern", + "Save Material to Library": "Material in Bibliothek speichern", + "Save Selected Material to Library": "Ausgewähltes Material in Bibliothek speichern", + "Saved {name} to your library": "{name} in deiner Bibliothek gespeichert", + "Search materials": "Materialien suchen", + "Select a part first": "Wähle zuerst ein Teil aus", + "Select a part with a material first": "Wähle zuerst ein Teil mit einem Material aus", + "Shelves": "Regale", + "Source": "Quelle", + "Stone": "Stein", + "Subsurface": "Subsurface", + "The engine sent the preset in an unknown shape": "Die Engine hat die Vorgabe in einer unbekannten Form gesendet", + "The library is empty": "Die Bibliothek ist leer", + "Thin film thickness": "Dicke der Dünnschicht", + "Thin glass": "Dünnes Glas", + "Thin walled": "Dünnwandig", + "This project has no materials yet.": "Dieses Projekt hat noch keine Materialien.", + "Tile size": "Kachelgröße", + "Transmission": "Transmission", + "Transmission depth": "Transmissionstiefe", + "User": "Eigene", + "Wood": "Holz", + "Yes": "Ja", + "{n} materials": "{n} Materialien" +} diff --git a/frontend/src/i18n/modules/library/es-MX.json b/frontend/src/i18n/modules/library/es-MX.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/library/es-MX.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/library/es.json b/frontend/src/i18n/modules/library/es.json new file mode 100644 index 00000000..7218b5d5 --- /dev/null +++ b/frontend/src/i18n/modules/library/es.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 material", + "Abbe number": "Número de Abbe", + "All": "Todo", + "Alt: whole group. Shift: same material.": "Alt: todo el grupo. Mayús: mismo material.", + "Anisotropy": "Anisotropía", + "Applied {name} to every part with the material of {part}": "Se aplicó {name} a todas las piezas con el material de {part}", + "Applied {name} to every part with the same material": "Se aplicó {name} a todas las piezas con el mismo material", + "Applied {name} to the group of {part}": "Se aplicó {name} al grupo de {part}", + "Applied {name} to the selected parts": "Se aplicó {name} a las piezas seleccionadas", + "Applied {name} to their groups": "Se aplicó {name} a sus grupos", + "Applied {name} to {part}": "Se aplicó {name} a {part}", + "Apply to Every Part with the Same Material": "Aplicar a todas las piezas con el mismo material", + "Apply to Selected Parts": "Aplicar a las piezas seleccionadas", + "Apply to Their Groups": "Aplicar a sus grupos", + "Apply to every part with the material of {name}": "Aplicar a todas las piezas con el material de {name}", + "Apply to the group of {name}": "Aplicar al grupo de {name}", + "Apply to {name}": "Aplicar a {name}", + "Authored": "Diseñado", + "Base color": "Color base", + "Brushed metal": "Metal cepillado", + "Cancel": "Cancelar", + "Categories": "Categorías", + "Category": "Categoría", + "Ceramic": "Cerámica", + "Clear plastic": "Plástico transparente", + "Coat": "Barniz", + "Coat roughness": "Rugosidad del barniz", + "Details": "Detalles", + "Diffuse": "Difuso", + "Drop on a part in the viewport": "Suelta sobre una pieza en la vista 3D", + "Drop the material on a part": "Suelta el material sobre una pieza", + "Emission": "Emisión", + "Emissive": "Emisivo", + "Fabric": "Tela", + "Favorite": "Favorito", + "Favorites": "Favoritos", + "Fuzz": "Pelusa", + "Gem": "Gema", + "Generic": "Genérico", + "Give the material a name": "Ponle un nombre al material", + "Glass": "Vidrio", + "In project": "En el proyecto", + "Index of refraction": "Índice de refracción", + "Keeps the material of the selected part as one of your own presets.": "Guarda el material de la pieza seleccionada como uno de tus preajustes.", + "Library": "Biblioteca", + "Liquid": "Líquido", + "Loading": "Cargando", + "Material details": "Detalles del material", + "Materials": "Materiales", + "Materials you apply appear here.": "Aquí aparecen los materiales que aplicas.", + "Materials you save from the selection appear here.": "Aquí aparecen los materiales que guardas desde la selección.", + "Measured": "Medido", + "Metal": "Metal", + "Metallic paint": "Pintura metálica", + "Metalness": "Metalicidad", + "Name": "Nombre", + "No": "No", + "No favorites yet. Right-click a material to add one.": "Aún no hay favoritos. Haz clic derecho en un material para añadir uno.", + "No materials match {query}": "Ningún material coincide con {query}", + "No part here": "No hay ninguna pieza aquí", + "Nothing in {category} here": "Aquí no hay nada en {category}", + "Opacity": "Opacidad", + "Paint": "Pintura", + "Plastic": "Plástico", + "Published": "Publicado", + "Recent": "Recientes", + "Remove": "Quitar", + "Remove from Library": "Quitar de la biblioteca", + "Remove {name} from your library? Documents that use it keep their material.": "¿Quitar {name} de tu biblioteca? Los documentos que lo usan conservan su material.", + "Resize the library": "Cambiar el tamaño de la biblioteca", + "Roughness": "Rugosidad", + "Rubber": "Goma", + "Save": "Guardar", + "Save Material to Library": "Guardar material en la biblioteca", + "Save Selected Material to Library": "Guardar el material seleccionado en la biblioteca", + "Saved {name} to your library": "Se guardó {name} en tu biblioteca", + "Search materials": "Buscar materiales", + "Select a part first": "Selecciona primero una pieza", + "Select a part with a material first": "Selecciona primero una pieza con un material", + "Shelves": "Estantes", + "Source": "Origen", + "Stone": "Piedra", + "Subsurface": "Subsuperficie", + "The engine sent the preset in an unknown shape": "El motor envió el preajuste con un formato desconocido", + "The library is empty": "La biblioteca está vacía", + "Thin film thickness": "Grosor de la película fina", + "Thin glass": "Vidrio fino", + "Thin walled": "Pared delgada", + "This project has no materials yet.": "Este proyecto aún no tiene materiales.", + "Tile size": "Tamaño de las miniaturas", + "Transmission": "Transmisión", + "Transmission depth": "Profundidad de transmisión", + "User": "Usuario", + "Wood": "Madera", + "Yes": "Sí", + "{n} materials": "{n} materiales" +} diff --git a/frontend/src/i18n/modules/library/fi.json b/frontend/src/i18n/modules/library/fi.json new file mode 100644 index 00000000..7147cef5 --- /dev/null +++ b/frontend/src/i18n/modules/library/fi.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 materiaali", + "Abbe number": "Abben luku", + "All": "Kaikki", + "Alt: whole group. Shift: same material.": "Alt: koko ryhmä. Shift: sama materiaali.", + "Anisotropy": "Anisotropia", + "Applied {name} to every part with the material of {part}": "{name} asetettu kaikille osille, joilla on kohteen {part} materiaali", + "Applied {name} to every part with the same material": "{name} asetettu kaikille osille, joilla on sama materiaali", + "Applied {name} to the group of {part}": "{name} asetettu kohteen {part} ryhmälle", + "Applied {name} to the selected parts": "{name} asetettu valituille osille", + "Applied {name} to their groups": "{name} asetettu niiden ryhmille", + "Applied {name} to {part}": "{name} asetettu kohteelle {part}", + "Apply to Every Part with the Same Material": "Aseta kaikille osille, joilla on sama materiaali", + "Apply to Selected Parts": "Aseta valituille osille", + "Apply to Their Groups": "Aseta niiden ryhmille", + "Apply to every part with the material of {name}": "Aseta kaikille osille, joilla on kohteen {name} materiaali", + "Apply to the group of {name}": "Aseta kohteen {name} ryhmälle", + "Apply to {name}": "Aseta kohteelle {name}", + "Authored": "Laadittu", + "Base color": "Perusväri", + "Brushed metal": "Harjattu metalli", + "Cancel": "Peruuta", + "Categories": "Luokat", + "Category": "Luokka", + "Ceramic": "Keramiikka", + "Clear plastic": "Kirkas muovi", + "Coat": "Pinnoite", + "Coat roughness": "Pinnoitteen karheus", + "Details": "Tiedot", + "Diffuse": "Diffuusi", + "Drop on a part in the viewport": "Pudota katseluikkunassa osan päälle", + "Drop the material on a part": "Pudota materiaali osan päälle", + "Emission": "Emissio", + "Emissive": "Emissiivinen", + "Fabric": "Kangas", + "Favorite": "Suosikki", + "Favorites": "Suosikit", + "Fuzz": "Nukka", + "Gem": "Jalokivi", + "Generic": "Yleinen", + "Give the material a name": "Anna materiaalille nimi", + "Glass": "Lasi", + "In project": "Projektissa", + "Index of refraction": "Taitekerroin", + "Keeps the material of the selected part as one of your own presets.": "Tallentaa valitun osan materiaalin yhdeksi omista esiasetuksistasi.", + "Library": "Kirjasto", + "Liquid": "Neste", + "Loading": "Ladataan", + "Material details": "Materiaalin tiedot", + "Materials": "Materiaalit", + "Materials you apply appear here.": "Käyttämäsi materiaalit näkyvät täällä.", + "Materials you save from the selection appear here.": "Valinnasta tallentamasi materiaalit näkyvät täällä.", + "Measured": "Mitattu", + "Metal": "Metalli", + "Metallic paint": "Metallimaali", + "Metalness": "Metallisuus", + "Name": "Nimi", + "No": "Ei", + "No favorites yet. Right-click a material to add one.": "Ei vielä suosikkeja. Lisää suosikki napsauttamalla materiaalia hiiren kakkospainikkeella.", + "No materials match {query}": "Yksikään materiaali ei vastaa hakua {query}", + "No part here": "Tässä ei ole osaa", + "Nothing in {category} here": "Kohteessa {category} ei ole täällä mitään", + "Opacity": "Peittävyys", + "Paint": "Maali", + "Plastic": "Muovi", + "Published": "Julkaistu", + "Recent": "Viimeaikaiset", + "Remove": "Poista", + "Remove from Library": "Poista kirjastosta", + "Remove {name} from your library? Documents that use it keep their material.": "Poistetaanko {name} kirjastostasi? Sitä käyttävät dokumentit säilyttävät materiaalinsa.", + "Resize the library": "Muuta kirjaston kokoa", + "Roughness": "Karheus", + "Rubber": "Kumi", + "Save": "Tallenna", + "Save Material to Library": "Tallenna materiaali kirjastoon", + "Save Selected Material to Library": "Tallenna valittu materiaali kirjastoon", + "Saved {name} to your library": "{name} tallennettu kirjastoosi", + "Search materials": "Hae materiaaleja", + "Select a part first": "Valitse ensin osa", + "Select a part with a material first": "Valitse ensin osa, jolla on materiaali", + "Shelves": "Hyllyt", + "Source": "Lähde", + "Stone": "Kivi", + "Subsurface": "Pinnanalainen sironta", + "The engine sent the preset in an unknown shape": "Moottori lähetti esiasetuksen tuntemattomassa muodossa", + "The library is empty": "Kirjasto on tyhjä", + "Thin film thickness": "Ohutkalvon paksuus", + "Thin glass": "Ohut lasi", + "Thin walled": "Ohutseinäinen", + "This project has no materials yet.": "Tässä projektissa ei ole vielä materiaaleja.", + "Tile size": "Ruutujen koko", + "Transmission": "Läpäisy", + "Transmission depth": "Läpäisyn syvyys", + "User": "Käyttäjä", + "Wood": "Puu", + "Yes": "Kyllä", + "{n} materials": "{n} materiaalia" +} diff --git a/frontend/src/i18n/modules/library/fr-CA.json b/frontend/src/i18n/modules/library/fr-CA.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/library/fr-CA.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/library/fr.json b/frontend/src/i18n/modules/library/fr.json new file mode 100644 index 00000000..9b372030 --- /dev/null +++ b/frontend/src/i18n/modules/library/fr.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 matériau", + "Abbe number": "Nombre d'Abbe", + "All": "Tout", + "Alt: whole group. Shift: same material.": "Alt : tout le groupe. Maj : même matériau.", + "Anisotropy": "Anisotropie", + "Applied {name} to every part with the material of {part}": "{name} appliqué à toutes les pièces ayant le matériau de {part}", + "Applied {name} to every part with the same material": "{name} appliqué à toutes les pièces ayant le même matériau", + "Applied {name} to the group of {part}": "{name} appliqué au groupe de {part}", + "Applied {name} to the selected parts": "{name} appliqué aux pièces sélectionnées", + "Applied {name} to their groups": "{name} appliqué à leurs groupes", + "Applied {name} to {part}": "{name} appliqué à {part}", + "Apply to Every Part with the Same Material": "Appliquer à toutes les pièces ayant le même matériau", + "Apply to Selected Parts": "Appliquer aux pièces sélectionnées", + "Apply to Their Groups": "Appliquer à leurs groupes", + "Apply to every part with the material of {name}": "Appliquer à toutes les pièces ayant le matériau de {name}", + "Apply to the group of {name}": "Appliquer au groupe de {name}", + "Apply to {name}": "Appliquer à {name}", + "Authored": "Conçu", + "Base color": "Couleur de base", + "Brushed metal": "Métal brossé", + "Cancel": "Annuler", + "Categories": "Catégories", + "Category": "Catégorie", + "Ceramic": "Céramique", + "Clear plastic": "Plastique transparent", + "Coat": "Vernis", + "Coat roughness": "Rugosité du vernis", + "Details": "Détails", + "Diffuse": "Diffus", + "Drop on a part in the viewport": "Déposer sur une pièce dans la vue 3D", + "Drop the material on a part": "Déposer le matériau sur une pièce", + "Emission": "Émission", + "Emissive": "Émissif", + "Fabric": "Tissu", + "Favorite": "Favori", + "Favorites": "Favoris", + "Fuzz": "Duvet", + "Gem": "Gemme", + "Generic": "Générique", + "Give the material a name": "Donnez un nom au matériau", + "Glass": "Verre", + "In project": "Dans le projet", + "Index of refraction": "Indice de réfraction", + "Keeps the material of the selected part as one of your own presets.": "Conserve le matériau de la pièce sélectionnée comme l'un de vos préréglages.", + "Library": "Bibliothèque", + "Liquid": "Liquide", + "Loading": "Chargement", + "Material details": "Détails du matériau", + "Materials": "Matériaux", + "Materials you apply appear here.": "Les matériaux que vous appliquez apparaissent ici.", + "Materials you save from the selection appear here.": "Les matériaux que vous enregistrez depuis la sélection apparaissent ici.", + "Measured": "Mesuré", + "Metal": "Métal", + "Metallic paint": "Peinture métallisée", + "Metalness": "Métallicité", + "Name": "Nom", + "No": "Non", + "No favorites yet. Right-click a material to add one.": "Aucun favori pour le moment. Faites un clic droit sur un matériau pour en ajouter un.", + "No materials match {query}": "Aucun matériau ne correspond à {query}", + "No part here": "Aucune pièce ici", + "Nothing in {category} here": "Rien dans {category} ici", + "Opacity": "Opacité", + "Paint": "Peinture", + "Plastic": "Plastique", + "Published": "Publié", + "Recent": "Récents", + "Remove": "Retirer", + "Remove from Library": "Retirer de la bibliothèque", + "Remove {name} from your library? Documents that use it keep their material.": "Retirer {name} de votre bibliothèque ? Les documents qui l'utilisent conservent leur matériau.", + "Resize the library": "Redimensionner la bibliothèque", + "Roughness": "Rugosité", + "Rubber": "Caoutchouc", + "Save": "Enregistrer", + "Save Material to Library": "Enregistrer le matériau dans la bibliothèque", + "Save Selected Material to Library": "Enregistrer le matériau sélectionné dans la bibliothèque", + "Saved {name} to your library": "{name} enregistré dans votre bibliothèque", + "Search materials": "Rechercher des matériaux", + "Select a part first": "Sélectionnez d'abord une pièce", + "Select a part with a material first": "Sélectionnez d'abord une pièce dotée d'un matériau", + "Shelves": "Étagères", + "Source": "Source", + "Stone": "Pierre", + "Subsurface": "Sous-surface", + "The engine sent the preset in an unknown shape": "Le moteur a envoyé le préréglage sous une forme inconnue", + "The library is empty": "La bibliothèque est vide", + "Thin film thickness": "Épaisseur du film mince", + "Thin glass": "Verre mince", + "Thin walled": "Paroi mince", + "This project has no materials yet.": "Ce projet n'a pas encore de matériaux.", + "Tile size": "Taille des vignettes", + "Transmission": "Transmission", + "Transmission depth": "Profondeur de transmission", + "User": "Personnel", + "Wood": "Bois", + "Yes": "Oui", + "{n} materials": "{n} matériaux" +} diff --git a/frontend/src/i18n/modules/library/hu.json b/frontend/src/i18n/modules/library/hu.json new file mode 100644 index 00000000..0b037a05 --- /dev/null +++ b/frontend/src/i18n/modules/library/hu.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 anyag", + "Abbe number": "Abbe-szám", + "All": "Mind", + "Alt: whole group. Shift: same material.": "Alt: az egész csoport. Shift: ugyanaz az anyag.", + "Anisotropy": "Anizotrópia", + "Applied {name} to every part with the material of {part}": "A(z) {name} alkalmazva az összes alkatrészre, amelynek a(z) {part} anyaga van", + "Applied {name} to every part with the same material": "A(z) {name} alkalmazva az összes azonos anyagú alkatrészre", + "Applied {name} to the group of {part}": "A(z) {name} alkalmazva a(z) {part} csoportjára", + "Applied {name} to the selected parts": "A(z) {name} alkalmazva a kijelölt alkatrészekre", + "Applied {name} to their groups": "A(z) {name} alkalmazva a csoportjaikra", + "Applied {name} to {part}": "A(z) {name} alkalmazva erre: {part}", + "Apply to Every Part with the Same Material": "Alkalmazás az összes azonos anyagú alkatrészre", + "Apply to Selected Parts": "Alkalmazás a kijelölt alkatrészekre", + "Apply to Their Groups": "Alkalmazás a csoportjaikra", + "Apply to every part with the material of {name}": "Alkalmazás az összes alkatrészre, amelynek a(z) {name} anyaga van", + "Apply to the group of {name}": "Alkalmazás a(z) {name} csoportjára", + "Apply to {name}": "Alkalmazás erre: {name}", + "Authored": "Saját készítésű", + "Base color": "Alapszín", + "Brushed metal": "Szálcsiszolt fém", + "Cancel": "Mégse", + "Categories": "Kategóriák", + "Category": "Kategória", + "Ceramic": "Kerámia", + "Clear plastic": "Átlátszó műanyag", + "Coat": "Lakkréteg", + "Coat roughness": "Lakkréteg érdessége", + "Details": "Részletek", + "Diffuse": "Diffúz", + "Drop on a part in the viewport": "Ejtse egy alkatrészre a nézetablakban", + "Drop the material on a part": "Ejtse az anyagot egy alkatrészre", + "Emission": "Emisszió", + "Emissive": "Emissziós", + "Fabric": "Szövet", + "Favorite": "Kedvenc", + "Favorites": "Kedvencek", + "Fuzz": "Pihe", + "Gem": "Drágakő", + "Generic": "Általános", + "Give the material a name": "Adjon nevet az anyagnak", + "Glass": "Üveg", + "In project": "A projektben", + "Index of refraction": "Törésmutató", + "Keeps the material of the selected part as one of your own presets.": "A kijelölt alkatrész anyagát a saját előbeállításai egyikeként tárolja.", + "Library": "Könyvtár", + "Liquid": "Folyadék", + "Loading": "Betöltés", + "Material details": "Anyag adatai", + "Materials": "Anyagok", + "Materials you apply appear here.": "Az Ön által alkalmazott anyagok itt jelennek meg.", + "Materials you save from the selection appear here.": "A kijelölésből elmentett anyagok itt jelennek meg.", + "Measured": "Mért", + "Metal": "Fém", + "Metallic paint": "Metálfesték", + "Metalness": "Fémesség", + "Name": "Név", + "No": "Nem", + "No favorites yet. Right-click a material to add one.": "Még nincsenek kedvencek. Kattintson jobb gombbal egy anyagra a hozzáadáshoz.", + "No materials match {query}": "Egyetlen anyag sem felel meg ennek: {query}", + "No part here": "Itt nincs alkatrész", + "Nothing in {category} here": "A(z) {category} kategóriában itt nincs semmi", + "Opacity": "Átlátszatlanság", + "Paint": "Festék", + "Plastic": "Műanyag", + "Published": "Közzétéve", + "Recent": "Legutóbbiak", + "Remove": "Eltávolítás", + "Remove from Library": "Eltávolítás a könyvtárból", + "Remove {name} from your library? Documents that use it keep their material.": "Eltávolítja a(z) {name} anyagot a könyvtárából? Az azt használó dokumentumok megtartják az anyagukat.", + "Resize the library": "A könyvtár átméretezése", + "Roughness": "Érdesség", + "Rubber": "Gumi", + "Save": "Mentés", + "Save Material to Library": "Anyag mentése a könyvtárba", + "Save Selected Material to Library": "A kijelölt anyag mentése a könyvtárba", + "Saved {name} to your library": "A(z) {name} elmentve a könyvtárba", + "Search materials": "Anyagok keresése", + "Select a part first": "Előbb jelöljön ki egy alkatrészt", + "Select a part with a material first": "Előbb jelöljön ki egy anyaggal rendelkező alkatrészt", + "Shelves": "Polcok", + "Source": "Forrás", + "Stone": "Kő", + "Subsurface": "Felszín alatti szóródás", + "The engine sent the preset in an unknown shape": "A motor ismeretlen alakban küldte el az előbeállítást", + "The library is empty": "A könyvtár üres", + "Thin film thickness": "Vékonyréteg vastagsága", + "Thin glass": "Vékony üveg", + "Thin walled": "Vékony falú", + "This project has no materials yet.": "Ebben a projektben még nincsenek anyagok.", + "Tile size": "Csempék mérete", + "Transmission": "Áteresztés", + "Transmission depth": "Áteresztés mélysége", + "User": "Felhasználó", + "Wood": "Fa", + "Yes": "Igen", + "{n} materials": "{n} anyag" +} diff --git a/frontend/src/i18n/modules/library/id.json b/frontend/src/i18n/modules/library/id.json new file mode 100644 index 00000000..3dc301a5 --- /dev/null +++ b/frontend/src/i18n/modules/library/id.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 material", + "Abbe number": "Bilangan Abbe", + "All": "Semua", + "Alt: whole group. Shift: same material.": "Alt: seluruh grup. Shift: material yang sama.", + "Anisotropy": "Anisotropi", + "Applied {name} to every part with the material of {part}": "{name} diterapkan ke semua bagian dengan material {part}", + "Applied {name} to every part with the same material": "{name} diterapkan ke semua bagian dengan material yang sama", + "Applied {name} to the group of {part}": "{name} diterapkan ke grup {part}", + "Applied {name} to the selected parts": "{name} diterapkan ke bagian yang dipilih", + "Applied {name} to their groups": "{name} diterapkan ke grup mereka", + "Applied {name} to {part}": "{name} diterapkan ke {part}", + "Apply to Every Part with the Same Material": "Terapkan ke Semua Bagian dengan Material yang Sama", + "Apply to Selected Parts": "Terapkan ke Bagian yang Dipilih", + "Apply to Their Groups": "Terapkan ke Grup Mereka", + "Apply to every part with the material of {name}": "Terapkan ke semua bagian dengan material {name}", + "Apply to the group of {name}": "Terapkan ke grup {name}", + "Apply to {name}": "Terapkan ke {name}", + "Authored": "Buatan sendiri", + "Base color": "Warna dasar", + "Brushed metal": "Logam sikat", + "Cancel": "Batal", + "Categories": "Kategori", + "Category": "Kategori", + "Ceramic": "Keramik", + "Clear plastic": "Plastik bening", + "Coat": "Coat", + "Coat roughness": "Roughness coat", + "Details": "Detail", + "Diffuse": "Diffuse", + "Drop on a part in the viewport": "Lepas pada bagian di viewport", + "Drop the material on a part": "Lepas material pada sebuah bagian", + "Emission": "Emisi", + "Emissive": "Emisif", + "Fabric": "Kain", + "Favorite": "Favorit", + "Favorites": "Favorit", + "Fuzz": "Fuzz", + "Gem": "Permata", + "Generic": "Umum", + "Give the material a name": "Beri nama material", + "Glass": "Kaca", + "In project": "Dalam proyek", + "Index of refraction": "Indeks bias", + "Keeps the material of the selected part as one of your own presets.": "Simpan material bagian yang dipilih sebagai salah satu preset Anda sendiri.", + "Library": "Pustaka", + "Liquid": "Cairan", + "Loading": "Memuat", + "Material details": "Detail material", + "Materials": "Material", + "Materials you apply appear here.": "Material yang Anda terapkan muncul di sini.", + "Materials you save from the selection appear here.": "Material yang Anda simpan dari pilihan muncul di sini.", + "Measured": "Terukur", + "Metal": "Logam", + "Metallic paint": "Cat metalik", + "Metalness": "Metalness", + "Name": "Nama", + "No": "Tidak", + "No favorites yet. Right-click a material to add one.": "Belum ada favorit. Klik kanan material untuk menambahkannya.", + "No materials match {query}": "Tidak ada material yang cocok dengan {query}", + "No part here": "Tidak ada bagian di sini", + "Nothing in {category} here": "Tidak ada apa pun di {category} di sini", + "Opacity": "Opasitas", + "Paint": "Cat", + "Plastic": "Plastik", + "Published": "Dipublikasikan", + "Recent": "Terbaru", + "Remove": "Hapus", + "Remove from Library": "Hapus dari Pustaka", + "Remove {name} from your library? Documents that use it keep their material.": "Hapus {name} dari pustaka Anda? Dokumen yang memakainya tetap mempertahankan materialnya.", + "Resize the library": "Ubah ukuran pustaka", + "Roughness": "Roughness", + "Rubber": "Karet", + "Save": "Simpan", + "Save Material to Library": "Simpan Material ke Pustaka", + "Save Selected Material to Library": "Simpan Material Terpilih ke Pustaka", + "Saved {name} to your library": "{name} disimpan ke pustaka Anda", + "Search materials": "Cari material", + "Select a part first": "Pilih bagian terlebih dahulu", + "Select a part with a material first": "Pilih bagian yang memiliki material terlebih dahulu", + "Shelves": "Rak", + "Source": "Sumber", + "Stone": "Batu", + "Subsurface": "Subsurface", + "The engine sent the preset in an unknown shape": "Mesin mengirim preset dalam bentuk yang tidak dikenal", + "The library is empty": "Pustaka kosong", + "Thin film thickness": "Ketebalan film tipis", + "Thin glass": "Kaca tipis", + "Thin walled": "Berdinding tipis", + "This project has no materials yet.": "Proyek ini belum memiliki material.", + "Tile size": "Ukuran ubin", + "Transmission": "Transmisi", + "Transmission depth": "Kedalaman transmisi", + "User": "Pengguna", + "Wood": "Kayu", + "Yes": "Ya", + "{n} materials": "{n} material" +} diff --git a/frontend/src/i18n/modules/library/it.json b/frontend/src/i18n/modules/library/it.json new file mode 100644 index 00000000..07eee416 --- /dev/null +++ b/frontend/src/i18n/modules/library/it.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 materiale", + "Abbe number": "Numero di Abbe", + "All": "Tutto", + "Alt: whole group. Shift: same material.": "Alt: tutto il gruppo. Maiusc: stesso materiale.", + "Anisotropy": "Anisotropia", + "Applied {name} to every part with the material of {part}": "{name} applicato a tutte le parti con il materiale di {part}", + "Applied {name} to every part with the same material": "{name} applicato a tutte le parti con lo stesso materiale", + "Applied {name} to the group of {part}": "{name} applicato al gruppo di {part}", + "Applied {name} to the selected parts": "{name} applicato alle parti selezionate", + "Applied {name} to their groups": "{name} applicato ai loro gruppi", + "Applied {name} to {part}": "{name} applicato a {part}", + "Apply to Every Part with the Same Material": "Applica a tutte le parti con lo stesso materiale", + "Apply to Selected Parts": "Applica alle parti selezionate", + "Apply to Their Groups": "Applica ai loro gruppi", + "Apply to every part with the material of {name}": "Applica a tutte le parti con il materiale di {name}", + "Apply to the group of {name}": "Applica al gruppo di {name}", + "Apply to {name}": "Applica a {name}", + "Authored": "Progettato", + "Base color": "Colore di base", + "Brushed metal": "Metallo spazzolato", + "Cancel": "Annulla", + "Categories": "Categorie", + "Category": "Categoria", + "Ceramic": "Ceramica", + "Clear plastic": "Plastica trasparente", + "Coat": "Vernice", + "Coat roughness": "Rugosità della vernice", + "Details": "Dettagli", + "Diffuse": "Diffuso", + "Drop on a part in the viewport": "Rilascia su una parte nel viewport", + "Drop the material on a part": "Rilascia il materiale su una parte", + "Emission": "Emissione", + "Emissive": "Emissivo", + "Fabric": "Tessuto", + "Favorite": "Preferito", + "Favorites": "Preferiti", + "Fuzz": "Peluria", + "Gem": "Gemma", + "Generic": "Generico", + "Give the material a name": "Dai un nome al materiale", + "Glass": "Vetro", + "In project": "Nel progetto", + "Index of refraction": "Indice di rifrazione", + "Keeps the material of the selected part as one of your own presets.": "Conserva il materiale della parte selezionata come uno dei tuoi preset.", + "Library": "Libreria", + "Liquid": "Liquido", + "Loading": "Caricamento", + "Material details": "Dettagli del materiale", + "Materials": "Materiali", + "Materials you apply appear here.": "Qui compaiono i materiali che applichi.", + "Materials you save from the selection appear here.": "Qui compaiono i materiali che salvi dalla selezione.", + "Measured": "Misurato", + "Metal": "Metallo", + "Metallic paint": "Vernice metallizzata", + "Metalness": "Metallicità", + "Name": "Nome", + "No": "No", + "No favorites yet. Right-click a material to add one.": "Ancora nessun preferito. Fai clic con il tasto destro su un materiale per aggiungerne uno.", + "No materials match {query}": "Nessun materiale corrisponde a {query}", + "No part here": "Nessuna parte qui", + "Nothing in {category} here": "Nulla in {category} qui", + "Opacity": "Opacità", + "Paint": "Vernice", + "Plastic": "Plastica", + "Published": "Pubblicato", + "Recent": "Recenti", + "Remove": "Rimuovi", + "Remove from Library": "Rimuovi dalla libreria", + "Remove {name} from your library? Documents that use it keep their material.": "Rimuovere {name} dalla tua libreria? I documenti che lo usano mantengono il loro materiale.", + "Resize the library": "Ridimensiona la libreria", + "Roughness": "Rugosità", + "Rubber": "Gomma", + "Save": "Salva", + "Save Material to Library": "Salva materiale nella libreria", + "Save Selected Material to Library": "Salva il materiale selezionato nella libreria", + "Saved {name} to your library": "{name} salvato nella tua libreria", + "Search materials": "Cerca materiali", + "Select a part first": "Seleziona prima una parte", + "Select a part with a material first": "Seleziona prima una parte con un materiale", + "Shelves": "Scaffali", + "Source": "Origine", + "Stone": "Pietra", + "Subsurface": "Sottosuperficie", + "The engine sent the preset in an unknown shape": "Il motore ha inviato il preset in una forma sconosciuta", + "The library is empty": "La libreria è vuota", + "Thin film thickness": "Spessore del film sottile", + "Thin glass": "Vetro sottile", + "Thin walled": "Parete sottile", + "This project has no materials yet.": "Questo progetto non ha ancora materiali.", + "Tile size": "Dimensione delle anteprime", + "Transmission": "Trasmissione", + "Transmission depth": "Profondità di trasmissione", + "User": "Utente", + "Wood": "Legno", + "Yes": "Sì", + "{n} materials": "{n} materiali" +} diff --git a/frontend/src/i18n/modules/library/ja.json b/frontend/src/i18n/modules/library/ja.json new file mode 100644 index 00000000..fca2831e --- /dev/null +++ b/frontend/src/i18n/modules/library/ja.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 件のマテリアル", + "Abbe number": "アッベ数", + "All": "すべて", + "Alt: whole group. Shift: same material.": "Alt: グループ全体。Shift: 同じマテリアル。", + "Anisotropy": "異方性", + "Applied {name} to every part with the material of {part}": "{part} のマテリアルを使うすべてのパーツに {name} を適用しました", + "Applied {name} to every part with the same material": "同じマテリアルを使うすべてのパーツに {name} を適用しました", + "Applied {name} to the group of {part}": "{part} のグループに {name} を適用しました", + "Applied {name} to the selected parts": "選択したパーツに {name} を適用しました", + "Applied {name} to their groups": "それぞれのグループに {name} を適用しました", + "Applied {name} to {part}": "{part} に {name} を適用しました", + "Apply to Every Part with the Same Material": "同じマテリアルのすべてのパーツに適用", + "Apply to Selected Parts": "選択したパーツに適用", + "Apply to Their Groups": "それぞれのグループに適用", + "Apply to every part with the material of {name}": "{name} のマテリアルを使うすべてのパーツに適用", + "Apply to the group of {name}": "{name} のグループに適用", + "Apply to {name}": "{name} に適用", + "Authored": "自作", + "Base color": "ベースカラー", + "Brushed metal": "ブラッシュドメタル", + "Cancel": "キャンセル", + "Categories": "カテゴリ", + "Category": "カテゴリ", + "Ceramic": "セラミック", + "Clear plastic": "透明プラスチック", + "Coat": "コート", + "Coat roughness": "コートラフネス", + "Details": "詳細", + "Diffuse": "ディフューズ", + "Drop on a part in the viewport": "ビューポートのパーツにドロップ", + "Drop the material on a part": "マテリアルをパーツにドロップ", + "Emission": "エミッション", + "Emissive": "エミッシブ", + "Fabric": "ファブリック", + "Favorite": "お気に入り", + "Favorites": "お気に入り", + "Fuzz": "ファズ", + "Gem": "宝石", + "Generic": "汎用", + "Give the material a name": "マテリアルに名前を付けてください", + "Glass": "ガラス", + "In project": "プロジェクト内", + "Index of refraction": "屈折率", + "Keeps the material of the selected part as one of your own presets.": "選択したパーツのマテリアルを、自分のプリセットの 1 つとして保存します。", + "Library": "ライブラリ", + "Liquid": "液体", + "Loading": "読み込み中", + "Material details": "マテリアルの詳細", + "Materials": "マテリアル", + "Materials you apply appear here.": "適用したマテリアルがここに表示されます。", + "Materials you save from the selection appear here.": "選択から保存したマテリアルがここに表示されます。", + "Measured": "実測", + "Metal": "メタル", + "Metallic paint": "メタリックペイント", + "Metalness": "メタルネス", + "Name": "名前", + "No": "いいえ", + "No favorites yet. Right-click a material to add one.": "お気に入りはまだありません。マテリアルを右クリックして追加してください。", + "No materials match {query}": "{query} に一致するマテリアルはありません", + "No part here": "ここにパーツはありません", + "Nothing in {category} here": "{category} にはまだ何もありません", + "Opacity": "不透明度", + "Paint": "塗料", + "Plastic": "プラスチック", + "Published": "公開", + "Recent": "最近", + "Remove": "削除", + "Remove from Library": "ライブラリから削除", + "Remove {name} from your library? Documents that use it keep their material.": "{name} をライブラリから削除しますか? このマテリアルを使っているドキュメントは、そのマテリアルを保持します。", + "Resize the library": "ライブラリのサイズを変更", + "Roughness": "ラフネス", + "Rubber": "ゴム", + "Save": "保存", + "Save Material to Library": "マテリアルをライブラリに保存", + "Save Selected Material to Library": "選択したマテリアルをライブラリに保存", + "Saved {name} to your library": "{name} をライブラリに保存しました", + "Search materials": "マテリアルを検索", + "Select a part first": "先にパーツを選択してください", + "Select a part with a material first": "先にマテリアルのあるパーツを選択してください", + "Shelves": "シェルフ", + "Source": "ソース", + "Stone": "石", + "Subsurface": "サブサーフェス", + "The engine sent the preset in an unknown shape": "エンジンが不明な形式でプリセットを送ってきました", + "The library is empty": "ライブラリは空です", + "Thin film thickness": "薄膜の厚さ", + "Thin glass": "薄いガラス", + "Thin walled": "薄肉", + "This project has no materials yet.": "このプロジェクトにはまだマテリアルがありません。", + "Tile size": "タイルサイズ", + "Transmission": "トランスミッション", + "Transmission depth": "トランスミッション深度", + "User": "ユーザー", + "Wood": "木材", + "Yes": "はい", + "{n} materials": "{n} 件のマテリアル" +} diff --git a/frontend/src/i18n/modules/library/ko.json b/frontend/src/i18n/modules/library/ko.json new file mode 100644 index 00000000..4ff92d73 --- /dev/null +++ b/frontend/src/i18n/modules/library/ko.json @@ -0,0 +1,98 @@ +{ + "1 material": "머티리얼 1개", + "Abbe number": "아베 수", + "All": "모두", + "Alt: whole group. Shift: same material.": "Alt: 그룹 전체. Shift: 같은 머티리얼.", + "Anisotropy": "이방성", + "Applied {name} to every part with the material of {part}": "{part}의 머티리얼을 쓰는 모든 파트에 {name}을(를) 적용했습니다", + "Applied {name} to every part with the same material": "같은 머티리얼을 쓰는 모든 파트에 {name}을(를) 적용했습니다", + "Applied {name} to the group of {part}": "{part}의 그룹에 {name}을(를) 적용했습니다", + "Applied {name} to the selected parts": "선택한 파트에 {name}을(를) 적용했습니다", + "Applied {name} to their groups": "각 그룹에 {name}을(를) 적용했습니다", + "Applied {name} to {part}": "{part}에 {name}을(를) 적용했습니다", + "Apply to Every Part with the Same Material": "같은 머티리얼의 모든 파트에 적용", + "Apply to Selected Parts": "선택한 파트에 적용", + "Apply to Their Groups": "각 그룹에 적용", + "Apply to every part with the material of {name}": "{name}의 머티리얼을 쓰는 모든 파트에 적용", + "Apply to the group of {name}": "{name}의 그룹에 적용", + "Apply to {name}": "{name}에 적용", + "Authored": "직접 제작", + "Base color": "베이스 컬러", + "Brushed metal": "브러시드 메탈", + "Cancel": "취소", + "Categories": "카테고리", + "Category": "카테고리", + "Ceramic": "세라믹", + "Clear plastic": "투명 플라스틱", + "Coat": "코트", + "Coat roughness": "코트 러프니스", + "Details": "상세 정보", + "Diffuse": "디퓨즈", + "Drop on a part in the viewport": "뷰포트의 파트에 놓기", + "Drop the material on a part": "머티리얼을 파트에 놓기", + "Emission": "발광", + "Emissive": "발광", + "Fabric": "패브릭", + "Favorite": "즐겨찾기", + "Favorites": "즐겨찾기", + "Fuzz": "퍼즈", + "Gem": "보석", + "Generic": "일반", + "Give the material a name": "머티리얼 이름을 지정하세요", + "Glass": "유리", + "In project": "프로젝트 내", + "Index of refraction": "굴절률", + "Keeps the material of the selected part as one of your own presets.": "선택한 파트의 머티리얼을 내 프리셋 중 하나로 보관합니다.", + "Library": "라이브러리", + "Liquid": "액체", + "Loading": "불러오는 중", + "Material details": "머티리얼 상세 정보", + "Materials": "머티리얼", + "Materials you apply appear here.": "적용한 머티리얼이 여기에 표시됩니다.", + "Materials you save from the selection appear here.": "선택 항목에서 저장한 머티리얼이 여기에 표시됩니다.", + "Measured": "실측", + "Metal": "금속", + "Metallic paint": "메탈릭 페인트", + "Metalness": "메탈니스", + "Name": "이름", + "No": "아니요", + "No favorites yet. Right-click a material to add one.": "즐겨찾기가 아직 없습니다. 머티리얼을 마우스 오른쪽 버튼으로 클릭해 추가하세요.", + "No materials match {query}": "{query}와(과) 일치하는 머티리얼이 없습니다", + "No part here": "여기에 파트가 없습니다", + "Nothing in {category} here": "{category}에 해당하는 항목이 없습니다", + "Opacity": "불투명도", + "Paint": "페인트", + "Plastic": "플라스틱", + "Published": "게시됨", + "Recent": "최근", + "Remove": "제거", + "Remove from Library": "라이브러리에서 제거", + "Remove {name} from your library? Documents that use it keep their material.": "{name}을(를) 라이브러리에서 제거하시겠습니까? 이 머티리얼을 사용하는 문서는 머티리얼을 그대로 유지합니다.", + "Resize the library": "라이브러리 크기 조절", + "Roughness": "러프니스", + "Rubber": "고무", + "Save": "저장", + "Save Material to Library": "머티리얼을 라이브러리에 저장", + "Save Selected Material to Library": "선택한 머티리얼을 라이브러리에 저장", + "Saved {name} to your library": "{name}을(를) 라이브러리에 저장했습니다", + "Search materials": "머티리얼 검색", + "Select a part first": "먼저 파트를 선택하세요", + "Select a part with a material first": "먼저 머티리얼이 있는 파트를 선택하세요", + "Shelves": "보관함", + "Source": "소스", + "Stone": "석재", + "Subsurface": "서브서피스", + "The engine sent the preset in an unknown shape": "엔진이 알 수 없는 형태로 프리셋을 보냈습니다", + "The library is empty": "라이브러리가 비어 있습니다", + "Thin film thickness": "박막 두께", + "Thin glass": "얇은 유리", + "Thin walled": "얇은 벽", + "This project has no materials yet.": "이 프로젝트에는 아직 머티리얼이 없습니다.", + "Tile size": "타일 크기", + "Transmission": "트랜스미션", + "Transmission depth": "트랜스미션 깊이", + "User": "사용자", + "Wood": "목재", + "Yes": "예", + "{n} materials": "머티리얼 {n}개" +} diff --git a/frontend/src/i18n/modules/library/nb.json b/frontend/src/i18n/modules/library/nb.json new file mode 100644 index 00000000..d2d3f611 --- /dev/null +++ b/frontend/src/i18n/modules/library/nb.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 materiale", + "Abbe number": "Abbetall", + "All": "Alle", + "Alt: whole group. Shift: same material.": "Alt: hele gruppen. Shift: samme materiale.", + "Anisotropy": "Anisotropi", + "Applied {name} to every part with the material of {part}": "Brukte {name} på alle deler med materialet til {part}", + "Applied {name} to every part with the same material": "Brukte {name} på alle deler med samme materiale", + "Applied {name} to the group of {part}": "Brukte {name} på gruppen til {part}", + "Applied {name} to the selected parts": "Brukte {name} på de valgte delene", + "Applied {name} to their groups": "Brukte {name} på gruppene deres", + "Applied {name} to {part}": "Brukte {name} på {part}", + "Apply to Every Part with the Same Material": "Bruk på alle deler med samme materiale", + "Apply to Selected Parts": "Bruk på valgte deler", + "Apply to Their Groups": "Bruk på gruppene deres", + "Apply to every part with the material of {name}": "Bruk på alle deler med materialet til {name}", + "Apply to the group of {name}": "Bruk på gruppen til {name}", + "Apply to {name}": "Bruk på {name}", + "Authored": "Håndlaget", + "Base color": "Basisfarge", + "Brushed metal": "Børstet metall", + "Cancel": "Avbryt", + "Categories": "Kategorier", + "Category": "Kategori", + "Ceramic": "Keramikk", + "Clear plastic": "Klar plast", + "Coat": "Coating", + "Coat roughness": "Coatingruhet", + "Details": "Detaljer", + "Diffuse": "Diffus", + "Drop on a part in the viewport": "Slipp på en del i visningsvinduet", + "Drop the material on a part": "Slipp materialet på en del", + "Emission": "Emisjon", + "Emissive": "Emissiv", + "Fabric": "Stoff", + "Favorite": "Favoritt", + "Favorites": "Favoritter", + "Fuzz": "Fuzz", + "Gem": "Edelstein", + "Generic": "Generelt", + "Give the material a name": "Gi materialet et navn", + "Glass": "Glass", + "In project": "I prosjektet", + "Index of refraction": "Brytningsindeks", + "Keeps the material of the selected part as one of your own presets.": "Lagrer materialet til den valgte delen som en av dine egne forhåndsinnstillinger.", + "Library": "Bibliotek", + "Liquid": "Væske", + "Loading": "Laster", + "Material details": "Materialdetaljer", + "Materials": "Materialer", + "Materials you apply appear here.": "Materialer du bruker, vises her.", + "Materials you save from the selection appear here.": "Materialer du lagrer fra markeringen, vises her.", + "Measured": "Målt", + "Metal": "Metall", + "Metallic paint": "Metallic lakk", + "Metalness": "Metalness", + "Name": "Navn", + "No": "Nei", + "No favorites yet. Right-click a material to add one.": "Ingen favoritter ennå. Høyreklikk på et materiale for å legge til en.", + "No materials match {query}": "Ingen materialer samsvarer med {query}", + "No part here": "Ingen del her", + "Nothing in {category} here": "Ingenting i {category} her", + "Opacity": "Opasitet", + "Paint": "Maling", + "Plastic": "Plast", + "Published": "Publisert", + "Recent": "Nylige", + "Remove": "Fjern", + "Remove from Library": "Fjern fra biblioteket", + "Remove {name} from your library? Documents that use it keep their material.": "Fjerne {name} fra biblioteket ditt? Dokumenter som bruker det, beholder materialet sitt.", + "Resize the library": "Endre størrelsen på biblioteket", + "Roughness": "Ruhet", + "Rubber": "Gummi", + "Save": "Lagre", + "Save Material to Library": "Lagre materiale i biblioteket", + "Save Selected Material to Library": "Lagre valgt materiale i biblioteket", + "Saved {name} to your library": "{name} er lagret i biblioteket ditt", + "Search materials": "Søk i materialer", + "Select a part first": "Velg en del først", + "Select a part with a material first": "Velg først en del med et materiale", + "Shelves": "Hyller", + "Source": "Kilde", + "Stone": "Stein", + "Subsurface": "Subsurface", + "The engine sent the preset in an unknown shape": "Motoren sendte forhåndsinnstillingen i en ukjent form", + "The library is empty": "Biblioteket er tomt", + "Thin film thickness": "Tykkelse på tynn film", + "Thin glass": "Tynt glass", + "Thin walled": "Tynnvegget", + "This project has no materials yet.": "Dette prosjektet har ingen materialer ennå.", + "Tile size": "Miniatyrstørrelse", + "Transmission": "Transmisjon", + "Transmission depth": "Transmisjonsdybde", + "User": "Bruker", + "Wood": "Tre", + "Yes": "Ja", + "{n} materials": "{n} materialer" +} diff --git a/frontend/src/i18n/modules/library/nl.json b/frontend/src/i18n/modules/library/nl.json new file mode 100644 index 00000000..52336395 --- /dev/null +++ b/frontend/src/i18n/modules/library/nl.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 materiaal", + "Abbe number": "Abbegetal", + "All": "Alle", + "Alt: whole group. Shift: same material.": "Alt: hele groep. Shift: hetzelfde materiaal.", + "Anisotropy": "Anisotropie", + "Applied {name} to every part with the material of {part}": "{name} toegepast op elk onderdeel met het materiaal van {part}", + "Applied {name} to every part with the same material": "{name} toegepast op elk onderdeel met hetzelfde materiaal", + "Applied {name} to the group of {part}": "{name} toegepast op de groep van {part}", + "Applied {name} to the selected parts": "{name} toegepast op de geselecteerde onderdelen", + "Applied {name} to their groups": "{name} toegepast op hun groepen", + "Applied {name} to {part}": "{name} toegepast op {part}", + "Apply to Every Part with the Same Material": "Toepassen op elk onderdeel met hetzelfde materiaal", + "Apply to Selected Parts": "Toepassen op geselecteerde onderdelen", + "Apply to Their Groups": "Toepassen op hun groepen", + "Apply to every part with the material of {name}": "Toepassen op elk onderdeel met het materiaal van {name}", + "Apply to the group of {name}": "Toepassen op de groep van {name}", + "Apply to {name}": "Toepassen op {name}", + "Authored": "Handmatig", + "Base color": "Basiskleur", + "Brushed metal": "Geborsteld metaal", + "Cancel": "Annuleren", + "Categories": "Categorieën", + "Category": "Categorie", + "Ceramic": "Keramiek", + "Clear plastic": "Doorzichtig kunststof", + "Coat": "Coating", + "Coat roughness": "Coatingruwheid", + "Details": "Details", + "Diffuse": "Diffuus", + "Drop on a part in the viewport": "Zet neer op een onderdeel in de viewport", + "Drop the material on a part": "Zet het materiaal neer op een onderdeel", + "Emission": "Emissie", + "Emissive": "Emissief", + "Fabric": "Stof", + "Favorite": "Favoriet", + "Favorites": "Favorieten", + "Fuzz": "Fuzz", + "Gem": "Edelsteen", + "Generic": "Algemeen", + "Give the material a name": "Geef het materiaal een naam", + "Glass": "Glas", + "In project": "In project", + "Index of refraction": "Brekingsindex", + "Keeps the material of the selected part as one of your own presets.": "Bewaart het materiaal van het geselecteerde onderdeel als een van je eigen voorinstellingen.", + "Library": "Bibliotheek", + "Liquid": "Vloeistof", + "Loading": "Laden", + "Material details": "Materiaaldetails", + "Materials": "Materialen", + "Materials you apply appear here.": "Materialen die je toepast, verschijnen hier.", + "Materials you save from the selection appear here.": "Materialen die je uit de selectie opslaat, verschijnen hier.", + "Measured": "Gemeten", + "Metal": "Metaal", + "Metallic paint": "Metallic verf", + "Metalness": "Metalness", + "Name": "Naam", + "No": "Nee", + "No favorites yet. Right-click a material to add one.": "Nog geen favorieten. Klik met de rechtermuisknop op een materiaal om er een toe te voegen.", + "No materials match {query}": "Geen materialen komen overeen met {query}", + "No part here": "Hier is geen onderdeel", + "Nothing in {category} here": "Hier staat niets in {category}", + "Opacity": "Dekking", + "Paint": "Verf", + "Plastic": "Kunststof", + "Published": "Gepubliceerd", + "Recent": "Recent", + "Remove": "Verwijderen", + "Remove from Library": "Uit bibliotheek verwijderen", + "Remove {name} from your library? Documents that use it keep their material.": "{name} uit je bibliotheek verwijderen? Documenten die het gebruiken, behouden hun materiaal.", + "Resize the library": "Het formaat van de bibliotheek wijzigen", + "Roughness": "Ruwheid", + "Rubber": "Rubber", + "Save": "Opslaan", + "Save Material to Library": "Materiaal opslaan in bibliotheek", + "Save Selected Material to Library": "Geselecteerd materiaal opslaan in bibliotheek", + "Saved {name} to your library": "{name} is opgeslagen in je bibliotheek", + "Search materials": "Materialen zoeken", + "Select a part first": "Selecteer eerst een onderdeel", + "Select a part with a material first": "Selecteer eerst een onderdeel met een materiaal", + "Shelves": "Schappen", + "Source": "Bron", + "Stone": "Steen", + "Subsurface": "Subsurface", + "The engine sent the preset in an unknown shape": "De engine stuurde de voorinstelling in een onbekende vorm", + "The library is empty": "De bibliotheek is leeg", + "Thin film thickness": "Dikte van de dunne film", + "Thin glass": "Dun glas", + "Thin walled": "Dunwandig", + "This project has no materials yet.": "Dit project heeft nog geen materialen.", + "Tile size": "Miniatuurgrootte", + "Transmission": "Transmissie", + "Transmission depth": "Transmissiediepte", + "User": "Gebruiker", + "Wood": "Hout", + "Yes": "Ja", + "{n} materials": "{n} materialen" +} diff --git a/frontend/src/i18n/modules/library/pl.json b/frontend/src/i18n/modules/library/pl.json new file mode 100644 index 00000000..740749e9 --- /dev/null +++ b/frontend/src/i18n/modules/library/pl.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 materiał", + "Abbe number": "Liczba Abbego", + "All": "Wszystko", + "Alt: whole group. Shift: same material.": "Alt: cała grupa. Shift: ten sam materiał.", + "Anisotropy": "Anizotropia", + "Applied {name} to every part with the material of {part}": "Zastosowano {name} do wszystkich części z materiałem części {part}", + "Applied {name} to every part with the same material": "Zastosowano {name} do wszystkich części z tym samym materiałem", + "Applied {name} to the group of {part}": "Zastosowano {name} do grupy części {part}", + "Applied {name} to the selected parts": "Zastosowano {name} do zaznaczonych części", + "Applied {name} to their groups": "Zastosowano {name} do ich grup", + "Applied {name} to {part}": "Zastosowano {name} do {part}", + "Apply to Every Part with the Same Material": "Zastosuj do wszystkich części z tym samym materiałem", + "Apply to Selected Parts": "Zastosuj do zaznaczonych części", + "Apply to Their Groups": "Zastosuj do ich grup", + "Apply to every part with the material of {name}": "Zastosuj do wszystkich części z materiałem części {name}", + "Apply to the group of {name}": "Zastosuj do grupy części {name}", + "Apply to {name}": "Zastosuj do {name}", + "Authored": "Autorskie", + "Base color": "Kolor bazowy", + "Brushed metal": "Szczotkowany metal", + "Cancel": "Anuluj", + "Categories": "Kategorie", + "Category": "Kategoria", + "Ceramic": "Ceramika", + "Clear plastic": "Przezroczyste tworzywo", + "Coat": "Powłoka", + "Coat roughness": "Chropowatość powłoki", + "Details": "Szczegóły", + "Diffuse": "Rozproszenie", + "Drop on a part in the viewport": "Upuść na część w widoku 3D", + "Drop the material on a part": "Upuść materiał na część", + "Emission": "Emisja", + "Emissive": "Emisyjny", + "Fabric": "Tkanina", + "Favorite": "Ulubiony", + "Favorites": "Ulubione", + "Fuzz": "Meszek", + "Gem": "Klejnot", + "Generic": "Ogólny", + "Give the material a name": "Nadaj materiałowi nazwę", + "Glass": "Szkło", + "In project": "W projekcie", + "Index of refraction": "Współczynnik załamania", + "Keeps the material of the selected part as one of your own presets.": "Zachowuje materiał zaznaczonej części jako jeden z Twoich własnych presetów.", + "Library": "Biblioteka", + "Liquid": "Ciecz", + "Loading": "Wczytywanie", + "Material details": "Szczegóły materiału", + "Materials": "Materiały", + "Materials you apply appear here.": "Tutaj pojawiają się materiały, które zastosujesz.", + "Materials you save from the selection appear here.": "Tutaj pojawiają się materiały zapisane z zaznaczenia.", + "Measured": "Mierzone", + "Metal": "Metal", + "Metallic paint": "Lakier metaliczny", + "Metalness": "Metaliczność", + "Name": "Nazwa", + "No": "Nie", + "No favorites yet. Right-click a material to add one.": "Nie ma jeszcze ulubionych. Kliknij materiał prawym przyciskiem myszy, aby dodać.", + "No materials match {query}": "Żaden materiał nie pasuje do {query}", + "No part here": "Brak części w tym miejscu", + "Nothing in {category} here": "W kategorii {category} nic tu nie ma", + "Opacity": "Nieprzezroczystość", + "Paint": "Farba", + "Plastic": "Tworzywo", + "Published": "Opublikowane", + "Recent": "Ostatnie", + "Remove": "Usuń", + "Remove from Library": "Usuń z biblioteki", + "Remove {name} from your library? Documents that use it keep their material.": "Usunąć {name} z biblioteki? Dokumenty, które go używają, zachowają swój materiał.", + "Resize the library": "Zmień rozmiar biblioteki", + "Roughness": "Chropowatość", + "Rubber": "Guma", + "Save": "Zapisz", + "Save Material to Library": "Zapisz materiał w bibliotece", + "Save Selected Material to Library": "Zapisz zaznaczony materiał w bibliotece", + "Saved {name} to your library": "Zapisano {name} w bibliotece", + "Search materials": "Szukaj materiałów", + "Select a part first": "Najpierw zaznacz część", + "Select a part with a material first": "Najpierw zaznacz część z materiałem", + "Shelves": "Półki", + "Source": "Źródło", + "Stone": "Kamień", + "Subsurface": "Rozpraszanie podpowierzchniowe", + "The engine sent the preset in an unknown shape": "Silnik przesłał preset w nieznanej postaci", + "The library is empty": "Biblioteka jest pusta", + "Thin film thickness": "Grubość cienkiej warstwy", + "Thin glass": "Cienkie szkło", + "Thin walled": "Cienkościenny", + "This project has no materials yet.": "Ten projekt nie ma jeszcze materiałów.", + "Tile size": "Rozmiar kafelków", + "Transmission": "Transmisja", + "Transmission depth": "Głębokość transmisji", + "User": "Użytkownik", + "Wood": "Drewno", + "Yes": "Tak", + "{n} materials": "Materiały: {n}" +} diff --git a/frontend/src/i18n/modules/library/pt-BR.json b/frontend/src/i18n/modules/library/pt-BR.json new file mode 100644 index 00000000..7fb7cfd5 --- /dev/null +++ b/frontend/src/i18n/modules/library/pt-BR.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 material", + "Abbe number": "Número de Abbe", + "All": "Todos", + "Alt: whole group. Shift: same material.": "Alt: o grupo todo. Shift: o mesmo material.", + "Anisotropy": "Anisotropia", + "Applied {name} to every part with the material of {part}": "{name} aplicado a todas as peças com o material de {part}", + "Applied {name} to every part with the same material": "{name} aplicado a todas as peças com o mesmo material", + "Applied {name} to the group of {part}": "{name} aplicado ao grupo de {part}", + "Applied {name} to the selected parts": "{name} aplicado às peças selecionadas", + "Applied {name} to their groups": "{name} aplicado aos grupos delas", + "Applied {name} to {part}": "{name} aplicado a {part}", + "Apply to Every Part with the Same Material": "Aplicar a todas as peças com o mesmo material", + "Apply to Selected Parts": "Aplicar às peças selecionadas", + "Apply to Their Groups": "Aplicar aos grupos delas", + "Apply to every part with the material of {name}": "Aplicar a todas as peças com o material de {name}", + "Apply to the group of {name}": "Aplicar ao grupo de {name}", + "Apply to {name}": "Aplicar a {name}", + "Authored": "Autorais", + "Base color": "Cor base", + "Brushed metal": "Metal escovado", + "Cancel": "Cancelar", + "Categories": "Categorias", + "Category": "Categoria", + "Ceramic": "Cerâmica", + "Clear plastic": "Plástico transparente", + "Coat": "Verniz", + "Coat roughness": "Rugosidade do verniz", + "Details": "Detalhes", + "Diffuse": "Difuso", + "Drop on a part in the viewport": "Solte sobre uma peça no viewport", + "Drop the material on a part": "Solte o material sobre uma peça", + "Emission": "Emissão", + "Emissive": "Emissivo", + "Fabric": "Tecido", + "Favorite": "Favorito", + "Favorites": "Favoritos", + "Fuzz": "Felpa", + "Gem": "Gema", + "Generic": "Genérico", + "Give the material a name": "Dê um nome ao material", + "Glass": "Vidro", + "In project": "No projeto", + "Index of refraction": "Índice de refração", + "Keeps the material of the selected part as one of your own presets.": "Mantém o material da peça selecionada como uma das suas predefinições.", + "Library": "Biblioteca", + "Liquid": "Líquido", + "Loading": "Carregando", + "Material details": "Detalhes do material", + "Materials": "Materiais", + "Materials you apply appear here.": "Os materiais que você aplicar aparecem aqui.", + "Materials you save from the selection appear here.": "Os materiais que você salvar da seleção aparecem aqui.", + "Measured": "Medidos", + "Metal": "Metal", + "Metallic paint": "Tinta metálica", + "Metalness": "Metalicidade", + "Name": "Nome", + "No": "Não", + "No favorites yet. Right-click a material to add one.": "Ainda não há favoritos. Clique com o botão direito em um material para adicionar um.", + "No materials match {query}": "Nenhum material corresponde a {query}", + "No part here": "Nenhuma peça aqui", + "Nothing in {category} here": "Nada em {category} aqui", + "Opacity": "Opacidade", + "Paint": "Tinta", + "Plastic": "Plástico", + "Published": "Publicados", + "Recent": "Recentes", + "Remove": "Remover", + "Remove from Library": "Remover da biblioteca", + "Remove {name} from your library? Documents that use it keep their material.": "Remover {name} da sua biblioteca? Os documentos que o usam mantêm o material.", + "Resize the library": "Redimensionar a biblioteca", + "Roughness": "Rugosidade", + "Rubber": "Borracha", + "Save": "Salvar", + "Save Material to Library": "Salvar material na biblioteca", + "Save Selected Material to Library": "Salvar o material selecionado na biblioteca", + "Saved {name} to your library": "{name} salvo na sua biblioteca", + "Search materials": "Pesquisar materiais", + "Select a part first": "Selecione uma peça primeiro", + "Select a part with a material first": "Selecione primeiro uma peça com material", + "Shelves": "Prateleiras", + "Source": "Origem", + "Stone": "Pedra", + "Subsurface": "Subsuperfície", + "The engine sent the preset in an unknown shape": "O motor enviou a predefinição em um formato desconhecido", + "The library is empty": "A biblioteca está vazia", + "Thin film thickness": "Espessura da película fina", + "Thin glass": "Vidro fino", + "Thin walled": "Parede fina", + "This project has no materials yet.": "Este projeto ainda não tem materiais.", + "Tile size": "Tamanho do bloco", + "Transmission": "Transmissão", + "Transmission depth": "Profundidade de transmissão", + "User": "Usuário", + "Wood": "Madeira", + "Yes": "Sim", + "{n} materials": "{n} materiais" +} diff --git a/frontend/src/i18n/modules/library/ru.json b/frontend/src/i18n/modules/library/ru.json new file mode 100644 index 00000000..1c1ee030 --- /dev/null +++ b/frontend/src/i18n/modules/library/ru.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 материал", + "Abbe number": "Число Аббе", + "All": "Все", + "Alt: whole group. Shift: same material.": "Alt: вся группа. Shift: тот же материал.", + "Anisotropy": "Анизотропия", + "Applied {name} to every part with the material of {part}": "{name} применён ко всем деталям с материалом детали {part}", + "Applied {name} to every part with the same material": "{name} применён ко всем деталям с тем же материалом", + "Applied {name} to the group of {part}": "{name} применён к группе детали {part}", + "Applied {name} to the selected parts": "{name} применён к выбранным деталям", + "Applied {name} to their groups": "{name} применён к их группам", + "Applied {name} to {part}": "{name} применён к детали {part}", + "Apply to Every Part with the Same Material": "Применить ко всем деталям с тем же материалом", + "Apply to Selected Parts": "Применить к выбранным деталям", + "Apply to Their Groups": "Применить к их группам", + "Apply to every part with the material of {name}": "Применить ко всем деталям с материалом детали {name}", + "Apply to the group of {name}": "Применить к группе детали {name}", + "Apply to {name}": "Применить к {name}", + "Authored": "Авторские", + "Base color": "Базовый цвет", + "Brushed metal": "Шлифованный металл", + "Cancel": "Отмена", + "Categories": "Категории", + "Category": "Категория", + "Ceramic": "Керамика", + "Clear plastic": "Прозрачный пластик", + "Coat": "Покрытие", + "Coat roughness": "Шероховатость покрытия", + "Details": "Сведения", + "Diffuse": "Диффузный", + "Drop on a part in the viewport": "Перетащите на деталь во вьюпорте", + "Drop the material on a part": "Перетащите материал на деталь", + "Emission": "Излучение", + "Emissive": "Излучающий", + "Fabric": "Ткань", + "Favorite": "Избранное", + "Favorites": "Избранное", + "Fuzz": "Ворсистость", + "Gem": "Драгоценный камень", + "Generic": "Универсальный", + "Give the material a name": "Дайте материалу название", + "Glass": "Стекло", + "In project": "В проекте", + "Index of refraction": "Показатель преломления", + "Keeps the material of the selected part as one of your own presets.": "Сохраняет материал выбранной детали как один из ваших пресетов.", + "Library": "Библиотека", + "Liquid": "Жидкость", + "Loading": "Загрузка", + "Material details": "Сведения о материале", + "Materials": "Материалы", + "Materials you apply appear here.": "Применённые вами материалы появятся здесь.", + "Materials you save from the selection appear here.": "Материалы, сохранённые из выделения, появятся здесь.", + "Measured": "Измеренные", + "Metal": "Металл", + "Metallic paint": "Металлик (краска)", + "Metalness": "Металличность", + "Name": "Название", + "No": "Нет", + "No favorites yet. Right-click a material to add one.": "Избранного пока нет. Щёлкните материал правой кнопкой, чтобы добавить.", + "No materials match {query}": "Нет материалов по запросу {query}", + "No part here": "Здесь нет детали", + "Nothing in {category} here": "В категории {category} здесь ничего нет", + "Opacity": "Непрозрачность", + "Paint": "Краска", + "Plastic": "Пластик", + "Published": "Опубликованные", + "Recent": "Недавние", + "Remove": "Удалить", + "Remove from Library": "Удалить из библиотеки", + "Remove {name} from your library? Documents that use it keep their material.": "Удалить {name} из вашей библиотеки? Документы, где он используется, сохранят свой материал.", + "Resize the library": "Изменить размер библиотеки", + "Roughness": "Шероховатость", + "Rubber": "Резина", + "Save": "Сохранить", + "Save Material to Library": "Сохранить материал в библиотеку", + "Save Selected Material to Library": "Сохранить выбранный материал в библиотеку", + "Saved {name} to your library": "{name} сохранён в вашу библиотеку", + "Search materials": "Поиск материалов", + "Select a part first": "Сначала выберите деталь", + "Select a part with a material first": "Сначала выберите деталь с материалом", + "Shelves": "Полки", + "Source": "Источник", + "Stone": "Камень", + "Subsurface": "Подповерхностное рассеивание", + "The engine sent the preset in an unknown shape": "Движок прислал пресет в неизвестном формате", + "The library is empty": "Библиотека пуста", + "Thin film thickness": "Толщина тонкой плёнки", + "Thin glass": "Тонкое стекло", + "Thin walled": "Тонкостенный", + "This project has no materials yet.": "В этом проекте пока нет материалов.", + "Tile size": "Размер плитки", + "Transmission": "Пропускание", + "Transmission depth": "Глубина пропускания", + "User": "Пользовательские", + "Wood": "Дерево", + "Yes": "Да", + "{n} materials": "Материалов: {n}" +} diff --git a/frontend/src/i18n/modules/library/strings.json b/frontend/src/i18n/modules/library/strings.json new file mode 100644 index 00000000..0d026a9e --- /dev/null +++ b/frontend/src/i18n/modules/library/strings.json @@ -0,0 +1,98 @@ +[ + "1 material", + "Abbe number", + "All", + "Alt: whole group. Shift: same material.", + "Anisotropy", + "Applied {name} to every part with the material of {part}", + "Applied {name} to every part with the same material", + "Applied {name} to the group of {part}", + "Applied {name} to the selected parts", + "Applied {name} to their groups", + "Applied {name} to {part}", + "Apply to Every Part with the Same Material", + "Apply to Selected Parts", + "Apply to Their Groups", + "Apply to every part with the material of {name}", + "Apply to the group of {name}", + "Apply to {name}", + "Authored", + "Base color", + "Brushed metal", + "Cancel", + "Categories", + "Category", + "Ceramic", + "Clear plastic", + "Coat", + "Coat roughness", + "Details", + "Diffuse", + "Drop on a part in the viewport", + "Drop the material on a part", + "Emission", + "Emissive", + "Fabric", + "Favorite", + "Favorites", + "Fuzz", + "Gem", + "Generic", + "Give the material a name", + "Glass", + "In project", + "Index of refraction", + "Keeps the material of the selected part as one of your own presets.", + "Library", + "Liquid", + "Loading", + "Material details", + "Materials", + "Materials you apply appear here.", + "Materials you save from the selection appear here.", + "Measured", + "Metal", + "Metallic paint", + "Metalness", + "Name", + "No", + "No favorites yet. Right-click a material to add one.", + "No materials match {query}", + "No part here", + "Nothing in {category} here", + "Opacity", + "Paint", + "Plastic", + "Published", + "Recent", + "Remove", + "Remove from Library", + "Remove {name} from your library? Documents that use it keep their material.", + "Resize the library", + "Roughness", + "Rubber", + "Save", + "Save Material to Library", + "Save Selected Material to Library", + "Saved {name} to your library", + "Search materials", + "Select a part first", + "Select a part with a material first", + "Shelves", + "Source", + "Stone", + "Subsurface", + "The engine sent the preset in an unknown shape", + "The library is empty", + "Thin film thickness", + "Thin glass", + "Thin walled", + "This project has no materials yet.", + "Tile size", + "Transmission", + "Transmission depth", + "User", + "Wood", + "Yes", + "{n} materials" +] diff --git a/frontend/src/i18n/modules/library/sv.json b/frontend/src/i18n/modules/library/sv.json new file mode 100644 index 00000000..803241be --- /dev/null +++ b/frontend/src/i18n/modules/library/sv.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 material", + "Abbe number": "Abbetal", + "All": "Alla", + "Alt: whole group. Shift: same material.": "Alt: hela gruppen. Shift: samma material.", + "Anisotropy": "Anisotropi", + "Applied {name} to every part with the material of {part}": "Använde {name} på alla delar med samma material som {part}", + "Applied {name} to every part with the same material": "Använde {name} på alla delar med samma material", + "Applied {name} to the group of {part}": "Använde {name} på gruppen för {part}", + "Applied {name} to the selected parts": "Använde {name} på de markerade delarna", + "Applied {name} to their groups": "Använde {name} på deras grupper", + "Applied {name} to {part}": "Använde {name} på {part}", + "Apply to Every Part with the Same Material": "Använd på alla delar med samma material", + "Apply to Selected Parts": "Använd på markerade delar", + "Apply to Their Groups": "Använd på deras grupper", + "Apply to every part with the material of {name}": "Använd på alla delar med materialet från {name}", + "Apply to the group of {name}": "Använd på gruppen för {name}", + "Apply to {name}": "Använd på {name}", + "Authored": "Handgjord", + "Base color": "Basfärg", + "Brushed metal": "Borstad metall", + "Cancel": "Avbryt", + "Categories": "Kategorier", + "Category": "Kategori", + "Ceramic": "Keramik", + "Clear plastic": "Genomskinlig plast", + "Coat": "Coating", + "Coat roughness": "Coatingråhet", + "Details": "Detaljer", + "Diffuse": "Diffus", + "Drop on a part in the viewport": "Släpp på en del i vyn", + "Drop the material on a part": "Släpp materialet på en del", + "Emission": "Emission", + "Emissive": "Emissiv", + "Fabric": "Tyg", + "Favorite": "Favorit", + "Favorites": "Favoriter", + "Fuzz": "Fuzz", + "Gem": "Ädelsten", + "Generic": "Allmänt", + "Give the material a name": "Ge materialet ett namn", + "Glass": "Glas", + "In project": "I projektet", + "Index of refraction": "Brytningsindex", + "Keeps the material of the selected part as one of your own presets.": "Sparar materialet för den markerade delen som en av dina egna förinställningar.", + "Library": "Bibliotek", + "Liquid": "Vätska", + "Loading": "Läser in", + "Material details": "Materialdetaljer", + "Materials": "Material", + "Materials you apply appear here.": "Material som du använder visas här.", + "Materials you save from the selection appear here.": "Material som du sparar från markeringen visas här.", + "Measured": "Uppmätt", + "Metal": "Metall", + "Metallic paint": "Metallic lack", + "Metalness": "Metallighet", + "Name": "Namn", + "No": "Nej", + "No favorites yet. Right-click a material to add one.": "Inga favoriter ännu. Högerklicka på ett material för att lägga till ett.", + "No materials match {query}": "Inga material matchar {query}", + "No part here": "Ingen del här", + "Nothing in {category} here": "Inget i {category} här", + "Opacity": "Opacitet", + "Paint": "Färg", + "Plastic": "Plast", + "Published": "Publicerad", + "Recent": "Senaste", + "Remove": "Ta bort", + "Remove from Library": "Ta bort från biblioteket", + "Remove {name} from your library? Documents that use it keep their material.": "Ta bort {name} från ditt bibliotek? Dokument som använder det behåller sitt material.", + "Resize the library": "Ändra bibliotekets storlek", + "Roughness": "Råhet", + "Rubber": "Gummi", + "Save": "Spara", + "Save Material to Library": "Spara material i biblioteket", + "Save Selected Material to Library": "Spara markerat material i biblioteket", + "Saved {name} to your library": "{name} har sparats i ditt bibliotek", + "Search materials": "Sök bland material", + "Select a part first": "Markera en del först", + "Select a part with a material first": "Markera först en del med ett material", + "Shelves": "Hyllor", + "Source": "Källa", + "Stone": "Sten", + "Subsurface": "Subsurface", + "The engine sent the preset in an unknown shape": "Motorn skickade förinställningen i en okänd form", + "The library is empty": "Biblioteket är tomt", + "Thin film thickness": "Tjocklek på tunn film", + "Thin glass": "Tunt glas", + "Thin walled": "Tunnväggig", + "This project has no materials yet.": "Det här projektet har inga material ännu.", + "Tile size": "Miniatyrstorlek", + "Transmission": "Transmission", + "Transmission depth": "Transmissionsdjup", + "User": "Användare", + "Wood": "Trä", + "Yes": "Ja", + "{n} materials": "{n} material" +} diff --git a/frontend/src/i18n/modules/library/th.json b/frontend/src/i18n/modules/library/th.json new file mode 100644 index 00000000..75b2f231 --- /dev/null +++ b/frontend/src/i18n/modules/library/th.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 แมทีเรียล", + "Abbe number": "ค่า Abbe", + "All": "ทั้งหมด", + "Alt: whole group. Shift: same material.": "Alt: ทั้งกลุ่ม Shift: แมทีเรียลเดียวกัน", + "Anisotropy": "แอนไอโซทรอปี", + "Applied {name} to every part with the material of {part}": "นำ {name} ไปใช้กับทุกชิ้นส่วนที่มีแมทีเรียลของ {part} แล้ว", + "Applied {name} to every part with the same material": "นำ {name} ไปใช้กับทุกชิ้นส่วนที่มีแมทีเรียลเดียวกันแล้ว", + "Applied {name} to the group of {part}": "นำ {name} ไปใช้กับกลุ่มของ {part} แล้ว", + "Applied {name} to the selected parts": "นำ {name} ไปใช้กับชิ้นส่วนที่เลือกแล้ว", + "Applied {name} to their groups": "นำ {name} ไปใช้กับกลุ่มของชิ้นส่วนเหล่านั้นแล้ว", + "Applied {name} to {part}": "นำ {name} ไปใช้กับ {part} แล้ว", + "Apply to Every Part with the Same Material": "ใช้กับทุกชิ้นส่วนที่มีแมทีเรียลเดียวกัน", + "Apply to Selected Parts": "ใช้กับชิ้นส่วนที่เลือก", + "Apply to Their Groups": "ใช้กับกลุ่มของชิ้นส่วนเหล่านั้น", + "Apply to every part with the material of {name}": "ใช้กับทุกชิ้นส่วนที่มีแมทีเรียลของ {name}", + "Apply to the group of {name}": "ใช้กับกลุ่มของ {name}", + "Apply to {name}": "ใช้กับ {name}", + "Authored": "สร้างเอง", + "Base color": "สีฐาน", + "Brushed metal": "โลหะขัดเป็นเส้น", + "Cancel": "ยกเลิก", + "Categories": "หมวดหมู่", + "Category": "หมวดหมู่", + "Ceramic": "เซรามิก", + "Clear plastic": "พลาสติกใส", + "Coat": "เคลือบ", + "Coat roughness": "ความหยาบของชั้นเคลือบ", + "Details": "รายละเอียด", + "Diffuse": "ดิฟฟิวส์", + "Drop on a part in the viewport": "วางบนชิ้นส่วนในวิวพอร์ต", + "Drop the material on a part": "วางแมทีเรียลบนชิ้นส่วน", + "Emission": "การเปล่งแสง", + "Emissive": "การเรืองแสง", + "Fabric": "ผ้า", + "Favorite": "รายการโปรด", + "Favorites": "รายการโปรด", + "Fuzz": "ขน", + "Gem": "อัญมณี", + "Generic": "ทั่วไป", + "Give the material a name": "ตั้งชื่อแมทีเรียล", + "Glass": "แก้ว", + "In project": "ในโปรเจกต์", + "Index of refraction": "ดัชนีหักเห", + "Keeps the material of the selected part as one of your own presets.": "เก็บแมทีเรียลของชิ้นส่วนที่เลือกไว้เป็นพรีเซ็ตของคุณเอง", + "Library": "คลัง", + "Liquid": "ของเหลว", + "Loading": "กำลังโหลด", + "Material details": "รายละเอียดแมทีเรียล", + "Materials": "แมทีเรียล", + "Materials you apply appear here.": "แมทีเรียลที่คุณนำไปใช้จะปรากฏที่นี่", + "Materials you save from the selection appear here.": "แมทีเรียลที่คุณบันทึกจากสิ่งที่เลือกจะปรากฏที่นี่", + "Measured": "วัดจริง", + "Metal": "โลหะ", + "Metallic paint": "สีโลหะ", + "Metalness": "ความเป็นโลหะ", + "Name": "ชื่อ", + "No": "ไม่", + "No favorites yet. Right-click a material to add one.": "ยังไม่มีรายการโปรด คลิกขวาที่แมทีเรียลเพื่อเพิ่ม", + "No materials match {query}": "ไม่มีแมทีเรียลที่ตรงกับ {query}", + "No part here": "ไม่มีชิ้นส่วนตรงนี้", + "Nothing in {category} here": "ไม่มีสิ่งใดใน {category} ที่นี่", + "Opacity": "ความทึบ", + "Paint": "สี", + "Plastic": "พลาสติก", + "Published": "เผยแพร่แล้ว", + "Recent": "ล่าสุด", + "Remove": "ลบออก", + "Remove from Library": "ลบออกจากคลัง", + "Remove {name} from your library? Documents that use it keep their material.": "ลบ {name} ออกจากคลังของคุณหรือไม่? เอกสารที่ใช้แมทีเรียลนี้ยังคงแมทีเรียลไว้", + "Resize the library": "ปรับขนาดคลัง", + "Roughness": "ความหยาบ", + "Rubber": "ยาง", + "Save": "บันทึก", + "Save Material to Library": "บันทึกแมทีเรียลลงคลัง", + "Save Selected Material to Library": "บันทึกแมทีเรียลที่เลือกลงคลัง", + "Saved {name} to your library": "บันทึก {name} ลงคลังของคุณแล้ว", + "Search materials": "ค้นหาแมทีเรียล", + "Select a part first": "เลือกชิ้นส่วนก่อน", + "Select a part with a material first": "เลือกชิ้นส่วนที่มีแมทีเรียลก่อน", + "Shelves": "ชั้นวาง", + "Source": "ต้นทาง", + "Stone": "หิน", + "Subsurface": "ซับเซอร์เฟซ", + "The engine sent the preset in an unknown shape": "เอนจินส่งพรีเซ็ตมาในรูปแบบที่ไม่รู้จัก", + "The library is empty": "คลังว่างเปล่า", + "Thin film thickness": "ความหนาของฟิล์มบาง", + "Thin glass": "กระจกบาง", + "Thin walled": "ผนังบาง", + "This project has no materials yet.": "โปรเจกต์นี้ยังไม่มีแมทีเรียล", + "Tile size": "ขนาดกระเบื้อง", + "Transmission": "การส่องผ่าน", + "Transmission depth": "ความลึกการส่องผ่าน", + "User": "ผู้ใช้", + "Wood": "ไม้", + "Yes": "ใช่", + "{n} materials": "{n} แมทีเรียล" +} diff --git a/frontend/src/i18n/modules/library/tr.json b/frontend/src/i18n/modules/library/tr.json new file mode 100644 index 00000000..8c63c5de --- /dev/null +++ b/frontend/src/i18n/modules/library/tr.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 malzeme", + "Abbe number": "Abbe sayısı", + "All": "Tümü", + "Alt: whole group. Shift: same material.": "Alt: tüm grup. Shift: aynı malzeme.", + "Anisotropy": "Anizotropi", + "Applied {name} to every part with the material of {part}": "{name}, {part} parçasının malzemesine sahip tüm parçalara uygulandı", + "Applied {name} to every part with the same material": "{name}, aynı malzemeye sahip tüm parçalara uygulandı", + "Applied {name} to the group of {part}": "{name}, {part} parçasının grubuna uygulandı", + "Applied {name} to the selected parts": "{name} seçili parçalara uygulandı", + "Applied {name} to their groups": "{name} gruplarına uygulandı", + "Applied {name} to {part}": "{name}, {part} parçasına uygulandı", + "Apply to Every Part with the Same Material": "Aynı Malzemeye Sahip Tüm Parçalara Uygula", + "Apply to Selected Parts": "Seçili Parçalara Uygula", + "Apply to Their Groups": "Gruplarına Uygula", + "Apply to every part with the material of {name}": "{name} malzemesine sahip tüm parçalara uygula", + "Apply to the group of {name}": "{name} grubuna uygula", + "Apply to {name}": "{name} öğesine uygula", + "Authored": "Özgün", + "Base color": "Temel renk", + "Brushed metal": "Fırçalanmış metal", + "Cancel": "İptal", + "Categories": "Kategoriler", + "Category": "Kategori", + "Ceramic": "Seramik", + "Clear plastic": "Şeffaf plastik", + "Coat": "Kaplama", + "Coat roughness": "Kaplama pürüzlülüğü", + "Details": "Ayrıntılar", + "Diffuse": "Yaygın yansıma", + "Drop on a part in the viewport": "Görünüm alanındaki bir parçanın üzerine bırakın", + "Drop the material on a part": "Malzemeyi bir parçanın üzerine bırakın", + "Emission": "Emisyon", + "Emissive": "Işıldayan", + "Fabric": "Kumaş", + "Favorite": "Sık kullanılan", + "Favorites": "Sık Kullanılanlar", + "Fuzz": "Tüylülük", + "Gem": "Değerli taş", + "Generic": "Genel", + "Give the material a name": "Malzemeye bir ad verin", + "Glass": "Cam", + "In project": "Projede", + "Index of refraction": "Kırılma indisi", + "Keeps the material of the selected part as one of your own presets.": "Seçili parçanın malzemesini kendi hazır ayarlarınızdan biri olarak saklar.", + "Library": "Kitaplık", + "Liquid": "Sıvı", + "Loading": "Yükleniyor", + "Material details": "Malzeme ayrıntıları", + "Materials": "Malzemeler", + "Materials you apply appear here.": "Uyguladığınız malzemeler burada görünür.", + "Materials you save from the selection appear here.": "Seçimden kaydettiğiniz malzemeler burada görünür.", + "Measured": "Ölçülmüş", + "Metal": "Metal", + "Metallic paint": "Metalik boya", + "Metalness": "Metaliklik", + "Name": "Ad", + "No": "Hayır", + "No favorites yet. Right-click a material to add one.": "Henüz sık kullanılan yok. Eklemek için bir malzemeye sağ tıklayın.", + "No materials match {query}": "{query} ile eşleşen malzeme yok", + "No part here": "Burada parça yok", + "Nothing in {category} here": "{category} içinde burada bir şey yok", + "Opacity": "Opaklık", + "Paint": "Boya", + "Plastic": "Plastik", + "Published": "Yayımlanan", + "Recent": "Son kullanılanlar", + "Remove": "Kaldır", + "Remove from Library": "Kitaplıktan Kaldır", + "Remove {name} from your library? Documents that use it keep their material.": "{name} kitaplığınızdan kaldırılsın mı? Onu kullanan belgeler malzemelerini korur.", + "Resize the library": "Kitaplığı yeniden boyutlandır", + "Roughness": "Pürüzlülük", + "Rubber": "Kauçuk", + "Save": "Kaydet", + "Save Material to Library": "Malzemeyi Kitaplığa Kaydet", + "Save Selected Material to Library": "Seçili Malzemeyi Kitaplığa Kaydet", + "Saved {name} to your library": "{name} kitaplığınıza kaydedildi", + "Search materials": "Malzeme ara", + "Select a part first": "Önce bir parça seçin", + "Select a part with a material first": "Önce malzemeli bir parça seçin", + "Shelves": "Raflar", + "Source": "Kaynak", + "Stone": "Taş", + "Subsurface": "Yüzey altı saçılımı", + "The engine sent the preset in an unknown shape": "Motor hazır ayarı bilinmeyen bir biçimde gönderdi", + "The library is empty": "Kitaplık boş", + "Thin film thickness": "İnce film kalınlığı", + "Thin glass": "İnce cam", + "Thin walled": "İnce duvarlı", + "This project has no materials yet.": "Bu projede henüz malzeme yok.", + "Tile size": "Karo boyutu", + "Transmission": "Geçirgenlik", + "Transmission depth": "Geçirgenlik derinliği", + "User": "Kullanıcı", + "Wood": "Ahşap", + "Yes": "Evet", + "{n} materials": "{n} malzeme" +} diff --git a/frontend/src/i18n/modules/library/uk.json b/frontend/src/i18n/modules/library/uk.json new file mode 100644 index 00000000..761390f1 --- /dev/null +++ b/frontend/src/i18n/modules/library/uk.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 матеріал", + "Abbe number": "Число Аббе", + "All": "Усі", + "Alt: whole group. Shift: same material.": "Alt: уся група. Shift: той самий матеріал.", + "Anisotropy": "Анізотропія", + "Applied {name} to every part with the material of {part}": "{name} застосовано до всіх деталей із матеріалом деталі {part}", + "Applied {name} to every part with the same material": "{name} застосовано до всіх деталей із тим самим матеріалом", + "Applied {name} to the group of {part}": "{name} застосовано до групи деталі {part}", + "Applied {name} to the selected parts": "{name} застосовано до вибраних деталей", + "Applied {name} to their groups": "{name} застосовано до їхніх груп", + "Applied {name} to {part}": "{name} застосовано до деталі {part}", + "Apply to Every Part with the Same Material": "Застосувати до всіх деталей із тим самим матеріалом", + "Apply to Selected Parts": "Застосувати до вибраних деталей", + "Apply to Their Groups": "Застосувати до їхніх груп", + "Apply to every part with the material of {name}": "Застосувати до всіх деталей із матеріалом деталі {name}", + "Apply to the group of {name}": "Застосувати до групи деталі {name}", + "Apply to {name}": "Застосувати до {name}", + "Authored": "Авторські", + "Base color": "Базовий колір", + "Brushed metal": "Шліфований метал", + "Cancel": "Скасувати", + "Categories": "Категорії", + "Category": "Категорія", + "Ceramic": "Кераміка", + "Clear plastic": "Прозорий пластик", + "Coat": "Покриття", + "Coat roughness": "Шорсткість покриття", + "Details": "Відомості", + "Diffuse": "Дифузний", + "Drop on a part in the viewport": "Перетягніть на деталь у в'юпорті", + "Drop the material on a part": "Перетягніть матеріал на деталь", + "Emission": "Випромінювання", + "Emissive": "Випромінювальний", + "Fabric": "Тканина", + "Favorite": "Обране", + "Favorites": "Обране", + "Fuzz": "Ворсистість", + "Gem": "Дорогоцінний камінь", + "Generic": "Універсальний", + "Give the material a name": "Дайте матеріалу назву", + "Glass": "Скло", + "In project": "У проєкті", + "Index of refraction": "Показник заломлення", + "Keeps the material of the selected part as one of your own presets.": "Зберігає матеріал вибраної деталі як один із ваших пресетів.", + "Library": "Бібліотека", + "Liquid": "Рідина", + "Loading": "Завантаження", + "Material details": "Відомості про матеріал", + "Materials": "Матеріали", + "Materials you apply appear here.": "Застосовані вами матеріали з'являться тут.", + "Materials you save from the selection appear here.": "Матеріали, збережені з виділення, з'являться тут.", + "Measured": "Виміряні", + "Metal": "Метал", + "Metallic paint": "Металік (фарба)", + "Metalness": "Металевість", + "Name": "Назва", + "No": "Ні", + "No favorites yet. Right-click a material to add one.": "Обраного поки немає. Клацніть матеріал правою кнопкою, щоб додати.", + "No materials match {query}": "Немає матеріалів за запитом {query}", + "No part here": "Тут немає деталі", + "Nothing in {category} here": "У категорії {category} тут нічого немає", + "Opacity": "Непрозорість", + "Paint": "Фарба", + "Plastic": "Пластик", + "Published": "Опубліковані", + "Recent": "Нещодавні", + "Remove": "Видалити", + "Remove from Library": "Видалити з бібліотеки", + "Remove {name} from your library? Documents that use it keep their material.": "Видалити {name} з вашої бібліотеки? Документи, де його використано, збережуть свій матеріал.", + "Resize the library": "Змінити розмір бібліотеки", + "Roughness": "Шорсткість", + "Rubber": "Гума", + "Save": "Зберегти", + "Save Material to Library": "Зберегти матеріал до бібліотеки", + "Save Selected Material to Library": "Зберегти вибраний матеріал до бібліотеки", + "Saved {name} to your library": "{name} збережено до вашої бібліотеки", + "Search materials": "Пошук матеріалів", + "Select a part first": "Спочатку виберіть деталь", + "Select a part with a material first": "Спочатку виберіть деталь із матеріалом", + "Shelves": "Полиці", + "Source": "Джерело", + "Stone": "Камінь", + "Subsurface": "Підповерхневе розсіювання", + "The engine sent the preset in an unknown shape": "Рушій надіслав пресет в невідомому форматі", + "The library is empty": "Бібліотека порожня", + "Thin film thickness": "Товщина тонкої плівки", + "Thin glass": "Тонке скло", + "Thin walled": "Тонкостінний", + "This project has no materials yet.": "У цьому проєкті поки немає матеріалів.", + "Tile size": "Розмір плитки", + "Transmission": "Пропускання", + "Transmission depth": "Глибина пропускання", + "User": "Користувацькі", + "Wood": "Дерево", + "Yes": "Так", + "{n} materials": "Матеріалів: {n}" +} diff --git a/frontend/src/i18n/modules/library/vi.json b/frontend/src/i18n/modules/library/vi.json new file mode 100644 index 00000000..cfe0a6ab --- /dev/null +++ b/frontend/src/i18n/modules/library/vi.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 vật liệu", + "Abbe number": "Số Abbe", + "All": "Tất cả", + "Alt: whole group. Shift: same material.": "Alt: cả nhóm. Shift: cùng vật liệu.", + "Anisotropy": "Dị hướng", + "Applied {name} to every part with the material of {part}": "Đã áp dụng {name} cho mọi bộ phận có vật liệu của {part}", + "Applied {name} to every part with the same material": "Đã áp dụng {name} cho mọi bộ phận có cùng vật liệu", + "Applied {name} to the group of {part}": "Đã áp dụng {name} cho nhóm của {part}", + "Applied {name} to the selected parts": "Đã áp dụng {name} cho các bộ phận đã chọn", + "Applied {name} to their groups": "Đã áp dụng {name} cho các nhóm của chúng", + "Applied {name} to {part}": "Đã áp dụng {name} cho {part}", + "Apply to Every Part with the Same Material": "Áp dụng cho mọi bộ phận có cùng vật liệu", + "Apply to Selected Parts": "Áp dụng cho bộ phận đã chọn", + "Apply to Their Groups": "Áp dụng cho các nhóm của chúng", + "Apply to every part with the material of {name}": "Áp dụng cho mọi bộ phận có vật liệu của {name}", + "Apply to the group of {name}": "Áp dụng cho nhóm của {name}", + "Apply to {name}": "Áp dụng cho {name}", + "Authored": "Tự tạo", + "Base color": "Màu nền", + "Brushed metal": "Kim loại xước", + "Cancel": "Hủy", + "Categories": "Danh mục", + "Category": "Danh mục", + "Ceramic": "Gốm sứ", + "Clear plastic": "Nhựa trong", + "Coat": "Lớp phủ", + "Coat roughness": "Độ nhám lớp phủ", + "Details": "Chi tiết", + "Diffuse": "Khuếch tán", + "Drop on a part in the viewport": "Thả lên một bộ phận trong khung nhìn", + "Drop the material on a part": "Thả vật liệu lên một bộ phận", + "Emission": "Phát xạ", + "Emissive": "Phát sáng", + "Fabric": "Vải", + "Favorite": "Yêu thích", + "Favorites": "Yêu thích", + "Fuzz": "Lông mịn", + "Gem": "Đá quý", + "Generic": "Chung", + "Give the material a name": "Đặt tên cho vật liệu", + "Glass": "Kính", + "In project": "Trong dự án", + "Index of refraction": "Chiết suất", + "Keeps the material of the selected part as one of your own presets.": "Giữ vật liệu của bộ phận đã chọn làm một cấu hình sẵn của riêng bạn.", + "Library": "Thư viện", + "Liquid": "Chất lỏng", + "Loading": "Đang tải", + "Material details": "Chi tiết vật liệu", + "Materials": "Vật liệu", + "Materials you apply appear here.": "Các vật liệu bạn áp dụng sẽ hiện ở đây.", + "Materials you save from the selection appear here.": "Các vật liệu bạn lưu từ vùng chọn sẽ hiện ở đây.", + "Measured": "Đo thực tế", + "Metal": "Kim loại", + "Metallic paint": "Sơn ánh kim", + "Metalness": "Độ kim loại", + "Name": "Tên", + "No": "Không", + "No favorites yet. Right-click a material to add one.": "Chưa có mục yêu thích. Nhấp chuột phải vào một vật liệu để thêm.", + "No materials match {query}": "Không có vật liệu nào khớp với {query}", + "No part here": "Không có bộ phận ở đây", + "Nothing in {category} here": "Không có gì trong {category} ở đây", + "Opacity": "Độ mờ đục", + "Paint": "Sơn", + "Plastic": "Nhựa", + "Published": "Đã phát hành", + "Recent": "Gần đây", + "Remove": "Gỡ", + "Remove from Library": "Gỡ khỏi thư viện", + "Remove {name} from your library? Documents that use it keep their material.": "Gỡ {name} khỏi thư viện của bạn? Các tài liệu đang dùng nó vẫn giữ vật liệu.", + "Resize the library": "Đổi kích thước thư viện", + "Roughness": "Độ nhám", + "Rubber": "Cao su", + "Save": "Lưu", + "Save Material to Library": "Lưu vật liệu vào thư viện", + "Save Selected Material to Library": "Lưu vật liệu đã chọn vào thư viện", + "Saved {name} to your library": "Đã lưu {name} vào thư viện của bạn", + "Search materials": "Tìm vật liệu", + "Select a part first": "Hãy chọn một bộ phận trước", + "Select a part with a material first": "Hãy chọn một bộ phận có vật liệu trước", + "Shelves": "Kệ", + "Source": "Nguồn", + "Stone": "Đá", + "Subsurface": "Tán xạ dưới bề mặt", + "The engine sent the preset in an unknown shape": "Công cụ gửi cấu hình sẵn theo dạng không xác định", + "The library is empty": "Thư viện trống", + "Thin film thickness": "Độ dày màng mỏng", + "Thin glass": "Kính mỏng", + "Thin walled": "Thành mỏng", + "This project has no materials yet.": "Dự án này chưa có vật liệu nào.", + "Tile size": "Kích thước ô lát", + "Transmission": "Truyền sáng", + "Transmission depth": "Độ sâu truyền sáng", + "User": "Người dùng", + "Wood": "Gỗ", + "Yes": "Có", + "{n} materials": "{n} vật liệu" +} diff --git a/frontend/src/i18n/modules/library/zh-CN.json b/frontend/src/i18n/modules/library/zh-CN.json new file mode 100644 index 00000000..f619e2e4 --- /dev/null +++ b/frontend/src/i18n/modules/library/zh-CN.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 个材质", + "Abbe number": "阿贝数", + "All": "全部", + "Alt: whole group. Shift: same material.": "Alt:整个组。Shift:相同材质。", + "Anisotropy": "各向异性", + "Applied {name} to every part with the material of {part}": "已将 {name} 应用到所有使用 {part} 材质的部件", + "Applied {name} to every part with the same material": "已将 {name} 应用到所有使用相同材质的部件", + "Applied {name} to the group of {part}": "已将 {name} 应用到 {part} 所在的组", + "Applied {name} to the selected parts": "已将 {name} 应用到所选部件", + "Applied {name} to their groups": "已将 {name} 应用到它们所在的组", + "Applied {name} to {part}": "已将 {name} 应用到 {part}", + "Apply to Every Part with the Same Material": "应用到所有使用相同材质的部件", + "Apply to Selected Parts": "应用到所选部件", + "Apply to Their Groups": "应用到它们所在的组", + "Apply to every part with the material of {name}": "应用到所有使用 {name} 材质的部件", + "Apply to the group of {name}": "应用到 {name} 所在的组", + "Apply to {name}": "应用到 {name}", + "Authored": "自制", + "Base color": "基础色", + "Brushed metal": "拉丝金属", + "Cancel": "取消", + "Categories": "分类", + "Category": "类别", + "Ceramic": "陶瓷", + "Clear plastic": "透明塑料", + "Coat": "清漆", + "Coat roughness": "清漆粗糙度", + "Details": "详细信息", + "Diffuse": "漫反射", + "Drop on a part in the viewport": "拖放到视口中的部件上", + "Drop the material on a part": "将材质拖放到部件上", + "Emission": "自发光", + "Emissive": "自发光", + "Fabric": "织物", + "Favorite": "收藏", + "Favorites": "收藏", + "Fuzz": "绒毛", + "Gem": "宝石", + "Generic": "通用", + "Give the material a name": "为材质命名", + "Glass": "玻璃", + "In project": "在项目中", + "Index of refraction": "折射率", + "Keeps the material of the selected part as one of your own presets.": "将所选部件的材质保存为你自己的预设之一。", + "Library": "资源库", + "Liquid": "液体", + "Loading": "正在加载", + "Material details": "材质详细信息", + "Materials": "材质", + "Materials you apply appear here.": "你应用的材质会显示在这里。", + "Materials you save from the selection appear here.": "你从所选内容保存的材质会显示在这里。", + "Measured": "实测", + "Metal": "金属", + "Metallic paint": "金属漆", + "Metalness": "金属度", + "Name": "名称", + "No": "否", + "No favorites yet. Right-click a material to add one.": "还没有收藏。右键点击材质即可添加。", + "No materials match {query}": "没有与 {query} 匹配的材质", + "No part here": "此处没有部件", + "Nothing in {category} here": "{category} 中暂无内容", + "Opacity": "不透明度", + "Paint": "油漆", + "Plastic": "塑料", + "Published": "已发布", + "Recent": "最近", + "Remove": "移除", + "Remove from Library": "从资源库中移除", + "Remove {name} from your library? Documents that use it keep their material.": "要将 {name} 从你的资源库中移除吗?使用它的文档会保留其材质。", + "Resize the library": "调整资源库大小", + "Roughness": "粗糙度", + "Rubber": "橡胶", + "Save": "保存", + "Save Material to Library": "将材质保存到资源库", + "Save Selected Material to Library": "将所选材质保存到资源库", + "Saved {name} to your library": "已将 {name} 保存到你的资源库", + "Search materials": "搜索材质", + "Select a part first": "请先选择一个部件", + "Select a part with a material first": "请先选择带有材质的部件", + "Shelves": "分区", + "Source": "来源", + "Stone": "石材", + "Subsurface": "次表面", + "The engine sent the preset in an unknown shape": "引擎发送的预设格式未知", + "The library is empty": "资源库为空", + "Thin film thickness": "薄膜厚度", + "Thin glass": "薄玻璃", + "Thin walled": "薄壁", + "This project has no materials yet.": "此项目还没有材质。", + "Tile size": "缩略图大小", + "Transmission": "透射", + "Transmission depth": "透射深度", + "User": "用户", + "Wood": "木材", + "Yes": "是", + "{n} materials": "{n} 个材质" +} diff --git a/frontend/src/i18n/modules/library/zh-TW.json b/frontend/src/i18n/modules/library/zh-TW.json new file mode 100644 index 00000000..7b632a9f --- /dev/null +++ b/frontend/src/i18n/modules/library/zh-TW.json @@ -0,0 +1,98 @@ +{ + "1 material": "1 個材質", + "Abbe number": "阿貝數", + "All": "全部", + "Alt: whole group. Shift: same material.": "Alt:整個群組。Shift:相同材質。", + "Anisotropy": "各向異性", + "Applied {name} to every part with the material of {part}": "已將 {name} 套用到所有使用 {part} 材質的零件", + "Applied {name} to every part with the same material": "已將 {name} 套用到所有使用相同材質的零件", + "Applied {name} to the group of {part}": "已將 {name} 套用到 {part} 所在的群組", + "Applied {name} to the selected parts": "已將 {name} 套用到所選零件", + "Applied {name} to their groups": "已將 {name} 套用到它們所在的群組", + "Applied {name} to {part}": "已將 {name} 套用到 {part}", + "Apply to Every Part with the Same Material": "套用到所有使用相同材質的零件", + "Apply to Selected Parts": "套用到所選零件", + "Apply to Their Groups": "套用到它們所在的群組", + "Apply to every part with the material of {name}": "套用到所有使用 {name} 材質的零件", + "Apply to the group of {name}": "套用到 {name} 所在的群組", + "Apply to {name}": "套用到 {name}", + "Authored": "自製", + "Base color": "基礎色", + "Brushed metal": "拉絲金屬", + "Cancel": "取消", + "Categories": "分類", + "Category": "類別", + "Ceramic": "陶瓷", + "Clear plastic": "透明塑膠", + "Coat": "透明塗層", + "Coat roughness": "透明塗層粗糙度", + "Details": "詳細資訊", + "Diffuse": "漫射", + "Drop on a part in the viewport": "拖放到視埠中的零件上", + "Drop the material on a part": "將材質拖放到零件上", + "Emission": "自發光", + "Emissive": "自發光", + "Fabric": "織物", + "Favorite": "我的最愛", + "Favorites": "我的最愛", + "Fuzz": "絨毛", + "Gem": "寶石", + "Generic": "通用", + "Give the material a name": "為材質命名", + "Glass": "玻璃", + "In project": "在專案中", + "Index of refraction": "折射率", + "Keeps the material of the selected part as one of your own presets.": "將所選零件的材質儲存為你自己的預設集之一。", + "Library": "資源庫", + "Liquid": "液體", + "Loading": "正在載入", + "Material details": "材質詳細資訊", + "Materials": "材質", + "Materials you apply appear here.": "你套用的材質會顯示在這裡。", + "Materials you save from the selection appear here.": "你從所選內容儲存的材質會顯示在這裡。", + "Measured": "實測", + "Metal": "金屬", + "Metallic paint": "金屬漆", + "Metalness": "金屬度", + "Name": "名稱", + "No": "否", + "No favorites yet. Right-click a material to add one.": "還沒有我的最愛。在材質上按一下滑鼠右鍵即可加入。", + "No materials match {query}": "沒有與 {query} 相符的材質", + "No part here": "此處沒有零件", + "Nothing in {category} here": "{category} 中暫無內容", + "Opacity": "不透明度", + "Paint": "油漆", + "Plastic": "塑膠", + "Published": "已發佈", + "Recent": "最近", + "Remove": "移除", + "Remove from Library": "從資源庫中移除", + "Remove {name} from your library? Documents that use it keep their material.": "要將 {name} 從你的資源庫中移除嗎?使用它的文件會保留其材質。", + "Resize the library": "調整資源庫大小", + "Roughness": "粗糙度", + "Rubber": "橡膠", + "Save": "儲存", + "Save Material to Library": "將材質儲存到資源庫", + "Save Selected Material to Library": "將所選材質儲存到資源庫", + "Saved {name} to your library": "已將 {name} 儲存到你的資源庫", + "Search materials": "搜尋材質", + "Select a part first": "請先選擇一個零件", + "Select a part with a material first": "請先選擇帶有材質的零件", + "Shelves": "分區", + "Source": "來源", + "Stone": "石材", + "Subsurface": "次表面", + "The engine sent the preset in an unknown shape": "引擎傳送的預設集格式未知", + "The library is empty": "資源庫是空的", + "Thin film thickness": "薄膜厚度", + "Thin glass": "薄玻璃", + "Thin walled": "薄壁", + "This project has no materials yet.": "此專案還沒有材質。", + "Tile size": "縮圖大小", + "Transmission": "透射", + "Transmission depth": "透射深度", + "User": "使用者", + "Wood": "木材", + "Yes": "是", + "{n} materials": "{n} 個材質" +} diff --git a/frontend/src/i18n/modules/material/cs.json b/frontend/src/i18n/modules/material/cs.json new file mode 100644 index 00000000..2fb5f3ec --- /dev/null +++ b/frontend/src/i18n/modules/material/cs.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Graf s 1 uzlem", + "A graph of {n} nodes": "Graf s {n} uzly", + "A texture drives this value; the value is its fallback": "Tuto hodnotu řídí textura; hodnota je její záložní", + "ACEScg": "ACEScg", + "Abbe number": "Abbeho číslo", + "Add a map": "Přidat mapu", + "All parameters": "Všechny parametry", + "Alpha": "Alfa", + "Aluminium": "Hliník", + "Anisotropy": "Anizotropie", + "Assign to selection": "Přiřadit k výběru", + "Base weight": "Základní váha", + "Bilinear": "Bilineární", + "Blend": "Prolnutí", + "Blue": "Modrá", + "Box": "Kvádrová", + "Brushed metal": "Broušený kov", + "Bump": "Bump", + "Category": "Kategorie", + "Change the material type": "Změnit typ materiálu", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Změnit {from} na {to}. Ponechat aktuální hodnoty, nebo je obnovit na výchozí hodnoty nového typu?", + "Channel": "Kanál", + "Choose a texture image": "Vyberte obrázek textury", + "Choose an input": "Vyberte vstup", + "Chromium": "Chrom", + "Clamp": "Oříznutí", + "Clear plastic": "Čirý plast", + "Clear the texture slot": "Vyprázdnit slot textury", + "Coat": "Lak", + "Coat IOR": "IOR laku", + "Coat colour": "Barva laku", + "Coat darkening": "Ztmavení laku", + "Coat roughness": "Drsnost laku", + "Cobalt": "Kobalt", + "Colour space": "Barevný prostor", + "Copper": "Měď", + "Custom colour": "Vlastní barva", + "Cylindrical": "Válcová", + "Data (raw)": "Data (surová)", + "Delete material": "Smazat materiál", + "Diffuse": "Difuzní", + "Diffuse roughness": "Drsnost difuze", + "Dispersion": "Disperze", + "Displacement": "Displacement", + "Drive {input} with a texture": "Řídit vstup {input} texturou", + "Driven by the graph. Edit the graph to change it.": "Řídí to graf. Chcete-li to změnit, upravte graf.", + "Drives no input yet": "Zatím neřídí žádný vstup", + "Drives {inputs}": "Řídí: {inputs}", + "Duplicate material": "Duplikovat materiál", + "Edit graph": "Upravit graf", + "Edit the texture of {input}": "Upravit texturu vstupu {input}", + "Emission colour": "Barva emise", + "Fallback": "Záložní hodnota", + "Fallback colour": "Záložní barva", + "Film IOR": "IOR vrstvy", + "Film thickness": "Tloušťka vrstvy", + "Filter": "Filtrování", + "Flip green (DirectX)": "Převrátit zelenou (DirectX)", + "Fuzz": "Chmýří", + "Fuzz colour": "Barva chmýří", + "Fuzz roughness": "Drsnost chmýří", + "Generic": "Obecný", + "Gold": "Zlato", + "Graph": "Graf", + "Green": "Zelená", + "IOR": "IOR", + "Images": "Obrázky", + "In use by 1 part. Assign another material to it first.": "Používá ho 1 část. Nejprve jí přiřaďte jiný materiál.", + "In use by {n} parts. Assign another material to them first.": "Používá ho {n} částí. Nejprve jim přiřaďte jiný materiál.", + "Invert": "Invertovat", + "Iron": "Železo", + "Keep this material as a preset in your library": "Uložit tento materiál jako předvolbu do vaší knihovny", + "Keep values": "Ponechat hodnoty", + "Labels": "Štítky", + "Linear sRGB": "Lineární sRGB", + "Luminance": "Luminance", + "Material types": "Typy materiálů", + "Measured metals": "Změřené kovy", + "Metallic paint": "Metalický lak", + "Mirror": "Zrcadlení", + "Multiply by the value": "Vynásobit hodnotou", + "Name": "Název", + "Nearest": "Nejbližší", + "New": "Nový", + "New material": "Nový materiál", + "Nickel": "Nikl", + "No graph": "Žádný graf", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Žádný graf. Tento typ vypadá správně jen se svým grafem; obnovte výchozí hodnoty typu, abyste ho získali zpět.", + "No materials yet. Create one from a type with New.": "Zatím žádné materiály. Vytvořte jeden z typu tlačítkem Nový.", + "No textures. Use the texture button beside a value, or add a map here.": "Žádné textury. Použijte tlačítko textury vedle hodnoty nebo sem přidejte mapu.", + "Object space": "Prostor objektu", + "Offset U": "Posun U", + "Offset V": "Posun V", + "Open the node editor for this material": "Otevřít editor uzlů pro tento materiál", + "Parameters": "Parametry", + "Pick a material first": "Nejprve vyberte materiál", + "Pick or create a material to edit it.": "Vyberte nebo vytvořte materiál, který chcete upravit.", + "Planar": "Planární", + "Platinum": "Platina", + "Projection": "Projekce", + "RGB": "RGB", + "Range from": "Rozsah od", + "Range to": "Rozsah do", + "Reading the material": "Čtení materiálu", + "Red": "Červená", + "Rename material": "Přejmenovat materiál", + "Repeat": "Opakování", + "Replace the image": "Nahradit obrázek", + "Reset to type": "Obnovit výchozí hodnoty typu", + "Save to library": "Uložit do knihovny", + "Saved {name} to your library": "{name} bylo uloženo do vaší knihovny", + "Saving to the library needs an engine with library.save.": "Ukládání do knihovny vyžaduje engine s příkazem library.save.", + "Scale U": "Měřítko U", + "Scale V": "Měřítko V", + "Select parts in the viewport or the scene first": "Nejprve vyberte části v pohledu nebo ve scéně", + "Silver": "Stříbro", + "Space": "Prostor", + "Specular colour": "Barva lesku", + "Specular weight": "Váha lesku", + "Spherical": "Kulová", + "Strength": "Síla", + "Subsurface": "Podpovrchový rozptyl", + "Subsurface colour": "Barva rozptylu", + "Subsurface radius": "Poloměr rozptylu", + "Subsurface radius scale": "Měřítko poloměru rozptylu", + "Texture": "Textura", + "Texture {key}": "Textura {key}", + "Texture ×": "Textura ×", + "Textures": "Textury", + "The engine does not know the type {id}; showing the main values.": "Engine nezná typ {id}; zobrazují se hlavní hodnoty.", + "The engine lists no material types yet": "Engine zatím neuvádí žádné typy materiálů", + "The image could not be uploaded ({status})": "Obrázek se nepodařilo nahrát ({status})", + "The texture multiplies this value": "Textura tuto hodnotu násobí", + "Thin film": "Tenký film", + "Thin glass": "Tenké sklo", + "Thin walled": "Tenkostěnný", + "Titanium": "Titan", + "Transmission": "Propustnost", + "Transmission colour": "Barva propustnosti", + "Transmission depth": "Hloubka propustnosti", + "Trilinear": "Trilineární", + "Type": "Typ", + "UV set": "Sada UV", + "Used by 1 part": "Používá 1 část", + "Used by {n} parts": "Používá {n} částí", + "Waiting for the material settings": "Čeká se na nastavení materiálu", + "Waiting for the material types": "Čeká se na typy materiálů", + "World space": "Světový prostor", + "Wrap": "Zalamování", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "Materiál {name} nelze smazat. {reason}", + "{name} copy": "{name} kopie" +} diff --git a/frontend/src/i18n/modules/material/da.json b/frontend/src/i18n/modules/material/da.json new file mode 100644 index 00000000..b3341f72 --- /dev/null +++ b/frontend/src/i18n/modules/material/da.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "En graf med 1 node", + "A graph of {n} nodes": "En graf med {n} nodes", + "A texture drives this value; the value is its fallback": "En tekstur styrer denne værdi; værdien er dens reserveværdi", + "ACEScg": "ACEScg", + "Abbe number": "Abbetal", + "Add a map": "Tilføj en map", + "All parameters": "Alle parametre", + "Alpha": "Alfa", + "Aluminium": "Aluminium", + "Anisotropy": "Anisotropi", + "Assign to selection": "Tildel til markering", + "Base weight": "Basisvægt", + "Bilinear": "Bilineær", + "Blend": "Blanding", + "Blue": "Blå", + "Box": "Boks", + "Brushed metal": "Børstet metal", + "Bump": "Bump", + "Category": "Kategori", + "Change the material type": "Skift materialetype", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Skift {from} til {to}. Vil du beholde de nuværende værdier eller nulstille dem til den nye type?", + "Channel": "Kanal", + "Choose a texture image": "Vælg et teksturbillede", + "Choose an input": "Vælg et input", + "Chromium": "Krom", + "Clamp": "Begræns", + "Clear plastic": "Klar plast", + "Clear the texture slot": "Ryd teksturpladsen", + "Coat": "Coating", + "Coat IOR": "Coating-IOR", + "Coat colour": "Coatingfarve", + "Coat darkening": "Coating-mørkning", + "Coat roughness": "Coatingruhed", + "Cobalt": "Kobolt", + "Colour space": "Farverum", + "Copper": "Kobber", + "Custom colour": "Brugerdefineret farve", + "Cylindrical": "Cylindrisk", + "Data (raw)": "Data (rå)", + "Delete material": "Slet materiale", + "Diffuse": "Diffus", + "Diffuse roughness": "Diffus ruhed", + "Dispersion": "Dispersion", + "Displacement": "Displacement", + "Drive {input} with a texture": "Styr {input} med en tekstur", + "Driven by the graph. Edit the graph to change it.": "Styres af grafen. Redigér grafen for at ændre det.", + "Drives no input yet": "Styrer endnu intet input", + "Drives {inputs}": "Styrer {inputs}", + "Duplicate material": "Dupliker materiale", + "Edit graph": "Redigér graf", + "Edit the texture of {input}": "Redigér teksturen for {input}", + "Emission colour": "Emissionsfarve", + "Fallback": "Reserveværdi", + "Fallback colour": "Reservefarve", + "Film IOR": "Film-IOR", + "Film thickness": "Filmtykkelse", + "Filter": "Filter", + "Flip green (DirectX)": "Vend grøn (DirectX)", + "Fuzz": "Fuzz", + "Fuzz colour": "Fuzz-farve", + "Fuzz roughness": "Fuzz-ruhed", + "Generic": "Generelt", + "Gold": "Guld", + "Graph": "Graf", + "Green": "Grøn", + "IOR": "IOR", + "Images": "Billeder", + "In use by 1 part. Assign another material to it first.": "Bruges af 1 del. Tildel den først et andet materiale.", + "In use by {n} parts. Assign another material to them first.": "Bruges af {n} dele. Tildel dem først et andet materiale.", + "Invert": "Inverter", + "Iron": "Jern", + "Keep this material as a preset in your library": "Behold dette materiale som en forudindstilling i dit bibliotek", + "Keep values": "Behold værdier", + "Labels": "Etiketter", + "Linear sRGB": "Lineær sRGB", + "Luminance": "Luminans", + "Material types": "Materialetyper", + "Measured metals": "Målte metaller", + "Metallic paint": "Metallic lak", + "Mirror": "Spejl", + "Multiply by the value": "Gang med værdien", + "Name": "Navn", + "Nearest": "Nærmeste", + "New": "Ny", + "New material": "Nyt materiale", + "Nickel": "Nikkel", + "No graph": "Ingen graf", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Ingen graf. Denne type ser kun rigtig ud med sin graf; nulstil til typen for at få den tilbage.", + "No materials yet. Create one from a type with New.": "Ingen materialer endnu. Opret et fra en type med Ny.", + "No textures. Use the texture button beside a value, or add a map here.": "Ingen teksturer. Brug teksturknappen ved siden af en værdi, eller tilføj en map her.", + "Object space": "Objektrum", + "Offset U": "Forskydning U", + "Offset V": "Forskydning V", + "Open the node editor for this material": "Åbn nodeeditoren for dette materiale", + "Parameters": "Parametre", + "Pick a material first": "Vælg først et materiale", + "Pick or create a material to edit it.": "Vælg eller opret et materiale for at redigere det.", + "Planar": "Plan", + "Platinum": "Platin", + "Projection": "Projektion", + "RGB": "RGB", + "Range from": "Interval fra", + "Range to": "Interval til", + "Reading the material": "Læser materialet", + "Red": "Rød", + "Rename material": "Omdøb materiale", + "Repeat": "Gentag", + "Replace the image": "Erstat billedet", + "Reset to type": "Nulstil til type", + "Save to library": "Gem i biblioteket", + "Saved {name} to your library": "{name} er gemt i dit bibliotek", + "Saving to the library needs an engine with library.save.": "Lagring i biblioteket kræver en motor med library.save.", + "Scale U": "Skalering U", + "Scale V": "Skalering V", + "Select parts in the viewport or the scene first": "Vælg først dele i viewporten eller scenen", + "Silver": "Sølv", + "Space": "Rum", + "Specular colour": "Spekulær farve", + "Specular weight": "Spekulær vægt", + "Spherical": "Sfærisk", + "Strength": "Styrke", + "Subsurface": "Subsurface", + "Subsurface colour": "Subsurface-farve", + "Subsurface radius": "Subsurface-radius", + "Subsurface radius scale": "Skala for subsurface-radius", + "Texture": "Tekstur", + "Texture {key}": "Tekstur {key}", + "Texture ×": "Tekstur ×", + "Textures": "Teksturer", + "The engine does not know the type {id}; showing the main values.": "Motoren kender ikke typen {id}; viser de vigtigste værdier.", + "The engine lists no material types yet": "Motoren viser endnu ingen materialetyper", + "The image could not be uploaded ({status})": "Billedet kunne ikke uploades ({status})", + "The texture multiplies this value": "Teksturen ganges med denne værdi", + "Thin film": "Tynd film", + "Thin glass": "Tyndt glas", + "Thin walled": "Tyndvægget", + "Titanium": "Titanium", + "Transmission": "Transmission", + "Transmission colour": "Transmissionsfarve", + "Transmission depth": "Transmissionsdybde", + "Trilinear": "Trilineær", + "Type": "Type", + "UV set": "UV-sæt", + "Used by 1 part": "Brugt af 1 del", + "Used by {n} parts": "Brugt af {n} dele", + "Waiting for the material settings": "Venter på materialeindstillingerne", + "Waiting for the material types": "Venter på materialetyperne", + "World space": "Verdensrum", + "Wrap": "Wrap", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} kan ikke slettes. {reason}", + "{name} copy": "{name} kopi" +} diff --git a/frontend/src/i18n/modules/material/de.json b/frontend/src/i18n/modules/material/de.json new file mode 100644 index 00000000..f4a43800 --- /dev/null +++ b/frontend/src/i18n/modules/material/de.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Ein Graph aus 1 Knoten", + "A graph of {n} nodes": "Ein Graph aus {n} Knoten", + "A texture drives this value; the value is its fallback": "Eine Textur steuert diesen Wert; der Wert ist ihr Ersatz", + "ACEScg": "ACEScg", + "Abbe number": "Abbe-Zahl", + "Add a map": "Map hinzufügen", + "All parameters": "Alle Parameter", + "Alpha": "Alpha", + "Aluminium": "Aluminium", + "Anisotropy": "Anisotropie", + "Assign to selection": "Der Auswahl zuweisen", + "Base weight": "Basisgewicht", + "Bilinear": "Bilinear", + "Blend": "Überblendung", + "Blue": "Blau", + "Box": "Box", + "Brushed metal": "Gebürstetes Metall", + "Bump": "Bump", + "Category": "Kategorie", + "Change the material type": "Materialtyp ändern", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "{from} in {to} ändern. Aktuelle Werte behalten oder auf den neuen Typ zurücksetzen?", + "Channel": "Kanal", + "Choose a texture image": "Texturbild auswählen", + "Choose an input": "Eingang auswählen", + "Chromium": "Chrom", + "Clamp": "Begrenzen", + "Clear plastic": "Klarer Kunststoff", + "Clear the texture slot": "Texturfeld leeren", + "Coat": "Klarlack", + "Coat IOR": "Klarlack-IOR", + "Coat colour": "Klarlackfarbe", + "Coat darkening": "Klarlack-Abdunklung", + "Coat roughness": "Klarlack-Rauheit", + "Cobalt": "Kobalt", + "Colour space": "Farbraum", + "Copper": "Kupfer", + "Custom colour": "Eigene Farbe", + "Cylindrical": "Zylindrisch", + "Data (raw)": "Daten (roh)", + "Delete material": "Material löschen", + "Diffuse": "Diffus", + "Diffuse roughness": "Diffuse Rauheit", + "Dispersion": "Dispersion", + "Displacement": "Displacement", + "Drive {input} with a texture": "{input} mit einer Textur steuern", + "Driven by the graph. Edit the graph to change it.": "Vom Graph gesteuert. Bearbeite den Graph, um es zu ändern.", + "Drives no input yet": "Steuert noch keinen Eingang", + "Drives {inputs}": "Steuert {inputs}", + "Duplicate material": "Material duplizieren", + "Edit graph": "Graph bearbeiten", + "Edit the texture of {input}": "Textur von {input} bearbeiten", + "Emission colour": "Emissionsfarbe", + "Fallback": "Ersatzwert", + "Fallback colour": "Ersatzfarbe", + "Film IOR": "Schicht-IOR", + "Film thickness": "Schichtdicke", + "Filter": "Filter", + "Flip green (DirectX)": "Grün invertieren (DirectX)", + "Fuzz": "Flaum", + "Fuzz colour": "Flaumfarbe", + "Fuzz roughness": "Flaum-Rauheit", + "Generic": "Allgemein", + "Gold": "Gold", + "Graph": "Graph", + "Green": "Grün", + "IOR": "IOR", + "Images": "Bilder", + "In use by 1 part. Assign another material to it first.": "Wird von 1 Teil verwendet. Weise ihm zuerst ein anderes Material zu.", + "In use by {n} parts. Assign another material to them first.": "Wird von {n} Teilen verwendet. Weise ihnen zuerst ein anderes Material zu.", + "Invert": "Invertieren", + "Iron": "Eisen", + "Keep this material as a preset in your library": "Dieses Material als Vorgabe in deiner Bibliothek behalten", + "Keep values": "Werte behalten", + "Labels": "Kennzeichnungen", + "Linear sRGB": "Lineares sRGB", + "Luminance": "Luminanz", + "Material types": "Materialtypen", + "Measured metals": "Gemessene Metalle", + "Metallic paint": "Metallic-Lack", + "Mirror": "Spiegel", + "Multiply by the value": "Mit dem Wert multiplizieren", + "Name": "Name", + "Nearest": "Nächster Nachbar", + "New": "Neu", + "New material": "Neues Material", + "Nickel": "Nickel", + "No graph": "Kein Graph", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Kein Graph. Dieser Typ sieht nur mit seinem Graph richtig aus; setze auf den Typ zurück, um ihn wiederzubekommen.", + "No materials yet. Create one from a type with New.": "Noch keine Materialien. Erstelle eines aus einem Typ mit Neu.", + "No textures. Use the texture button beside a value, or add a map here.": "Keine Texturen. Nutze die Textur-Schaltfläche neben einem Wert oder füge hier eine Map hinzu.", + "Object space": "Objektraum", + "Offset U": "Versatz U", + "Offset V": "Versatz V", + "Open the node editor for this material": "Knoteneditor für dieses Material öffnen", + "Parameters": "Parameter", + "Pick a material first": "Wähle zuerst ein Material aus", + "Pick or create a material to edit it.": "Wähle ein Material aus oder erstelle eines, um es zu bearbeiten.", + "Planar": "Planar", + "Platinum": "Platin", + "Projection": "Projektion", + "RGB": "RGB", + "Range from": "Bereich von", + "Range to": "Bereich bis", + "Reading the material": "Material wird gelesen", + "Red": "Rot", + "Rename material": "Material umbenennen", + "Repeat": "Wiederholen", + "Replace the image": "Bild ersetzen", + "Reset to type": "Auf Typ zurücksetzen", + "Save to library": "In Bibliothek speichern", + "Saved {name} to your library": "{name} in deiner Bibliothek gespeichert", + "Saving to the library needs an engine with library.save.": "Zum Speichern in der Bibliothek ist eine Engine mit library.save nötig.", + "Scale U": "Skalierung U", + "Scale V": "Skalierung V", + "Select parts in the viewport or the scene first": "Wähle zuerst Teile im Viewport oder in der Szene aus", + "Silver": "Silber", + "Space": "Raum", + "Specular colour": "Spekularfarbe", + "Specular weight": "Spekulargewicht", + "Spherical": "Sphärisch", + "Strength": "Stärke", + "Subsurface": "Subsurface", + "Subsurface colour": "Subsurface-Farbe", + "Subsurface radius": "Subsurface-Radius", + "Subsurface radius scale": "Subsurface-Radius-Skalierung", + "Texture": "Textur", + "Texture {key}": "Textur {key}", + "Texture ×": "Textur ×", + "Textures": "Texturen", + "The engine does not know the type {id}; showing the main values.": "Die Engine kennt den Typ {id} nicht; die wichtigsten Werte werden angezeigt.", + "The engine lists no material types yet": "Die Engine listet noch keine Materialtypen auf", + "The image could not be uploaded ({status})": "Das Bild konnte nicht hochgeladen werden ({status})", + "The texture multiplies this value": "Die Textur multipliziert diesen Wert", + "Thin film": "Dünnschicht", + "Thin glass": "Dünnes Glas", + "Thin walled": "Dünnwandig", + "Titanium": "Titan", + "Transmission": "Transmission", + "Transmission colour": "Transmissionsfarbe", + "Transmission depth": "Transmissionstiefe", + "Trilinear": "Trilinear", + "Type": "Typ", + "UV set": "UV-Set", + "Used by 1 part": "Von 1 Teil verwendet", + "Used by {n} parts": "Von {n} Teilen verwendet", + "Waiting for the material settings": "Warten auf die Materialeinstellungen", + "Waiting for the material types": "Warten auf die Materialtypen", + "World space": "Weltraum", + "Wrap": "Randverhalten", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} kann nicht gelöscht werden. {reason}", + "{name} copy": "{name} Kopie" +} diff --git a/frontend/src/i18n/modules/material/es-MX.json b/frontend/src/i18n/modules/material/es-MX.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/material/es-MX.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/material/es.json b/frontend/src/i18n/modules/material/es.json new file mode 100644 index 00000000..8dee7daf --- /dev/null +++ b/frontend/src/i18n/modules/material/es.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Un grafo de 1 nodo", + "A graph of {n} nodes": "Un grafo de {n} nodos", + "A texture drives this value; the value is its fallback": "Una textura controla este valor; el valor es su reserva", + "ACEScg": "ACEScg", + "Abbe number": "Número de Abbe", + "Add a map": "Añadir un mapa", + "All parameters": "Todos los parámetros", + "Alpha": "Alfa", + "Aluminium": "Aluminio", + "Anisotropy": "Anisotropía", + "Assign to selection": "Asignar a la selección", + "Base weight": "Peso base", + "Bilinear": "Bilineal", + "Blend": "Mezcla", + "Blue": "Azul", + "Box": "Cúbica", + "Brushed metal": "Metal cepillado", + "Bump": "Bump", + "Category": "Categoría", + "Change the material type": "Cambiar el tipo de material", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Cambiar {from} a {to}. ¿Conservar los valores actuales o restablecerlos al nuevo tipo?", + "Channel": "Canal", + "Choose a texture image": "Elegir una imagen de textura", + "Choose an input": "Elegir una entrada", + "Chromium": "Cromo", + "Clamp": "Extender", + "Clear plastic": "Plástico transparente", + "Clear the texture slot": "Vaciar la ranura de textura", + "Coat": "Barniz", + "Coat IOR": "IOR del barniz", + "Coat colour": "Color del barniz", + "Coat darkening": "Oscurecimiento del barniz", + "Coat roughness": "Rugosidad del barniz", + "Cobalt": "Cobalto", + "Colour space": "Espacio de color", + "Copper": "Cobre", + "Custom colour": "Color personalizado", + "Cylindrical": "Cilíndrica", + "Data (raw)": "Datos (sin procesar)", + "Delete material": "Eliminar material", + "Diffuse": "Difuso", + "Diffuse roughness": "Rugosidad difusa", + "Dispersion": "Dispersión", + "Displacement": "Desplazamiento", + "Drive {input} with a texture": "Controlar {input} con una textura", + "Driven by the graph. Edit the graph to change it.": "Controlado por el grafo. Edita el grafo para cambiarlo.", + "Drives no input yet": "Aún no controla ninguna entrada", + "Drives {inputs}": "Controla {inputs}", + "Duplicate material": "Duplicar material", + "Edit graph": "Editar grafo", + "Edit the texture of {input}": "Editar la textura de {input}", + "Emission colour": "Color de emisión", + "Fallback": "Valor de reserva", + "Fallback colour": "Color de reserva", + "Film IOR": "IOR de la película", + "Film thickness": "Grosor de la película", + "Filter": "Filtro", + "Flip green (DirectX)": "Invertir el verde (DirectX)", + "Fuzz": "Pelusa", + "Fuzz colour": "Color de la pelusa", + "Fuzz roughness": "Rugosidad de la pelusa", + "Generic": "Genérico", + "Gold": "Oro", + "Graph": "Grafo", + "Green": "Verde", + "IOR": "IOR", + "Images": "Imágenes", + "In use by 1 part. Assign another material to it first.": "Lo usa 1 pieza. Asígnale primero otro material.", + "In use by {n} parts. Assign another material to them first.": "Lo usan {n} piezas. Asígnales primero otro material.", + "Invert": "Invertir", + "Iron": "Hierro", + "Keep this material as a preset in your library": "Guardar este material como preajuste en tu biblioteca", + "Keep values": "Conservar valores", + "Labels": "Etiquetas", + "Linear sRGB": "sRGB lineal", + "Luminance": "Luminancia", + "Material types": "Tipos de material", + "Measured metals": "Metales medidos", + "Metallic paint": "Pintura metálica", + "Mirror": "Espejo", + "Multiply by the value": "Multiplicar por el valor", + "Name": "Nombre", + "Nearest": "Más cercano", + "New": "Nuevo", + "New material": "Material nuevo", + "Nickel": "Níquel", + "No graph": "Sin grafo", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Sin grafo. Este tipo solo se ve bien con su grafo; restablece al tipo para recuperarlo.", + "No materials yet. Create one from a type with New.": "Aún no hay materiales. Crea uno a partir de un tipo con Nuevo.", + "No textures. Use the texture button beside a value, or add a map here.": "Sin texturas. Usa el botón de textura junto a un valor o añade un mapa aquí.", + "Object space": "Espacio de objeto", + "Offset U": "Desfase U", + "Offset V": "Desfase V", + "Open the node editor for this material": "Abrir el editor de nodos de este material", + "Parameters": "Parámetros", + "Pick a material first": "Elige primero un material", + "Pick or create a material to edit it.": "Elige o crea un material para editarlo.", + "Planar": "Plana", + "Platinum": "Platino", + "Projection": "Proyección", + "RGB": "RGB", + "Range from": "Rango desde", + "Range to": "Rango hasta", + "Reading the material": "Leyendo el material", + "Red": "Rojo", + "Rename material": "Renombrar material", + "Repeat": "Repetir", + "Replace the image": "Reemplazar la imagen", + "Reset to type": "Restablecer al tipo", + "Save to library": "Guardar en la biblioteca", + "Saved {name} to your library": "Se guardó {name} en tu biblioteca", + "Saving to the library needs an engine with library.save.": "Guardar en la biblioteca requiere un motor con library.save.", + "Scale U": "Escala U", + "Scale V": "Escala V", + "Select parts in the viewport or the scene first": "Selecciona primero piezas en la vista 3D o en la escena", + "Silver": "Plata", + "Space": "Espacio", + "Specular colour": "Color especular", + "Specular weight": "Peso especular", + "Spherical": "Esférica", + "Strength": "Intensidad", + "Subsurface": "Subsuperficie", + "Subsurface colour": "Color de subsuperficie", + "Subsurface radius": "Radio de subsuperficie", + "Subsurface radius scale": "Escala del radio de subsuperficie", + "Texture": "Textura", + "Texture {key}": "Textura {key}", + "Texture ×": "Textura ×", + "Textures": "Texturas", + "The engine does not know the type {id}; showing the main values.": "El motor no conoce el tipo {id}; se muestran los valores principales.", + "The engine lists no material types yet": "El motor aún no enumera ningún tipo de material", + "The image could not be uploaded ({status})": "No se pudo subir la imagen ({status})", + "The texture multiplies this value": "La textura multiplica este valor", + "Thin film": "Película fina", + "Thin glass": "Vidrio fino", + "Thin walled": "Pared delgada", + "Titanium": "Titanio", + "Transmission": "Transmisión", + "Transmission colour": "Color de transmisión", + "Transmission depth": "Profundidad de transmisión", + "Trilinear": "Trilineal", + "Type": "Tipo", + "UV set": "Juego de UV", + "Used by 1 part": "Usado por 1 pieza", + "Used by {n} parts": "Usado por {n} piezas", + "Waiting for the material settings": "Esperando los ajustes del material", + "Waiting for the material types": "Esperando los tipos de material", + "World space": "Espacio del mundo", + "Wrap": "Modo de repetición", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "No se puede eliminar {name}. {reason}", + "{name} copy": "{name} copia" +} diff --git a/frontend/src/i18n/modules/material/fi.json b/frontend/src/i18n/modules/material/fi.json new file mode 100644 index 00000000..807ba498 --- /dev/null +++ b/frontend/src/i18n/modules/material/fi.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Graafi, jossa on 1 solmu", + "A graph of {n} nodes": "Graafi, jossa on {n} solmua", + "A texture drives this value; the value is its fallback": "Tekstuuri ohjaa tätä arvoa; arvo on sen varaarvo", + "ACEScg": "ACEScg", + "Abbe number": "Abben luku", + "Add a map": "Lisää kartta", + "All parameters": "Kaikki parametrit", + "Alpha": "Alfa", + "Aluminium": "Alumiini", + "Anisotropy": "Anisotropia", + "Assign to selection": "Määritä valinnalle", + "Base weight": "Peruspaino", + "Bilinear": "Bilineaarinen", + "Blend": "Sekoitus", + "Blue": "Sininen", + "Box": "Laatikko", + "Brushed metal": "Harjattu metalli", + "Bump": "Bump", + "Category": "Luokka", + "Change the material type": "Vaihda materiaalin tyyppi", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Vaihda {from} tyyppiin {to}. Säilytetäänkö nykyiset arvot vai palautetaanko ne uuden tyypin arvoihin?", + "Channel": "Kanava", + "Choose a texture image": "Valitse tekstuurikuva", + "Choose an input": "Valitse tulo", + "Chromium": "Kromi", + "Clamp": "Rajaus", + "Clear plastic": "Kirkas muovi", + "Clear the texture slot": "Tyhjennä tekstuuripaikka", + "Coat": "Pinnoite", + "Coat IOR": "Pinnoitteen IOR", + "Coat colour": "Pinnoitteen väri", + "Coat darkening": "Pinnoitteen tummuminen", + "Coat roughness": "Pinnoitteen karheus", + "Cobalt": "Koboltti", + "Colour space": "Väriavaruus", + "Copper": "Kupari", + "Custom colour": "Mukautettu väri", + "Cylindrical": "Sylinterimäinen", + "Data (raw)": "Data (raaka)", + "Delete material": "Poista materiaali", + "Diffuse": "Diffuusi", + "Diffuse roughness": "Diffuusin karheus", + "Dispersion": "Dispersio", + "Displacement": "Siirtymä", + "Drive {input} with a texture": "Ohjaa kohdetta {input} tekstuurilla", + "Driven by the graph. Edit the graph to change it.": "Graafi ohjaa tätä. Muuta sitä muokkaamalla graafia.", + "Drives no input yet": "Ei ohjaa vielä yhtään tuloa", + "Drives {inputs}": "Ohjaa: {inputs}", + "Duplicate material": "Monista materiaali", + "Edit graph": "Muokkaa graafia", + "Edit the texture of {input}": "Muokkaa kohteen {input} tekstuuria", + "Emission colour": "Emissioväri", + "Fallback": "Varaarvo", + "Fallback colour": "Varaväri", + "Film IOR": "Kalvon IOR", + "Film thickness": "Kalvon paksuus", + "Filter": "Suodatus", + "Flip green (DirectX)": "Käännä vihreä (DirectX)", + "Fuzz": "Nukka", + "Fuzz colour": "Nukan väri", + "Fuzz roughness": "Nukan karheus", + "Generic": "Yleinen", + "Gold": "Kulta", + "Graph": "Graafi", + "Green": "Vihreä", + "IOR": "IOR", + "Images": "Kuvat", + "In use by 1 part. Assign another material to it first.": "Käytössä 1 osassa. Määritä sille ensin toinen materiaali.", + "In use by {n} parts. Assign another material to them first.": "Käytössä {n} osassa. Määritä niille ensin toinen materiaali.", + "Invert": "Käännä", + "Iron": "Rauta", + "Keep this material as a preset in your library": "Säilytä tämä materiaali esiasetuksena kirjastossasi", + "Keep values": "Säilytä arvot", + "Labels": "Tunnisteet", + "Linear sRGB": "Lineaarinen sRGB", + "Luminance": "Luminanssi", + "Material types": "Materiaalityypit", + "Measured metals": "Mitatut metallit", + "Metallic paint": "Metallimaali", + "Mirror": "Peilaus", + "Multiply by the value": "Kerro arvolla", + "Name": "Nimi", + "Nearest": "Lähin", + "New": "Uusi", + "New material": "Uusi materiaali", + "Nickel": "Nikkeli", + "No graph": "Ei graafia", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Ei graafia. Tämä tyyppi näyttää oikealta vain graafinsa kanssa; palauta tyypin oletukset, niin saat sen takaisin.", + "No materials yet. Create one from a type with New.": "Ei vielä materiaaleja. Luo sellainen tyypistä painikkeella Uusi.", + "No textures. Use the texture button beside a value, or add a map here.": "Ei tekstuureja. Käytä arvon vieressä olevaa tekstuuripainiketta tai lisää kartta tähän.", + "Object space": "Objektiavaruus", + "Offset U": "Siirto U", + "Offset V": "Siirto V", + "Open the node editor for this material": "Avaa tämän materiaalin solmueditori", + "Parameters": "Parametrit", + "Pick a material first": "Valitse ensin materiaali", + "Pick or create a material to edit it.": "Valitse tai luo muokattava materiaali.", + "Planar": "Tasomainen", + "Platinum": "Platina", + "Projection": "Projektio", + "RGB": "RGB", + "Range from": "Alue alkaen", + "Range to": "Alue asti", + "Reading the material": "Luetaan materiaalia", + "Red": "Punainen", + "Rename material": "Nimeä materiaali uudelleen", + "Repeat": "Toisto", + "Replace the image": "Korvaa kuva", + "Reset to type": "Palauta tyypin oletukset", + "Save to library": "Tallenna kirjastoon", + "Saved {name} to your library": "{name} tallennettu kirjastoosi", + "Saving to the library needs an engine with library.save.": "Kirjastoon tallentaminen vaatii moottorin, jossa on library.save.", + "Scale U": "Skaalaus U", + "Scale V": "Skaalaus V", + "Select parts in the viewport or the scene first": "Valitse ensin osia katseluikkunassa tai kohtauksessa", + "Silver": "Hopea", + "Space": "Avaruus", + "Specular colour": "Kiillon väri", + "Specular weight": "Kiillon paino", + "Spherical": "Pallomainen", + "Strength": "Voimakkuus", + "Subsurface": "Pinnanalainen sironta", + "Subsurface colour": "Sirontaväri", + "Subsurface radius": "Sirontasäde", + "Subsurface radius scale": "Sirontasäteen skaala", + "Texture": "Tekstuuri", + "Texture {key}": "Tekstuuri {key}", + "Texture ×": "Tekstuuri ×", + "Textures": "Tekstuurit", + "The engine does not know the type {id}; showing the main values.": "Moottori ei tunne tyyppiä {id}; näytetään tärkeimmät arvot.", + "The engine lists no material types yet": "Moottori ei vielä listaa materiaalityyppejä", + "The image could not be uploaded ({status})": "Kuvaa ei voitu lähettää ({status})", + "The texture multiplies this value": "Tekstuuri kertoo tämän arvon", + "Thin film": "Ohutkalvo", + "Thin glass": "Ohut lasi", + "Thin walled": "Ohutseinäinen", + "Titanium": "Titaani", + "Transmission": "Läpäisy", + "Transmission colour": "Läpäisyn väri", + "Transmission depth": "Läpäisyn syvyys", + "Trilinear": "Trilineaarinen", + "Type": "Tyyppi", + "UV set": "UV-joukko", + "Used by 1 part": "Käytössä 1 osassa", + "Used by {n} parts": "Käytössä {n} osassa", + "Waiting for the material settings": "Odotetaan materiaaliasetuksia", + "Waiting for the material types": "Odotetaan materiaalityyppejä", + "World space": "Maailma-avaruus", + "Wrap": "Kääre", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "Kohdetta {name} ei voi poistaa. {reason}", + "{name} copy": "{name} kopio" +} diff --git a/frontend/src/i18n/modules/material/fr-CA.json b/frontend/src/i18n/modules/material/fr-CA.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/frontend/src/i18n/modules/material/fr-CA.json @@ -0,0 +1 @@ +{} diff --git a/frontend/src/i18n/modules/material/fr.json b/frontend/src/i18n/modules/material/fr.json new file mode 100644 index 00000000..a86ee984 --- /dev/null +++ b/frontend/src/i18n/modules/material/fr.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Un graphe de 1 nœud", + "A graph of {n} nodes": "Un graphe de {n} nœuds", + "A texture drives this value; the value is its fallback": "Une texture pilote cette valeur ; la valeur sert de repli", + "ACEScg": "ACEScg", + "Abbe number": "Nombre d'Abbe", + "Add a map": "Ajouter une map", + "All parameters": "Tous les paramètres", + "Alpha": "Alpha", + "Aluminium": "Aluminium", + "Anisotropy": "Anisotropie", + "Assign to selection": "Affecter à la sélection", + "Base weight": "Poids de base", + "Bilinear": "Bilinéaire", + "Blend": "Fondu", + "Blue": "Bleu", + "Box": "Cubique", + "Brushed metal": "Métal brossé", + "Bump": "Bump", + "Category": "Catégorie", + "Change the material type": "Changer le type de matériau", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Passer de {from} à {to}. Conserver les valeurs actuelles ou les réinitialiser pour le nouveau type ?", + "Channel": "Canal", + "Choose a texture image": "Choisir une image de texture", + "Choose an input": "Choisir une entrée", + "Chromium": "Chrome", + "Clamp": "Étendre", + "Clear plastic": "Plastique transparent", + "Clear the texture slot": "Vider l'emplacement de texture", + "Coat": "Vernis", + "Coat IOR": "IOR du vernis", + "Coat colour": "Couleur du vernis", + "Coat darkening": "Assombrissement du vernis", + "Coat roughness": "Rugosité du vernis", + "Cobalt": "Cobalt", + "Colour space": "Espace colorimétrique", + "Copper": "Cuivre", + "Custom colour": "Couleur personnalisée", + "Cylindrical": "Cylindrique", + "Data (raw)": "Données (brutes)", + "Delete material": "Supprimer le matériau", + "Diffuse": "Diffus", + "Diffuse roughness": "Rugosité diffuse", + "Dispersion": "Dispersion", + "Displacement": "Déplacement", + "Drive {input} with a texture": "Piloter {input} avec une texture", + "Driven by the graph. Edit the graph to change it.": "Piloté par le graphe. Modifiez le graphe pour le changer.", + "Drives no input yet": "Ne pilote encore aucune entrée", + "Drives {inputs}": "Pilote {inputs}", + "Duplicate material": "Dupliquer le matériau", + "Edit graph": "Modifier le graphe", + "Edit the texture of {input}": "Modifier la texture de {input}", + "Emission colour": "Couleur d'émission", + "Fallback": "Valeur de repli", + "Fallback colour": "Couleur de repli", + "Film IOR": "IOR du film", + "Film thickness": "Épaisseur du film", + "Filter": "Filtre", + "Flip green (DirectX)": "Inverser le vert (DirectX)", + "Fuzz": "Duvet", + "Fuzz colour": "Couleur du duvet", + "Fuzz roughness": "Rugosité du duvet", + "Generic": "Générique", + "Gold": "Or", + "Graph": "Graphe", + "Green": "Vert", + "IOR": "IOR", + "Images": "Images", + "In use by 1 part. Assign another material to it first.": "Utilisé par 1 pièce. Affectez-lui d'abord un autre matériau.", + "In use by {n} parts. Assign another material to them first.": "Utilisé par {n} pièces. Affectez-leur d'abord un autre matériau.", + "Invert": "Inverser", + "Iron": "Fer", + "Keep this material as a preset in your library": "Conserver ce matériau comme préréglage dans votre bibliothèque", + "Keep values": "Conserver les valeurs", + "Labels": "Étiquettes", + "Linear sRGB": "sRGB linéaire", + "Luminance": "Luminance", + "Material types": "Types de matériaux", + "Measured metals": "Métaux mesurés", + "Metallic paint": "Peinture métallisée", + "Mirror": "Miroir", + "Multiply by the value": "Multiplier par la valeur", + "Name": "Nom", + "Nearest": "Plus proche voisin", + "New": "Nouveau", + "New material": "Nouveau matériau", + "Nickel": "Nickel", + "No graph": "Aucun graphe", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Aucun graphe. Ce type n'a un rendu correct qu'avec son graphe ; réinitialisez sur le type pour le retrouver.", + "No materials yet. Create one from a type with New.": "Aucun matériau pour le moment. Créez-en un à partir d'un type avec Nouveau.", + "No textures. Use the texture button beside a value, or add a map here.": "Aucune texture. Utilisez le bouton de texture à côté d'une valeur ou ajoutez une map ici.", + "Object space": "Espace objet", + "Offset U": "Décalage U", + "Offset V": "Décalage V", + "Open the node editor for this material": "Ouvrir l'éditeur de nœuds de ce matériau", + "Parameters": "Paramètres", + "Pick a material first": "Choisissez d'abord un matériau", + "Pick or create a material to edit it.": "Choisissez ou créez un matériau pour le modifier.", + "Planar": "Planaire", + "Platinum": "Platine", + "Projection": "Projection", + "RGB": "RVB", + "Range from": "Plage de", + "Range to": "Plage jusqu'à", + "Reading the material": "Lecture du matériau", + "Red": "Rouge", + "Rename material": "Renommer le matériau", + "Repeat": "Répéter", + "Replace the image": "Remplacer l'image", + "Reset to type": "Réinitialiser sur le type", + "Save to library": "Enregistrer dans la bibliothèque", + "Saved {name} to your library": "{name} enregistré dans votre bibliothèque", + "Saving to the library needs an engine with library.save.": "L'enregistrement dans la bibliothèque nécessite un moteur avec library.save.", + "Scale U": "Échelle U", + "Scale V": "Échelle V", + "Select parts in the viewport or the scene first": "Sélectionnez d'abord des pièces dans la vue 3D ou la scène", + "Silver": "Argent", + "Space": "Espace", + "Specular colour": "Couleur spéculaire", + "Specular weight": "Poids spéculaire", + "Spherical": "Sphérique", + "Strength": "Intensité", + "Subsurface": "Sous-surface", + "Subsurface colour": "Couleur de sous-surface", + "Subsurface radius": "Rayon de sous-surface", + "Subsurface radius scale": "Échelle du rayon de sous-surface", + "Texture": "Texture", + "Texture {key}": "Texture {key}", + "Texture ×": "Texture ×", + "Textures": "Textures", + "The engine does not know the type {id}; showing the main values.": "Le moteur ne connaît pas le type {id} ; affichage des valeurs principales.", + "The engine lists no material types yet": "Le moteur ne liste encore aucun type de matériau", + "The image could not be uploaded ({status})": "L'image n'a pas pu être téléversée ({status})", + "The texture multiplies this value": "La texture multiplie cette valeur", + "Thin film": "Film mince", + "Thin glass": "Verre mince", + "Thin walled": "Paroi mince", + "Titanium": "Titane", + "Transmission": "Transmission", + "Transmission colour": "Couleur de transmission", + "Transmission depth": "Profondeur de transmission", + "Trilinear": "Trilinéaire", + "Type": "Type", + "UV set": "Jeu d'UV", + "Used by 1 part": "Utilisé par 1 pièce", + "Used by {n} parts": "Utilisé par {n} pièces", + "Waiting for the material settings": "En attente des réglages du matériau", + "Waiting for the material types": "En attente des types de matériaux", + "World space": "Espace monde", + "Wrap": "Mode de répétition", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} ne peut pas être supprimé. {reason}", + "{name} copy": "{name} copie" +} diff --git a/frontend/src/i18n/modules/material/hu.json b/frontend/src/i18n/modules/material/hu.json new file mode 100644 index 00000000..c37d9420 --- /dev/null +++ b/frontend/src/i18n/modules/material/hu.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Gráf 1 csomóponttal", + "A graph of {n} nodes": "Gráf {n} csomóponttal", + "A texture drives this value; the value is its fallback": "Ezt az értéket egy textúra vezérli; az érték a tartaléka", + "ACEScg": "ACEScg", + "Abbe number": "Abbe-szám", + "Add a map": "Térkép hozzáadása", + "All parameters": "Összes paraméter", + "Alpha": "Alfa", + "Aluminium": "Alumínium", + "Anisotropy": "Anizotrópia", + "Assign to selection": "Hozzárendelés a kijelöléshez", + "Base weight": "Alapsúly", + "Bilinear": "Bilineáris", + "Blend": "Keverés", + "Blue": "Kék", + "Box": "Doboz", + "Brushed metal": "Szálcsiszolt fém", + "Bump": "Bump", + "Category": "Kategória", + "Change the material type": "Anyagtípus módosítása", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "{from} cseréje erre: {to}. Megtartja a jelenlegi értékeket, vagy visszaállítja őket az új típus értékeire?", + "Channel": "Csatorna", + "Choose a texture image": "Válasszon textúraképet", + "Choose an input": "Válasszon bemenetet", + "Chromium": "Króm", + "Clamp": "Rögzítés", + "Clear plastic": "Átlátszó műanyag", + "Clear the texture slot": "Textúrahely kiürítése", + "Coat": "Lakkréteg", + "Coat IOR": "Lakkréteg IOR", + "Coat colour": "Lakkréteg színe", + "Coat darkening": "Lakkréteg sötétedése", + "Coat roughness": "Lakkréteg érdessége", + "Cobalt": "Kobalt", + "Colour space": "Színtér", + "Copper": "Réz", + "Custom colour": "Egyéni szín", + "Cylindrical": "Henger", + "Data (raw)": "Adat (nyers)", + "Delete material": "Anyag törlése", + "Diffuse": "Diffúz", + "Diffuse roughness": "Diffúz érdesség", + "Dispersion": "Diszperzió", + "Displacement": "Elmozdítás", + "Drive {input} with a texture": "A(z) {input} vezérlése textúrával", + "Driven by the graph. Edit the graph to change it.": "A gráf vezérli. Módosításhoz szerkessze a gráfot.", + "Drives no input yet": "Még egyetlen bemenetet sem vezérel", + "Drives {inputs}": "Vezérli: {inputs}", + "Duplicate material": "Anyag kettőzése", + "Edit graph": "Gráf szerkesztése", + "Edit the texture of {input}": "A(z) {input} textúrájának szerkesztése", + "Emission colour": "Emisszió színe", + "Fallback": "Tartalékérték", + "Fallback colour": "Tartalékszín", + "Film IOR": "Réteg IOR", + "Film thickness": "Rétegvastagság", + "Filter": "Szűrés", + "Flip green (DirectX)": "Zöld megfordítása (DirectX)", + "Fuzz": "Pihe", + "Fuzz colour": "Pihe színe", + "Fuzz roughness": "Pihe érdessége", + "Generic": "Általános", + "Gold": "Arany", + "Graph": "Gráf", + "Green": "Zöld", + "IOR": "IOR", + "Images": "Képek", + "In use by 1 part. Assign another material to it first.": "1 alkatrész használja. Előbb rendeljen hozzá másik anyagot.", + "In use by {n} parts. Assign another material to them first.": "{n} alkatrész használja. Előbb rendeljen hozzájuk másik anyagot.", + "Invert": "Invertálás", + "Iron": "Vas", + "Keep this material as a preset in your library": "Az anyag megőrzése előbeállításként a könyvtárában", + "Keep values": "Értékek megtartása", + "Labels": "Címkék", + "Linear sRGB": "Lineáris sRGB", + "Luminance": "Luminancia", + "Material types": "Anyagtípusok", + "Measured metals": "Mért fémek", + "Metallic paint": "Metálfesték", + "Mirror": "Tükrözés", + "Multiply by the value": "Szorzás az értékkel", + "Name": "Név", + "Nearest": "Legközelebbi", + "New": "Új", + "New material": "Új anyag", + "Nickel": "Nikkel", + "No graph": "Nincs gráf", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Nincs gráf. Ez a típus csak a saját gráfjával néz ki helyesen; a visszaszerzéséhez állítsa vissza a típus alaphelyzetét.", + "No materials yet. Create one from a type with New.": "Még nincsenek anyagok. Hozzon létre egyet típusból az Új gombbal.", + "No textures. Use the texture button beside a value, or add a map here.": "Nincsenek textúrák. Használja az érték melletti textúragombot, vagy adjon hozzá itt térképet.", + "Object space": "Objektumtér", + "Offset U": "Eltolás U", + "Offset V": "Eltolás V", + "Open the node editor for this material": "A csomópontszerkesztő megnyitása ehhez az anyaghoz", + "Parameters": "Paraméterek", + "Pick a material first": "Előbb válasszon anyagot", + "Pick or create a material to edit it.": "Válasszon ki vagy hozzon létre egy anyagot a szerkesztéshez.", + "Planar": "Síkbeli", + "Platinum": "Platina", + "Projection": "Vetítés", + "RGB": "RGB", + "Range from": "Tartomány kezdete", + "Range to": "Tartomány vége", + "Reading the material": "Anyag beolvasása", + "Red": "Piros", + "Rename material": "Anyag átnevezése", + "Repeat": "Ismétlés", + "Replace the image": "Kép cseréje", + "Reset to type": "Típus alaphelyzete", + "Save to library": "Mentés a könyvtárba", + "Saved {name} to your library": "A(z) {name} elmentve a könyvtárba", + "Saving to the library needs an engine with library.save.": "A könyvtárba mentéshez a library.save parancsot ismerő motor kell.", + "Scale U": "Méretezés U", + "Scale V": "Méretezés V", + "Select parts in the viewport or the scene first": "Előbb jelöljön ki alkatrészeket a nézetablakban vagy a jelenetben", + "Silver": "Ezüst", + "Space": "Tér", + "Specular colour": "Spekuláris szín", + "Specular weight": "Spekuláris súly", + "Spherical": "Gömb", + "Strength": "Erősség", + "Subsurface": "Felszín alatti szóródás", + "Subsurface colour": "Szóródás színe", + "Subsurface radius": "Szóródási sugár", + "Subsurface radius scale": "Szóródási sugár skálája", + "Texture": "Textúra", + "Texture {key}": "{key} textúra", + "Texture ×": "Textúra ×", + "Textures": "Textúrák", + "The engine does not know the type {id}; showing the main values.": "A motor nem ismeri a(z) {id} típust; a fő értékek láthatók.", + "The engine lists no material types yet": "A motor még nem sorol fel anyagtípusokat", + "The image could not be uploaded ({status})": "A képet nem sikerült feltölteni ({status})", + "The texture multiplies this value": "A textúra megszorozza ezt az értéket", + "Thin film": "Vékonyréteg", + "Thin glass": "Vékony üveg", + "Thin walled": "Vékony falú", + "Titanium": "Titán", + "Transmission": "Áteresztés", + "Transmission colour": "Áteresztés színe", + "Transmission depth": "Áteresztés mélysége", + "Trilinear": "Trilineáris", + "Type": "Típus", + "UV set": "UV-készlet", + "Used by 1 part": "1 alkatrész használja", + "Used by {n} parts": "{n} alkatrész használja", + "Waiting for the material settings": "Várakozás az anyagbeállításokra", + "Waiting for the material types": "Várakozás az anyagtípusokra", + "World space": "Világtér", + "Wrap": "Burkolás", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "A(z) {name} nem törölhető. {reason}", + "{name} copy": "{name} másolata" +} diff --git a/frontend/src/i18n/modules/material/id.json b/frontend/src/i18n/modules/material/id.json new file mode 100644 index 00000000..c578eec5 --- /dev/null +++ b/frontend/src/i18n/modules/material/id.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Graf dengan 1 node", + "A graph of {n} nodes": "Graf dengan {n} node", + "A texture drives this value; the value is its fallback": "Tekstur menggerakkan nilai ini; nilai ini menjadi cadangannya", + "ACEScg": "ACEScg", + "Abbe number": "Bilangan Abbe", + "Add a map": "Tambah map", + "All parameters": "Semua parameter", + "Alpha": "Alfa", + "Aluminium": "Aluminium", + "Anisotropy": "Anisotropi", + "Assign to selection": "Tetapkan ke pilihan", + "Base weight": "Bobot dasar", + "Bilinear": "Bilinear", + "Blend": "Campur", + "Blue": "Biru", + "Box": "Kotak", + "Brushed metal": "Logam sikat", + "Bump": "Bump", + "Category": "Kategori", + "Change the material type": "Ubah tipe material", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Ubah {from} ke {to}. Pertahankan nilai saat ini, atau setel ulang ke tipe baru?", + "Channel": "Kanal", + "Choose a texture image": "Pilih gambar tekstur", + "Choose an input": "Pilih input", + "Chromium": "Kromium", + "Clamp": "Jepit", + "Clear plastic": "Plastik bening", + "Clear the texture slot": "Kosongkan slot tekstur", + "Coat": "Lapisan coat", + "Coat IOR": "IOR coat", + "Coat colour": "Warna coat", + "Coat darkening": "Penggelapan coat", + "Coat roughness": "Roughness coat", + "Cobalt": "Kobalt", + "Colour space": "Ruang warna", + "Copper": "Tembaga", + "Custom colour": "Warna kustom", + "Cylindrical": "Silinder", + "Data (raw)": "Data (mentah)", + "Delete material": "Hapus material", + "Diffuse": "Diffuse", + "Diffuse roughness": "Roughness diffuse", + "Dispersion": "Dispersi", + "Displacement": "Displacement", + "Drive {input} with a texture": "Gerakkan {input} dengan tekstur", + "Driven by the graph. Edit the graph to change it.": "Digerakkan oleh graf. Sunting graf untuk mengubahnya.", + "Drives no input yet": "Belum menggerakkan input apa pun", + "Drives {inputs}": "Menggerakkan {inputs}", + "Duplicate material": "Duplikat material", + "Edit graph": "Sunting graf", + "Edit the texture of {input}": "Sunting tekstur {input}", + "Emission colour": "Warna emisi", + "Fallback": "Cadangan", + "Fallback colour": "Warna cadangan", + "Film IOR": "IOR film", + "Film thickness": "Ketebalan film", + "Filter": "Filter", + "Flip green (DirectX)": "Balik hijau (DirectX)", + "Fuzz": "Fuzz", + "Fuzz colour": "Warna fuzz", + "Fuzz roughness": "Roughness fuzz", + "Generic": "Umum", + "Gold": "Emas", + "Graph": "Graf", + "Green": "Hijau", + "IOR": "IOR", + "Images": "Gambar", + "In use by 1 part. Assign another material to it first.": "Digunakan oleh 1 bagian. Tetapkan material lain padanya terlebih dahulu.", + "In use by {n} parts. Assign another material to them first.": "Digunakan oleh {n} bagian. Tetapkan material lain pada bagian-bagian itu terlebih dahulu.", + "Invert": "Balikkan", + "Iron": "Besi", + "Keep this material as a preset in your library": "Simpan material ini sebagai preset di pustaka Anda", + "Keep values": "Pertahankan nilai", + "Labels": "Label", + "Linear sRGB": "sRGB linear", + "Luminance": "Luminans", + "Material types": "Tipe material", + "Measured metals": "Logam terukur", + "Metallic paint": "Cat metalik", + "Mirror": "Cermin", + "Multiply by the value": "Kalikan dengan nilai", + "Name": "Nama", + "Nearest": "Terdekat", + "New": "Baru", + "New material": "Material baru", + "Nickel": "Nikel", + "No graph": "Tanpa graf", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Tanpa graf. Tipe ini tampak benar hanya dengan grafnya; setel ulang ke tipe untuk mengembalikannya.", + "No materials yet. Create one from a type with New.": "Belum ada material. Buat dari sebuah tipe dengan Baru.", + "No textures. Use the texture button beside a value, or add a map here.": "Tidak ada tekstur. Gunakan tombol tekstur di samping nilai, atau tambah map di sini.", + "Object space": "Ruang objek", + "Offset U": "Offset U", + "Offset V": "Offset V", + "Open the node editor for this material": "Buka editor node untuk material ini", + "Parameters": "Parameter", + "Pick a material first": "Pilih material terlebih dahulu", + "Pick or create a material to edit it.": "Pilih atau buat material untuk menyuntingnya.", + "Planar": "Planar", + "Platinum": "Platina", + "Projection": "Proyeksi", + "RGB": "RGB", + "Range from": "Rentang dari", + "Range to": "Rentang ke", + "Reading the material": "Membaca material", + "Red": "Merah", + "Rename material": "Ganti nama material", + "Repeat": "Ulangi", + "Replace the image": "Ganti gambar", + "Reset to type": "Setel ulang ke tipe", + "Save to library": "Simpan ke pustaka", + "Saved {name} to your library": "{name} disimpan ke pustaka Anda", + "Saving to the library needs an engine with library.save.": "Menyimpan ke pustaka memerlukan mesin dengan library.save.", + "Scale U": "Skala U", + "Scale V": "Skala V", + "Select parts in the viewport or the scene first": "Pilih bagian di viewport atau scene terlebih dahulu", + "Silver": "Perak", + "Space": "Ruang", + "Specular colour": "Warna specular", + "Specular weight": "Bobot specular", + "Spherical": "Bola", + "Strength": "Kekuatan", + "Subsurface": "Subsurface", + "Subsurface colour": "Warna subsurface", + "Subsurface radius": "Radius subsurface", + "Subsurface radius scale": "Skala radius subsurface", + "Texture": "Tekstur", + "Texture {key}": "Tekstur {key}", + "Texture ×": "Tekstur ×", + "Textures": "Tekstur", + "The engine does not know the type {id}; showing the main values.": "Mesin tidak mengenal tipe {id}; menampilkan nilai utama.", + "The engine lists no material types yet": "Mesin belum mencantumkan tipe material", + "The image could not be uploaded ({status})": "Gambar tidak dapat diunggah ({status})", + "The texture multiplies this value": "Tekstur mengalikan nilai ini", + "Thin film": "Film tipis", + "Thin glass": "Kaca tipis", + "Thin walled": "Berdinding tipis", + "Titanium": "Titanium", + "Transmission": "Transmisi", + "Transmission colour": "Warna transmisi", + "Transmission depth": "Kedalaman transmisi", + "Trilinear": "Trilinear", + "Type": "Tipe", + "UV set": "Set UV", + "Used by 1 part": "Digunakan oleh 1 bagian", + "Used by {n} parts": "Digunakan oleh {n} bagian", + "Waiting for the material settings": "Menunggu pengaturan material", + "Waiting for the material types": "Menunggu tipe material", + "World space": "Ruang dunia", + "Wrap": "Bungkus", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} tidak dapat dihapus. {reason}", + "{name} copy": "Salinan {name}" +} diff --git a/frontend/src/i18n/modules/material/it.json b/frontend/src/i18n/modules/material/it.json new file mode 100644 index 00000000..aa8e29dc --- /dev/null +++ b/frontend/src/i18n/modules/material/it.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Un grafo di 1 nodo", + "A graph of {n} nodes": "Un grafo di {n} nodi", + "A texture drives this value; the value is its fallback": "Una texture controlla questo valore; il valore è la sua riserva", + "ACEScg": "ACEScg", + "Abbe number": "Numero di Abbe", + "Add a map": "Aggiungi una mappa", + "All parameters": "Tutti i parametri", + "Alpha": "Alpha", + "Aluminium": "Alluminio", + "Anisotropy": "Anisotropia", + "Assign to selection": "Assegna alla selezione", + "Base weight": "Peso di base", + "Bilinear": "Bilineare", + "Blend": "Sfumatura", + "Blue": "Blu", + "Box": "Box", + "Brushed metal": "Metallo spazzolato", + "Bump": "Bump", + "Category": "Categoria", + "Change the material type": "Cambia il tipo di materiale", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Cambiare {from} in {to}. Mantenere i valori attuali o reimpostarli sul nuovo tipo?", + "Channel": "Canale", + "Choose a texture image": "Scegli un'immagine di texture", + "Choose an input": "Scegli un ingresso", + "Chromium": "Cromo", + "Clamp": "Estendi", + "Clear plastic": "Plastica trasparente", + "Clear the texture slot": "Svuota lo slot della texture", + "Coat": "Vernice", + "Coat IOR": "IOR della vernice", + "Coat colour": "Colore della vernice", + "Coat darkening": "Scurimento della vernice", + "Coat roughness": "Rugosità della vernice", + "Cobalt": "Cobalto", + "Colour space": "Spazio colore", + "Copper": "Rame", + "Custom colour": "Colore personalizzato", + "Cylindrical": "Cilindrica", + "Data (raw)": "Dati (grezzi)", + "Delete material": "Elimina materiale", + "Diffuse": "Diffuso", + "Diffuse roughness": "Rugosità diffusa", + "Dispersion": "Dispersione", + "Displacement": "Displacement", + "Drive {input} with a texture": "Controlla {input} con una texture", + "Driven by the graph. Edit the graph to change it.": "Controllato dal grafo. Modifica il grafo per cambiarlo.", + "Drives no input yet": "Non controlla ancora nessun ingresso", + "Drives {inputs}": "Controlla {inputs}", + "Duplicate material": "Duplica materiale", + "Edit graph": "Modifica grafo", + "Edit the texture of {input}": "Modifica la texture di {input}", + "Emission colour": "Colore di emissione", + "Fallback": "Valore di riserva", + "Fallback colour": "Colore di riserva", + "Film IOR": "IOR del film", + "Film thickness": "Spessore del film", + "Filter": "Filtro", + "Flip green (DirectX)": "Inverti il verde (DirectX)", + "Fuzz": "Peluria", + "Fuzz colour": "Colore della peluria", + "Fuzz roughness": "Rugosità della peluria", + "Generic": "Generico", + "Gold": "Oro", + "Graph": "Grafo", + "Green": "Verde", + "IOR": "IOR", + "Images": "Immagini", + "In use by 1 part. Assign another material to it first.": "Usato da 1 parte. Assegnale prima un altro materiale.", + "In use by {n} parts. Assign another material to them first.": "Usato da {n} parti. Assegna loro prima un altro materiale.", + "Invert": "Inverti", + "Iron": "Ferro", + "Keep this material as a preset in your library": "Conserva questo materiale come preset nella tua libreria", + "Keep values": "Mantieni i valori", + "Labels": "Etichette", + "Linear sRGB": "sRGB lineare", + "Luminance": "Luminanza", + "Material types": "Tipi di materiale", + "Measured metals": "Metalli misurati", + "Metallic paint": "Vernice metallizzata", + "Mirror": "Specchio", + "Multiply by the value": "Moltiplica per il valore", + "Name": "Nome", + "Nearest": "Più vicino", + "New": "Nuovo", + "New material": "Nuovo materiale", + "Nickel": "Nichel", + "No graph": "Nessun grafo", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Nessun grafo. Questo tipo ha l'aspetto corretto solo con il suo grafo; reimposta sul tipo per riaverlo.", + "No materials yet. Create one from a type with New.": "Ancora nessun materiale. Creane uno da un tipo con Nuovo.", + "No textures. Use the texture button beside a value, or add a map here.": "Nessuna texture. Usa il pulsante texture accanto a un valore oppure aggiungi qui una mappa.", + "Object space": "Spazio oggetto", + "Offset U": "Spostamento U", + "Offset V": "Spostamento V", + "Open the node editor for this material": "Apri l'editor di nodi per questo materiale", + "Parameters": "Parametri", + "Pick a material first": "Scegli prima un materiale", + "Pick or create a material to edit it.": "Scegli o crea un materiale per modificarlo.", + "Planar": "Planare", + "Platinum": "Platino", + "Projection": "Proiezione", + "RGB": "RGB", + "Range from": "Intervallo da", + "Range to": "Intervallo a", + "Reading the material": "Lettura del materiale", + "Red": "Rosso", + "Rename material": "Rinomina materiale", + "Repeat": "Ripeti", + "Replace the image": "Sostituisci l'immagine", + "Reset to type": "Reimposta sul tipo", + "Save to library": "Salva nella libreria", + "Saved {name} to your library": "{name} salvato nella tua libreria", + "Saving to the library needs an engine with library.save.": "Per salvare nella libreria serve un motore con library.save.", + "Scale U": "Scala U", + "Scale V": "Scala V", + "Select parts in the viewport or the scene first": "Seleziona prima delle parti nel viewport o nella scena", + "Silver": "Argento", + "Space": "Spazio", + "Specular colour": "Colore speculare", + "Specular weight": "Peso speculare", + "Spherical": "Sferica", + "Strength": "Intensità", + "Subsurface": "Sottosuperficie", + "Subsurface colour": "Colore della sottosuperficie", + "Subsurface radius": "Raggio della sottosuperficie", + "Subsurface radius scale": "Scala del raggio della sottosuperficie", + "Texture": "Texture", + "Texture {key}": "Texture {key}", + "Texture ×": "Texture ×", + "Textures": "Texture", + "The engine does not know the type {id}; showing the main values.": "Il motore non conosce il tipo {id}; vengono mostrati i valori principali.", + "The engine lists no material types yet": "Il motore non elenca ancora alcun tipo di materiale", + "The image could not be uploaded ({status})": "Impossibile caricare l'immagine ({status})", + "The texture multiplies this value": "La texture moltiplica questo valore", + "Thin film": "Film sottile", + "Thin glass": "Vetro sottile", + "Thin walled": "Parete sottile", + "Titanium": "Titanio", + "Transmission": "Trasmissione", + "Transmission colour": "Colore di trasmissione", + "Transmission depth": "Profondità di trasmissione", + "Trilinear": "Trilineare", + "Type": "Tipo", + "UV set": "Set UV", + "Used by 1 part": "Usato da 1 parte", + "Used by {n} parts": "Usato da {n} parti", + "Waiting for the material settings": "In attesa delle impostazioni del materiale", + "Waiting for the material types": "In attesa dei tipi di materiale", + "World space": "Spazio mondo", + "Wrap": "Modalità di ripetizione", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} non può essere eliminato. {reason}", + "{name} copy": "{name} copia" +} diff --git a/frontend/src/i18n/modules/material/ja.json b/frontend/src/i18n/modules/material/ja.json new file mode 100644 index 00000000..87691932 --- /dev/null +++ b/frontend/src/i18n/modules/material/ja.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "1 ノードのグラフ", + "A graph of {n} nodes": "{n} ノードのグラフ", + "A texture drives this value; the value is its fallback": "テクスチャがこの値を制御します。この値はフォールバックです", + "ACEScg": "ACEScg", + "Abbe number": "アッベ数", + "Add a map": "マップを追加", + "All parameters": "すべてのパラメータ", + "Alpha": "アルファ", + "Aluminium": "アルミニウム", + "Anisotropy": "異方性", + "Assign to selection": "選択に割り当て", + "Base weight": "ベースウェイト", + "Bilinear": "バイリニア", + "Blend": "ブレンド", + "Blue": "青", + "Box": "ボックス", + "Brushed metal": "ブラッシュドメタル", + "Bump": "バンプ", + "Category": "カテゴリ", + "Change the material type": "マテリアルタイプを変更", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "{from} を {to} に変更します。現在の値を保持しますか、それとも新しいタイプの値にリセットしますか?", + "Channel": "チャンネル", + "Choose a texture image": "テクスチャ画像を選択", + "Choose an input": "入力を選択", + "Chromium": "クロム", + "Clamp": "クランプ", + "Clear plastic": "透明プラスチック", + "Clear the texture slot": "テクスチャスロットをクリア", + "Coat": "コート", + "Coat IOR": "コート IOR", + "Coat colour": "コートカラー", + "Coat darkening": "コートの暗化", + "Coat roughness": "コートラフネス", + "Cobalt": "コバルト", + "Colour space": "カラースペース", + "Copper": "銅", + "Custom colour": "カスタムカラー", + "Cylindrical": "円筒", + "Data (raw)": "データ (ロー)", + "Delete material": "マテリアルを削除", + "Diffuse": "ディフューズ", + "Diffuse roughness": "ディフューズラフネス", + "Dispersion": "分散", + "Displacement": "ディスプレイスメント", + "Drive {input} with a texture": "{input} をテクスチャで制御", + "Driven by the graph. Edit the graph to change it.": "グラフで制御されています。変更するにはグラフを編集してください。", + "Drives no input yet": "まだ入力を制御していません", + "Drives {inputs}": "{inputs} を制御", + "Duplicate material": "マテリアルを複製", + "Edit graph": "グラフを編集", + "Edit the texture of {input}": "{input} のテクスチャを編集", + "Emission colour": "エミッションカラー", + "Fallback": "フォールバック", + "Fallback colour": "フォールバックカラー", + "Film IOR": "薄膜 IOR", + "Film thickness": "薄膜の厚さ", + "Filter": "フィルタ", + "Flip green (DirectX)": "グリーンを反転 (DirectX)", + "Fuzz": "ファズ", + "Fuzz colour": "ファズカラー", + "Fuzz roughness": "ファズラフネス", + "Generic": "汎用", + "Gold": "金", + "Graph": "グラフ", + "Green": "緑", + "IOR": "IOR", + "Images": "画像", + "In use by 1 part. Assign another material to it first.": "1 個のパーツで使用中です。先に別のマテリアルを割り当ててください。", + "In use by {n} parts. Assign another material to them first.": "{n} 個のパーツで使用中です。先に別のマテリアルを割り当ててください。", + "Invert": "反転", + "Iron": "鉄", + "Keep this material as a preset in your library": "このマテリアルをプリセットとしてライブラリに保存", + "Keep values": "値を保持", + "Labels": "ラベル", + "Linear sRGB": "リニア sRGB", + "Luminance": "輝度", + "Material types": "マテリアルタイプ", + "Measured metals": "実測の金属", + "Metallic paint": "メタリックペイント", + "Mirror": "ミラー", + "Multiply by the value": "値を乗算", + "Name": "名前", + "Nearest": "ニアレスト", + "New": "新規", + "New material": "新規マテリアル", + "Nickel": "ニッケル", + "No graph": "グラフなし", + "No graph. This type looks right only with its graph; reset to type to get it back.": "グラフがありません。このタイプはグラフがある場合のみ正しく表示されます。タイプにリセットすると元に戻ります。", + "No materials yet. Create one from a type with New.": "マテリアルがまだありません。「新規」でタイプを選んで作成してください。", + "No textures. Use the texture button beside a value, or add a map here.": "テクスチャがありません。値の横のテクスチャボタンを使うか、ここでマップを追加してください。", + "Object space": "オブジェクト空間", + "Offset U": "オフセット U", + "Offset V": "オフセット V", + "Open the node editor for this material": "このマテリアルのノードエディタを開く", + "Parameters": "パラメータ", + "Pick a material first": "先にマテリアルを選択してください", + "Pick or create a material to edit it.": "編集するマテリアルを選択または作成してください。", + "Planar": "平面", + "Platinum": "プラチナ", + "Projection": "投影", + "RGB": "RGB", + "Range from": "範囲の開始", + "Range to": "範囲の終了", + "Reading the material": "マテリアルを読み取り中", + "Red": "赤", + "Rename material": "マテリアル名を変更", + "Repeat": "リピート", + "Replace the image": "画像を置き換え", + "Reset to type": "タイプにリセット", + "Save to library": "ライブラリに保存", + "Saved {name} to your library": "{name} をライブラリに保存しました", + "Saving to the library needs an engine with library.save.": "ライブラリへの保存には、library.save に対応したエンジンが必要です。", + "Scale U": "スケール U", + "Scale V": "スケール V", + "Select parts in the viewport or the scene first": "先にビューポートまたはシーンでパーツを選択してください", + "Silver": "銀", + "Space": "空間", + "Specular colour": "スペキュラカラー", + "Specular weight": "スペキュラウェイト", + "Spherical": "球面", + "Strength": "強さ", + "Subsurface": "サブサーフェス", + "Subsurface colour": "サブサーフェスカラー", + "Subsurface radius": "サブサーフェス半径", + "Subsurface radius scale": "サブサーフェス半径スケール", + "Texture": "テクスチャ", + "Texture {key}": "テクスチャ {key}", + "Texture ×": "テクスチャ ×", + "Textures": "テクスチャ", + "The engine does not know the type {id}; showing the main values.": "エンジンはタイプ {id} を認識しません。主要な値を表示しています。", + "The engine lists no material types yet": "エンジンがマテリアルタイプをまだ一覧していません", + "The image could not be uploaded ({status})": "画像をアップロードできませんでした ({status})", + "The texture multiplies this value": "テクスチャがこの値に乗算されます", + "Thin film": "薄膜", + "Thin glass": "薄いガラス", + "Thin walled": "薄肉", + "Titanium": "チタン", + "Transmission": "トランスミッション", + "Transmission colour": "トランスミッションカラー", + "Transmission depth": "トランスミッション深度", + "Trilinear": "トライリニア", + "Type": "タイプ", + "UV set": "UV セット", + "Used by 1 part": "1 個のパーツで使用", + "Used by {n} parts": "{n} 個のパーツで使用", + "Waiting for the material settings": "マテリアル設定を待機中", + "Waiting for the material types": "マテリアルタイプを待機中", + "World space": "ワールド空間", + "Wrap": "ラップ", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} は削除できません。{reason}", + "{name} copy": "{name} のコピー" +} diff --git a/frontend/src/i18n/modules/material/ko.json b/frontend/src/i18n/modules/material/ko.json new file mode 100644 index 00000000..95993cda --- /dev/null +++ b/frontend/src/i18n/modules/material/ko.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "노드 1개짜리 그래프", + "A graph of {n} nodes": "노드 {n}개짜리 그래프", + "A texture drives this value; the value is its fallback": "텍스처가 이 값을 제어합니다. 이 값은 대체값입니다", + "ACEScg": "ACEScg", + "Abbe number": "아베 수", + "Add a map": "맵 추가", + "All parameters": "모든 파라미터", + "Alpha": "알파", + "Aluminium": "알루미늄", + "Anisotropy": "이방성", + "Assign to selection": "선택 항목에 할당", + "Base weight": "기본 가중치", + "Bilinear": "바이리니어", + "Blend": "블렌드", + "Blue": "파랑", + "Box": "박스", + "Brushed metal": "브러시드 메탈", + "Bump": "범프", + "Category": "카테고리", + "Change the material type": "머티리얼 유형 변경", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "{from}을(를) {to}(으)로 변경합니다. 현재 값을 유지할까요, 새 유형의 값으로 재설정할까요?", + "Channel": "채널", + "Choose a texture image": "텍스처 이미지 선택", + "Choose an input": "입력 선택", + "Chromium": "크롬", + "Clamp": "클램프", + "Clear plastic": "투명 플라스틱", + "Clear the texture slot": "텍스처 슬롯 비우기", + "Coat": "코트", + "Coat IOR": "코트 IOR", + "Coat colour": "코트 색상", + "Coat darkening": "코트 어두워짐", + "Coat roughness": "코트 러프니스", + "Cobalt": "코발트", + "Colour space": "색 공간", + "Copper": "구리", + "Custom colour": "사용자 지정 색상", + "Cylindrical": "원통형", + "Data (raw)": "데이터(원본)", + "Delete material": "머티리얼 삭제", + "Diffuse": "디퓨즈", + "Diffuse roughness": "디퓨즈 러프니스", + "Dispersion": "분산", + "Displacement": "디스플레이스먼트", + "Drive {input} with a texture": "{input}을(를) 텍스처로 제어", + "Driven by the graph. Edit the graph to change it.": "그래프로 제어됩니다. 바꾸려면 그래프를 편집하세요.", + "Drives no input yet": "아직 제어하는 입력이 없음", + "Drives {inputs}": "{inputs} 제어", + "Duplicate material": "머티리얼 복제", + "Edit graph": "그래프 편집", + "Edit the texture of {input}": "{input}의 텍스처 편집", + "Emission colour": "발광 색상", + "Fallback": "대체값", + "Fallback colour": "대체 색상", + "Film IOR": "필름 IOR", + "Film thickness": "필름 두께", + "Filter": "필터", + "Flip green (DirectX)": "그린 반전(DirectX)", + "Fuzz": "퍼즈", + "Fuzz colour": "퍼즈 색상", + "Fuzz roughness": "퍼즈 러프니스", + "Generic": "일반", + "Gold": "금", + "Graph": "그래프", + "Green": "초록", + "IOR": "IOR", + "Images": "이미지", + "In use by 1 part. Assign another material to it first.": "파트 1개에서 사용 중입니다. 먼저 다른 머티리얼을 할당하세요.", + "In use by {n} parts. Assign another material to them first.": "파트 {n}개에서 사용 중입니다. 먼저 다른 머티리얼을 할당하세요.", + "Invert": "반전", + "Iron": "철", + "Keep this material as a preset in your library": "이 머티리얼을 프리셋으로 라이브러리에 보관", + "Keep values": "값 유지", + "Labels": "레이블", + "Linear sRGB": "리니어 sRGB", + "Luminance": "휘도", + "Material types": "머티리얼 유형", + "Measured metals": "실측 금속", + "Metallic paint": "메탈릭 페인트", + "Mirror": "거울", + "Multiply by the value": "값에 곱하기", + "Name": "이름", + "Nearest": "최근접", + "New": "새로 만들기", + "New material": "새 머티리얼", + "Nickel": "니켈", + "No graph": "그래프 없음", + "No graph. This type looks right only with its graph; reset to type to get it back.": "그래프가 없습니다. 이 유형은 그래프가 있어야 올바르게 보입니다. 유형으로 재설정하면 되돌아옵니다.", + "No materials yet. Create one from a type with New.": "아직 머티리얼이 없습니다. 새로 만들기에서 유형을 골라 만드세요.", + "No textures. Use the texture button beside a value, or add a map here.": "텍스처가 없습니다. 값 옆의 텍스처 버튼을 사용하거나 여기서 맵을 추가하세요.", + "Object space": "오브젝트 공간", + "Offset U": "오프셋 U", + "Offset V": "오프셋 V", + "Open the node editor for this material": "이 머티리얼의 노드 편집기 열기", + "Parameters": "파라미터", + "Pick a material first": "먼저 머티리얼을 선택하세요", + "Pick or create a material to edit it.": "편집할 머티리얼을 선택하거나 만드세요.", + "Planar": "평면", + "Platinum": "백금", + "Projection": "투영", + "RGB": "RGB", + "Range from": "범위 시작", + "Range to": "범위 끝", + "Reading the material": "머티리얼 읽는 중", + "Red": "빨강", + "Rename material": "머티리얼 이름 바꾸기", + "Repeat": "반복", + "Replace the image": "이미지 교체", + "Reset to type": "유형으로 재설정", + "Save to library": "라이브러리에 저장", + "Saved {name} to your library": "{name}을(를) 라이브러리에 저장했습니다", + "Saving to the library needs an engine with library.save.": "라이브러리에 저장하려면 library.save를 지원하는 엔진이 필요합니다.", + "Scale U": "스케일 U", + "Scale V": "스케일 V", + "Select parts in the viewport or the scene first": "먼저 뷰포트나 장면에서 파트를 선택하세요", + "Silver": "은", + "Space": "공간", + "Specular colour": "스페큘러 색상", + "Specular weight": "스페큘러 가중치", + "Spherical": "구형", + "Strength": "강도", + "Subsurface": "서브서피스", + "Subsurface colour": "서브서피스 색상", + "Subsurface radius": "서브서피스 반경", + "Subsurface radius scale": "서브서피스 반경 배율", + "Texture": "텍스처", + "Texture {key}": "텍스처 {key}", + "Texture ×": "텍스처 ×", + "Textures": "텍스처", + "The engine does not know the type {id}; showing the main values.": "엔진이 {id} 유형을 알지 못합니다. 주요 값을 표시합니다.", + "The engine lists no material types yet": "엔진에 아직 머티리얼 유형이 없습니다", + "The image could not be uploaded ({status})": "이미지를 업로드하지 못했습니다 ({status})", + "The texture multiplies this value": "텍스처가 이 값에 곱해집니다", + "Thin film": "박막", + "Thin glass": "얇은 유리", + "Thin walled": "얇은 벽", + "Titanium": "티타늄", + "Transmission": "트랜스미션", + "Transmission colour": "트랜스미션 색상", + "Transmission depth": "트랜스미션 깊이", + "Trilinear": "트라이리니어", + "Type": "유형", + "UV set": "UV 세트", + "Used by 1 part": "파트 1개에서 사용", + "Used by {n} parts": "파트 {n}개에서 사용", + "Waiting for the material settings": "머티리얼 설정을 기다리는 중", + "Waiting for the material types": "머티리얼 유형을 기다리는 중", + "World space": "월드 공간", + "Wrap": "래핑", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name}을(를) 삭제할 수 없습니다. {reason}", + "{name} copy": "{name} 복사본" +} diff --git a/frontend/src/i18n/modules/material/nb.json b/frontend/src/i18n/modules/material/nb.json new file mode 100644 index 00000000..6c1692e1 --- /dev/null +++ b/frontend/src/i18n/modules/material/nb.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "En graf med 1 node", + "A graph of {n} nodes": "En graf med {n} noder", + "A texture drives this value; the value is its fallback": "En tekstur styrer denne verdien; verdien er reserveverdien", + "ACEScg": "ACEScg", + "Abbe number": "Abbetall", + "Add a map": "Legg til en map", + "All parameters": "Alle parametere", + "Alpha": "Alfa", + "Aluminium": "Aluminium", + "Anisotropy": "Anisotropi", + "Assign to selection": "Tilordne markering", + "Base weight": "Basisvekt", + "Bilinear": "Bilineær", + "Blend": "Blanding", + "Blue": "Blå", + "Box": "Boks", + "Brushed metal": "Børstet metall", + "Bump": "Bump", + "Category": "Kategori", + "Change the material type": "Endre materialtypen", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Endre {from} til {to}. Vil du beholde de gjeldende verdiene eller tilbakestille dem til den nye typen?", + "Channel": "Kanal", + "Choose a texture image": "Velg et teksturbilde", + "Choose an input": "Velg en inngang", + "Chromium": "Krom", + "Clamp": "Begrens", + "Clear plastic": "Klar plast", + "Clear the texture slot": "Tøm tekstursporet", + "Coat": "Coating", + "Coat IOR": "Coating-IOR", + "Coat colour": "Coatingfarge", + "Coat darkening": "Coating-mørkning", + "Coat roughness": "Coatingruhet", + "Cobalt": "Kobolt", + "Colour space": "Fargerom", + "Copper": "Kobber", + "Custom colour": "Egendefinert farge", + "Cylindrical": "Sylindrisk", + "Data (raw)": "Data (rå)", + "Delete material": "Slett materiale", + "Diffuse": "Diffus", + "Diffuse roughness": "Diffus ruhet", + "Dispersion": "Dispersjon", + "Displacement": "Displacement", + "Drive {input} with a texture": "Styr {input} med en tekstur", + "Driven by the graph. Edit the graph to change it.": "Styres av grafen. Rediger grafen for å endre det.", + "Drives no input yet": "Styrer ingen inngang ennå", + "Drives {inputs}": "Styrer {inputs}", + "Duplicate material": "Dupliser materiale", + "Edit graph": "Rediger graf", + "Edit the texture of {input}": "Rediger teksturen for {input}", + "Emission colour": "Emisjonsfarge", + "Fallback": "Reserveverdi", + "Fallback colour": "Reservefarge", + "Film IOR": "Film-IOR", + "Film thickness": "Filmtykkelse", + "Filter": "Filter", + "Flip green (DirectX)": "Snu grønn (DirectX)", + "Fuzz": "Fuzz", + "Fuzz colour": "Fuzz-farge", + "Fuzz roughness": "Fuzz-ruhet", + "Generic": "Generelt", + "Gold": "Gull", + "Graph": "Graf", + "Green": "Grønn", + "IOR": "IOR", + "Images": "Bilder", + "In use by 1 part. Assign another material to it first.": "Brukes av 1 del. Tilordne et annet materiale til den først.", + "In use by {n} parts. Assign another material to them first.": "Brukes av {n} deler. Tilordne et annet materiale til dem først.", + "Invert": "Inverter", + "Iron": "Jern", + "Keep this material as a preset in your library": "Behold dette materialet som en forhåndsinnstilling i biblioteket ditt", + "Keep values": "Behold verdier", + "Labels": "Etiketter", + "Linear sRGB": "Lineær sRGB", + "Luminance": "Luminans", + "Material types": "Materialtyper", + "Measured metals": "Målte metaller", + "Metallic paint": "Metallic lakk", + "Mirror": "Speil", + "Multiply by the value": "Multipliser med verdien", + "Name": "Navn", + "Nearest": "Nærmeste", + "New": "Ny", + "New material": "Nytt materiale", + "Nickel": "Nikkel", + "No graph": "Ingen graf", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Ingen graf. Denne typen ser bare riktig ut med grafen sin; tilbakestill til typen for å få den tilbake.", + "No materials yet. Create one from a type with New.": "Ingen materialer ennå. Lag et fra en type med Ny.", + "No textures. Use the texture button beside a value, or add a map here.": "Ingen teksturer. Bruk teksturknappen ved siden av en verdi, eller legg til en map her.", + "Object space": "Objektrom", + "Offset U": "Forskyvning U", + "Offset V": "Forskyvning V", + "Open the node editor for this material": "Åpne nodeeditoren for dette materialet", + "Parameters": "Parametere", + "Pick a material first": "Velg et materiale først", + "Pick or create a material to edit it.": "Velg eller lag et materiale for å redigere det.", + "Planar": "Plan", + "Platinum": "Platina", + "Projection": "Projeksjon", + "RGB": "RGB", + "Range from": "Område fra", + "Range to": "Område til", + "Reading the material": "Leser materialet", + "Red": "Rød", + "Rename material": "Gi materialet nytt navn", + "Repeat": "Gjenta", + "Replace the image": "Erstatt bildet", + "Reset to type": "Tilbakestill til type", + "Save to library": "Lagre i biblioteket", + "Saved {name} to your library": "{name} er lagret i biblioteket ditt", + "Saving to the library needs an engine with library.save.": "Lagring i biblioteket krever en motor med library.save.", + "Scale U": "Skala U", + "Scale V": "Skala V", + "Select parts in the viewport or the scene first": "Velg først deler i visningsvinduet eller scenen", + "Silver": "Sølv", + "Space": "Rom", + "Specular colour": "Spekulær farge", + "Specular weight": "Spekulær vekt", + "Spherical": "Sfærisk", + "Strength": "Styrke", + "Subsurface": "Subsurface", + "Subsurface colour": "Subsurface-farge", + "Subsurface radius": "Subsurface-radius", + "Subsurface radius scale": "Skala for subsurface-radius", + "Texture": "Tekstur", + "Texture {key}": "Tekstur {key}", + "Texture ×": "Tekstur ×", + "Textures": "Teksturer", + "The engine does not know the type {id}; showing the main values.": "Motoren kjenner ikke typen {id}; viser de viktigste verdiene.", + "The engine lists no material types yet": "Motoren lister ingen materialtyper ennå", + "The image could not be uploaded ({status})": "Bildet kunne ikke lastes opp ({status})", + "The texture multiplies this value": "Teksturen multipliseres med denne verdien", + "Thin film": "Tynn film", + "Thin glass": "Tynt glass", + "Thin walled": "Tynnvegget", + "Titanium": "Titan", + "Transmission": "Transmisjon", + "Transmission colour": "Transmisjonsfarge", + "Transmission depth": "Transmisjonsdybde", + "Trilinear": "Trilineær", + "Type": "Type", + "UV set": "UV-sett", + "Used by 1 part": "Brukt av 1 del", + "Used by {n} parts": "Brukt av {n} deler", + "Waiting for the material settings": "Venter på materialinnstillingene", + "Waiting for the material types": "Venter på materialtypene", + "World space": "Verdensrom", + "Wrap": "Wrap", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} kan ikke slettes. {reason}", + "{name} copy": "{name} kopi" +} diff --git a/frontend/src/i18n/modules/material/nl.json b/frontend/src/i18n/modules/material/nl.json new file mode 100644 index 00000000..727caf1b --- /dev/null +++ b/frontend/src/i18n/modules/material/nl.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Een graaf van 1 node", + "A graph of {n} nodes": "Een graaf van {n} nodes", + "A texture drives this value; the value is its fallback": "Een tekstuur stuurt deze waarde aan; de waarde is de terugvalwaarde", + "ACEScg": "ACEScg", + "Abbe number": "Abbegetal", + "Add a map": "Een map toevoegen", + "All parameters": "Alle parameters", + "Alpha": "Alpha", + "Aluminium": "Aluminium", + "Anisotropy": "Anisotropie", + "Assign to selection": "Aan selectie toewijzen", + "Base weight": "Basisgewicht", + "Bilinear": "Bilineair", + "Blend": "Overvloeiing", + "Blue": "Blauw", + "Box": "Box", + "Brushed metal": "Geborsteld metaal", + "Bump": "Bump", + "Category": "Categorie", + "Change the material type": "Het materiaaltype wijzigen", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "{from} wijzigen in {to}. De huidige waarden behouden, of terugzetten naar het nieuwe type?", + "Channel": "Kanaal", + "Choose a texture image": "Een tekstuurafbeelding kiezen", + "Choose an input": "Een invoer kiezen", + "Chromium": "Chroom", + "Clamp": "Begrenzen", + "Clear plastic": "Doorzichtig kunststof", + "Clear the texture slot": "De tekstuurslot leegmaken", + "Coat": "Coating", + "Coat IOR": "Coating-IOR", + "Coat colour": "Coatingkleur", + "Coat darkening": "Coating-verdonkering", + "Coat roughness": "Coatingruwheid", + "Cobalt": "Kobalt", + "Colour space": "Kleurruimte", + "Copper": "Koper", + "Custom colour": "Aangepaste kleur", + "Cylindrical": "Cilindrisch", + "Data (raw)": "Data (ruw)", + "Delete material": "Materiaal verwijderen", + "Diffuse": "Diffuus", + "Diffuse roughness": "Diffuse ruwheid", + "Dispersion": "Dispersie", + "Displacement": "Displacement", + "Drive {input} with a texture": "{input} aansturen met een tekstuur", + "Driven by the graph. Edit the graph to change it.": "Wordt aangestuurd door de graaf. Bewerk de graaf om dit te wijzigen.", + "Drives no input yet": "Stuurt nog geen invoer aan", + "Drives {inputs}": "Stuurt {inputs} aan", + "Duplicate material": "Materiaal dupliceren", + "Edit graph": "Graaf bewerken", + "Edit the texture of {input}": "De tekstuur van {input} bewerken", + "Emission colour": "Emissiekleur", + "Fallback": "Terugvalwaarde", + "Fallback colour": "Terugvalkleur", + "Film IOR": "Film-IOR", + "Film thickness": "Filmdikte", + "Filter": "Filter", + "Flip green (DirectX)": "Groen omkeren (DirectX)", + "Fuzz": "Fuzz", + "Fuzz colour": "Fuzz-kleur", + "Fuzz roughness": "Fuzz-ruwheid", + "Generic": "Algemeen", + "Gold": "Goud", + "Graph": "Graaf", + "Green": "Groen", + "IOR": "IOR", + "Images": "Afbeeldingen", + "In use by 1 part. Assign another material to it first.": "In gebruik door 1 onderdeel. Wijs er eerst een ander materiaal aan toe.", + "In use by {n} parts. Assign another material to them first.": "In gebruik door {n} onderdelen. Wijs er eerst een ander materiaal aan toe.", + "Invert": "Omkeren", + "Iron": "IJzer", + "Keep this material as a preset in your library": "Dit materiaal als voorinstelling in je bibliotheek bewaren", + "Keep values": "Waarden behouden", + "Labels": "Labels", + "Linear sRGB": "Lineaire sRGB", + "Luminance": "Luminantie", + "Material types": "Materiaaltypen", + "Measured metals": "Gemeten metalen", + "Metallic paint": "Metallic verf", + "Mirror": "Spiegelen", + "Multiply by the value": "Vermenigvuldigen met de waarde", + "Name": "Naam", + "Nearest": "Dichtstbijzijnde", + "New": "Nieuw", + "New material": "Nieuw materiaal", + "Nickel": "Nikkel", + "No graph": "Geen graaf", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Geen graaf. Dit type ziet er alleen goed uit met zijn graaf; zet het terug naar het type om de graaf te herstellen.", + "No materials yet. Create one from a type with New.": "Nog geen materialen. Maak er een van een type met Nieuw.", + "No textures. Use the texture button beside a value, or add a map here.": "Geen teksturen. Gebruik de tekstuurknop naast een waarde, of voeg hier een map toe.", + "Object space": "Objectruimte", + "Offset U": "Verschuiving U", + "Offset V": "Verschuiving V", + "Open the node editor for this material": "De node-editor voor dit materiaal openen", + "Parameters": "Parameters", + "Pick a material first": "Kies eerst een materiaal", + "Pick or create a material to edit it.": "Kies of maak een materiaal om het te bewerken.", + "Planar": "Vlak", + "Platinum": "Platina", + "Projection": "Projectie", + "RGB": "RGB", + "Range from": "Bereik van", + "Range to": "Bereik tot", + "Reading the material": "Het materiaal lezen", + "Red": "Rood", + "Rename material": "Materiaal hernoemen", + "Repeat": "Herhalen", + "Replace the image": "De afbeelding vervangen", + "Reset to type": "Terugzetten naar type", + "Save to library": "Opslaan in bibliotheek", + "Saved {name} to your library": "{name} is opgeslagen in je bibliotheek", + "Saving to the library needs an engine with library.save.": "Opslaan in de bibliotheek vereist een engine met library.save.", + "Scale U": "Schaal U", + "Scale V": "Schaal V", + "Select parts in the viewport or the scene first": "Selecteer eerst onderdelen in de viewport of de scène", + "Silver": "Zilver", + "Space": "Ruimte", + "Specular colour": "Speculaire kleur", + "Specular weight": "Speculair gewicht", + "Spherical": "Sferisch", + "Strength": "Sterkte", + "Subsurface": "Subsurface", + "Subsurface colour": "Subsurface-kleur", + "Subsurface radius": "Subsurface-radius", + "Subsurface radius scale": "Schaal van subsurface-radius", + "Texture": "Tekstuur", + "Texture {key}": "Tekstuur {key}", + "Texture ×": "Tekstuur ×", + "Textures": "Teksturen", + "The engine does not know the type {id}; showing the main values.": "De engine kent het type {id} niet; de belangrijkste waarden worden getoond.", + "The engine lists no material types yet": "De engine toont nog geen materiaaltypen", + "The image could not be uploaded ({status})": "De afbeelding kon niet worden geüpload ({status})", + "The texture multiplies this value": "De tekstuur vermenigvuldigt deze waarde", + "Thin film": "Dunne film", + "Thin glass": "Dun glas", + "Thin walled": "Dunwandig", + "Titanium": "Titanium", + "Transmission": "Transmissie", + "Transmission colour": "Transmissiekleur", + "Transmission depth": "Transmissiediepte", + "Trilinear": "Trilineair", + "Type": "Type", + "UV set": "UV-set", + "Used by 1 part": "Gebruikt door 1 onderdeel", + "Used by {n} parts": "Gebruikt door {n} onderdelen", + "Waiting for the material settings": "Wachten op de materiaalinstellingen", + "Waiting for the material types": "Wachten op de materiaaltypen", + "World space": "Wereldruimte", + "Wrap": "Wrap", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} kan niet worden verwijderd. {reason}", + "{name} copy": "{name} kopie" +} diff --git a/frontend/src/i18n/modules/material/pl.json b/frontend/src/i18n/modules/material/pl.json new file mode 100644 index 00000000..afba8ca7 --- /dev/null +++ b/frontend/src/i18n/modules/material/pl.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Graf: 1 węzeł", + "A graph of {n} nodes": "Graf, węzły: {n}", + "A texture drives this value; the value is its fallback": "Ta wartość jest sterowana teksturą; wartość służy jako zastępcza", + "ACEScg": "ACEScg", + "Abbe number": "Liczba Abbego", + "Add a map": "Dodaj mapę", + "All parameters": "Wszystkie parametry", + "Alpha": "Alfa", + "Aluminium": "Aluminium", + "Anisotropy": "Anizotropia", + "Assign to selection": "Przypisz do zaznaczenia", + "Base weight": "Waga bazowa", + "Bilinear": "Dwuliniowe", + "Blend": "Mieszanie", + "Blue": "Niebieski", + "Box": "Skrzynkowa", + "Brushed metal": "Szczotkowany metal", + "Bump": "Bump", + "Category": "Kategoria", + "Change the material type": "Zmień typ materiału", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Zmień {from} na {to}. Zachować bieżące wartości czy zresetować je do wartości nowego typu?", + "Channel": "Kanał", + "Choose a texture image": "Wybierz obraz tekstury", + "Choose an input": "Wybierz wejście", + "Chromium": "Chrom", + "Clamp": "Przycięcie", + "Clear plastic": "Przezroczyste tworzywo", + "Clear the texture slot": "Wyczyść slot tekstury", + "Coat": "Powłoka", + "Coat IOR": "IOR powłoki", + "Coat colour": "Kolor powłoki", + "Coat darkening": "Ciemnienie powłoki", + "Coat roughness": "Chropowatość powłoki", + "Cobalt": "Kobalt", + "Colour space": "Przestrzeń barw", + "Copper": "Miedź", + "Custom colour": "Kolor własny", + "Cylindrical": "Cylindryczna", + "Data (raw)": "Dane (surowe)", + "Delete material": "Usuń materiał", + "Diffuse": "Rozproszenie", + "Diffuse roughness": "Chropowatość rozproszenia", + "Dispersion": "Dyspersja", + "Displacement": "Przemieszczenie", + "Drive {input} with a texture": "Steruj wejściem {input} za pomocą tekstury", + "Driven by the graph. Edit the graph to change it.": "Sterowane przez graf. Aby to zmienić, edytuj graf.", + "Drives no input yet": "Nie steruje jeszcze żadnym wejściem", + "Drives {inputs}": "Steruje: {inputs}", + "Duplicate material": "Duplikuj materiał", + "Edit graph": "Edytuj graf", + "Edit the texture of {input}": "Edytuj teksturę wejścia {input}", + "Emission colour": "Kolor emisji", + "Fallback": "Wartość zastępcza", + "Fallback colour": "Kolor zastępczy", + "Film IOR": "IOR warstwy", + "Film thickness": "Grubość warstwy", + "Filter": "Filtrowanie", + "Flip green (DirectX)": "Odwróć zielony (DirectX)", + "Fuzz": "Meszek", + "Fuzz colour": "Kolor meszku", + "Fuzz roughness": "Chropowatość meszku", + "Generic": "Ogólny", + "Gold": "Złoto", + "Graph": "Graf", + "Green": "Zielony", + "IOR": "IOR", + "Images": "Obrazy", + "In use by 1 part. Assign another material to it first.": "Używany przez 1 część. Najpierw przypisz jej inny materiał.", + "In use by {n} parts. Assign another material to them first.": "Używany przez części: {n}. Najpierw przypisz im inny materiał.", + "Invert": "Odwróć", + "Iron": "Żelazo", + "Keep this material as a preset in your library": "Zachowaj ten materiał jako preset w swojej bibliotece", + "Keep values": "Zachowaj wartości", + "Labels": "Etykiety", + "Linear sRGB": "Liniowa sRGB", + "Luminance": "Luminancja", + "Material types": "Typy materiałów", + "Measured metals": "Metale z pomiarów", + "Metallic paint": "Lakier metaliczny", + "Mirror": "Odbicie lustrzane", + "Multiply by the value": "Pomnóż przez wartość", + "Name": "Nazwa", + "Nearest": "Najbliższy", + "New": "Nowy", + "New material": "Nowy materiał", + "Nickel": "Nikiel", + "No graph": "Brak grafu", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Brak grafu. Ten typ wygląda poprawnie tylko z własnym grafem; przywróć domyślne typu, aby go odzyskać.", + "No materials yet. Create one from a type with New.": "Nie ma jeszcze materiałów. Utwórz jeden z typu przyciskiem Nowy.", + "No textures. Use the texture button beside a value, or add a map here.": "Brak tekstur. Użyj przycisku tekstury obok wartości albo dodaj tutaj mapę.", + "Object space": "Przestrzeń obiektu", + "Offset U": "Przesunięcie U", + "Offset V": "Przesunięcie V", + "Open the node editor for this material": "Otwórz edytor węzłów dla tego materiału", + "Parameters": "Parametry", + "Pick a material first": "Najpierw wybierz materiał", + "Pick or create a material to edit it.": "Wybierz lub utwórz materiał, aby go edytować.", + "Planar": "Płaska", + "Platinum": "Platyna", + "Projection": "Projekcja", + "RGB": "RGB", + "Range from": "Zakres od", + "Range to": "Zakres do", + "Reading the material": "Odczytywanie materiału", + "Red": "Czerwony", + "Rename material": "Zmień nazwę materiału", + "Repeat": "Powtarzanie", + "Replace the image": "Zastąp obraz", + "Reset to type": "Przywróć domyślne typu", + "Save to library": "Zapisz w bibliotece", + "Saved {name} to your library": "Zapisano {name} w bibliotece", + "Saving to the library needs an engine with library.save.": "Zapis w bibliotece wymaga silnika z poleceniem library.save.", + "Scale U": "Skala U", + "Scale V": "Skala V", + "Select parts in the viewport or the scene first": "Najpierw zaznacz części w widoku 3D lub w scenie", + "Silver": "Srebro", + "Space": "Przestrzeń", + "Specular colour": "Kolor połysku", + "Specular weight": "Waga połysku", + "Spherical": "Sferyczna", + "Strength": "Siła", + "Subsurface": "Rozpraszanie podpowierzchniowe", + "Subsurface colour": "Kolor rozpraszania", + "Subsurface radius": "Promień rozpraszania", + "Subsurface radius scale": "Skala promienia rozpraszania", + "Texture": "Tekstura", + "Texture {key}": "Tekstura {key}", + "Texture ×": "Tekstura ×", + "Textures": "Tekstury", + "The engine does not know the type {id}; showing the main values.": "Silnik nie zna typu {id}; pokazuję główne wartości.", + "The engine lists no material types yet": "Silnik nie podaje jeszcze typów materiałów", + "The image could not be uploaded ({status})": "Nie udało się przesłać obrazu ({status})", + "The texture multiplies this value": "Tekstura mnoży tę wartość", + "Thin film": "Cienka warstwa", + "Thin glass": "Cienkie szkło", + "Thin walled": "Cienkościenny", + "Titanium": "Tytan", + "Transmission": "Transmisja", + "Transmission colour": "Kolor transmisji", + "Transmission depth": "Głębokość transmisji", + "Trilinear": "Trójliniowe", + "Type": "Typ", + "UV set": "Zestaw UV", + "Used by 1 part": "Używany przez 1 część", + "Used by {n} parts": "Używany przez części: {n}", + "Waiting for the material settings": "Oczekiwanie na ustawienia materiału", + "Waiting for the material types": "Oczekiwanie na typy materiałów", + "World space": "Przestrzeń świata", + "Wrap": "Zawijanie", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "Nie można usunąć {name}. {reason}", + "{name} copy": "{name} kopia" +} diff --git a/frontend/src/i18n/modules/material/pt-BR.json b/frontend/src/i18n/modules/material/pt-BR.json new file mode 100644 index 00000000..8629a4af --- /dev/null +++ b/frontend/src/i18n/modules/material/pt-BR.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Um grafo de 1 nó", + "A graph of {n} nodes": "Um grafo de {n} nós", + "A texture drives this value; the value is its fallback": "Uma textura controla este valor; o valor é o reserva", + "ACEScg": "ACEScg", + "Abbe number": "Número de Abbe", + "Add a map": "Adicionar um mapa", + "All parameters": "Todos os parâmetros", + "Alpha": "Alfa", + "Aluminium": "Alumínio", + "Anisotropy": "Anisotropia", + "Assign to selection": "Atribuir à seleção", + "Base weight": "Peso base", + "Bilinear": "Bilinear", + "Blend": "Mistura", + "Blue": "Azul", + "Box": "Caixa", + "Brushed metal": "Metal escovado", + "Bump": "Bump", + "Category": "Categoria", + "Change the material type": "Alterar o tipo de material", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Alterar {from} para {to}. Manter os valores atuais ou redefini-los para o novo tipo?", + "Channel": "Canal", + "Choose a texture image": "Escolha uma imagem de textura", + "Choose an input": "Escolha uma entrada", + "Chromium": "Cromo", + "Clamp": "Limitar", + "Clear plastic": "Plástico transparente", + "Clear the texture slot": "Limpar o slot de textura", + "Coat": "Verniz", + "Coat IOR": "IOR do verniz", + "Coat colour": "Cor do verniz", + "Coat darkening": "Escurecimento do verniz", + "Coat roughness": "Rugosidade do verniz", + "Cobalt": "Cobalto", + "Colour space": "Espaço de cor", + "Copper": "Cobre", + "Custom colour": "Cor personalizada", + "Cylindrical": "Cilíndrica", + "Data (raw)": "Dados (brutos)", + "Delete material": "Excluir material", + "Diffuse": "Difuso", + "Diffuse roughness": "Rugosidade difusa", + "Dispersion": "Dispersão", + "Displacement": "Deslocamento", + "Drive {input} with a texture": "Controlar {input} com uma textura", + "Driven by the graph. Edit the graph to change it.": "Controlado pelo grafo. Edite o grafo para alterá-lo.", + "Drives no input yet": "Ainda não controla nenhuma entrada", + "Drives {inputs}": "Controla {inputs}", + "Duplicate material": "Duplicar material", + "Edit graph": "Editar grafo", + "Edit the texture of {input}": "Editar a textura de {input}", + "Emission colour": "Cor de emissão", + "Fallback": "Reserva", + "Fallback colour": "Cor de reserva", + "Film IOR": "IOR da película", + "Film thickness": "Espessura da película", + "Filter": "Filtro", + "Flip green (DirectX)": "Inverter o verde (DirectX)", + "Fuzz": "Felpa", + "Fuzz colour": "Cor da felpa", + "Fuzz roughness": "Rugosidade da felpa", + "Generic": "Genérico", + "Gold": "Ouro", + "Graph": "Grafo", + "Green": "Verde", + "IOR": "IOR", + "Images": "Imagens", + "In use by 1 part. Assign another material to it first.": "Em uso por 1 peça. Atribua outro material a ela primeiro.", + "In use by {n} parts. Assign another material to them first.": "Em uso por {n} peças. Atribua outro material a elas primeiro.", + "Invert": "Inverter", + "Iron": "Ferro", + "Keep this material as a preset in your library": "Manter este material como predefinição na sua biblioteca", + "Keep values": "Manter valores", + "Labels": "Rótulos", + "Linear sRGB": "sRGB linear", + "Luminance": "Luminância", + "Material types": "Tipos de material", + "Measured metals": "Metais medidos", + "Metallic paint": "Tinta metálica", + "Mirror": "Espelho", + "Multiply by the value": "Multiplicar pelo valor", + "Name": "Nome", + "Nearest": "Mais próximo", + "New": "Novo", + "New material": "Novo material", + "Nickel": "Níquel", + "No graph": "Sem grafo", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Sem grafo. Este tipo só fica correto com o grafo dele; redefina para o tipo para recuperá-lo.", + "No materials yet. Create one from a type with New.": "Ainda não há materiais. Crie um a partir de um tipo com Novo.", + "No textures. Use the texture button beside a value, or add a map here.": "Nenhuma textura. Use o botão de textura ao lado de um valor ou adicione um mapa aqui.", + "Object space": "Espaço do objeto", + "Offset U": "Deslocamento U", + "Offset V": "Deslocamento V", + "Open the node editor for this material": "Abrir o editor de nós deste material", + "Parameters": "Parâmetros", + "Pick a material first": "Escolha um material primeiro", + "Pick or create a material to edit it.": "Escolha ou crie um material para editá-lo.", + "Planar": "Plana", + "Platinum": "Platina", + "Projection": "Projeção", + "RGB": "RGB", + "Range from": "Intervalo de", + "Range to": "Intervalo até", + "Reading the material": "Lendo o material", + "Red": "Vermelho", + "Rename material": "Renomear material", + "Repeat": "Repetir", + "Replace the image": "Substituir a imagem", + "Reset to type": "Redefinir para o tipo", + "Save to library": "Salvar na biblioteca", + "Saved {name} to your library": "{name} salvo na sua biblioteca", + "Saving to the library needs an engine with library.save.": "Salvar na biblioteca exige um motor com library.save.", + "Scale U": "Escala U", + "Scale V": "Escala V", + "Select parts in the viewport or the scene first": "Selecione peças no viewport ou na cena primeiro", + "Silver": "Prata", + "Space": "Espaço", + "Specular colour": "Cor do especular", + "Specular weight": "Peso do especular", + "Spherical": "Esférica", + "Strength": "Intensidade", + "Subsurface": "Subsuperfície", + "Subsurface colour": "Cor da subsuperfície", + "Subsurface radius": "Raio da subsuperfície", + "Subsurface radius scale": "Escala do raio da subsuperfície", + "Texture": "Textura", + "Texture {key}": "Textura {key}", + "Texture ×": "Textura ×", + "Textures": "Texturas", + "The engine does not know the type {id}; showing the main values.": "O motor não conhece o tipo {id}; mostrando os valores principais.", + "The engine lists no material types yet": "O motor ainda não lista tipos de material", + "The image could not be uploaded ({status})": "Não foi possível enviar a imagem ({status})", + "The texture multiplies this value": "A textura multiplica este valor", + "Thin film": "Película fina", + "Thin glass": "Vidro fino", + "Thin walled": "Parede fina", + "Titanium": "Titânio", + "Transmission": "Transmissão", + "Transmission colour": "Cor de transmissão", + "Transmission depth": "Profundidade de transmissão", + "Trilinear": "Trilinear", + "Type": "Tipo", + "UV set": "Conjunto UV", + "Used by 1 part": "Usado por 1 peça", + "Used by {n} parts": "Usado por {n} peças", + "Waiting for the material settings": "Aguardando as configurações do material", + "Waiting for the material types": "Aguardando os tipos de material", + "World space": "Espaço do mundo", + "Wrap": "Envolvimento", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "Não é possível excluir {name}. {reason}", + "{name} copy": "Cópia de {name}" +} diff --git a/frontend/src/i18n/modules/material/ru.json b/frontend/src/i18n/modules/material/ru.json new file mode 100644 index 00000000..84724d29 --- /dev/null +++ b/frontend/src/i18n/modules/material/ru.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Граф из 1 узла", + "A graph of {n} nodes": "Граф из узлов: {n}", + "A texture drives this value; the value is its fallback": "Это значение задаёт текстура; значение служит запасным", + "ACEScg": "ACEScg", + "Abbe number": "Число Аббе", + "Add a map": "Добавить карту", + "All parameters": "Все параметры", + "Alpha": "Альфа", + "Aluminium": "Алюминий", + "Anisotropy": "Анизотропия", + "Assign to selection": "Назначить выделенному", + "Base weight": "Базовый вес", + "Bilinear": "Билинейная", + "Blend": "Смешивание", + "Blue": "Синий", + "Box": "Куб", + "Brushed metal": "Шлифованный металл", + "Bump": "Бамп", + "Category": "Категория", + "Change the material type": "Сменить тип материала", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Сменить {from} на {to}. Сохранить текущие значения или сбросить их до нового типа?", + "Channel": "Канал", + "Choose a texture image": "Выберите изображение текстуры", + "Choose an input": "Выберите вход", + "Chromium": "Хром", + "Clamp": "Ограничение", + "Clear plastic": "Прозрачный пластик", + "Clear the texture slot": "Очистить слот текстуры", + "Coat": "Покрытие", + "Coat IOR": "IOR покрытия", + "Coat colour": "Цвет покрытия", + "Coat darkening": "Затемнение покрытия", + "Coat roughness": "Шероховатость покрытия", + "Cobalt": "Кобальт", + "Colour space": "Цветовое пространство", + "Copper": "Медь", + "Custom colour": "Свой цвет", + "Cylindrical": "Цилиндрическая", + "Data (raw)": "Данные (без обработки)", + "Delete material": "Удалить материал", + "Diffuse": "Диффузный", + "Diffuse roughness": "Диффузная шероховатость", + "Dispersion": "Дисперсия", + "Displacement": "Смещение", + "Drive {input} with a texture": "Задать {input} текстурой", + "Driven by the graph. Edit the graph to change it.": "Задаётся графом. Измените граф, чтобы изменить значение.", + "Drives no input yet": "Пока ничего не задаёт", + "Drives {inputs}": "Задаёт: {inputs}", + "Duplicate material": "Дублировать материал", + "Edit graph": "Изменить граф", + "Edit the texture of {input}": "Изменить текстуру для {input}", + "Emission colour": "Цвет излучения", + "Fallback": "Запасное значение", + "Fallback colour": "Запасной цвет", + "Film IOR": "IOR плёнки", + "Film thickness": "Толщина плёнки", + "Filter": "Фильтр", + "Flip green (DirectX)": "Инвертировать зелёный (DirectX)", + "Fuzz": "Ворсистость", + "Fuzz colour": "Цвет ворса", + "Fuzz roughness": "Шероховатость ворса", + "Generic": "Универсальный", + "Gold": "Золото", + "Graph": "Граф", + "Green": "Зелёный", + "IOR": "IOR", + "Images": "Изображения", + "In use by 1 part. Assign another material to it first.": "Используется в 1 детали. Сначала назначьте ей другой материал.", + "In use by {n} parts. Assign another material to them first.": "Используется в деталях: {n}. Сначала назначьте им другой материал.", + "Invert": "Инвертировать", + "Iron": "Железо", + "Keep this material as a preset in your library": "Сохранить этот материал как пресет в вашей библиотеке", + "Keep values": "Оставить значения", + "Labels": "Подписи", + "Linear sRGB": "Линейное sRGB", + "Luminance": "Яркость", + "Material types": "Типы материалов", + "Measured metals": "Измеренные металлы", + "Metallic paint": "Металлик (краска)", + "Mirror": "Зеркало", + "Multiply by the value": "Умножить на значение", + "Name": "Название", + "Nearest": "Ближайший", + "New": "Создать", + "New material": "Новый материал", + "Nickel": "Никель", + "No graph": "Нет графа", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Графа нет. Этот тип выглядит правильно только с графом; сбросьте до типа, чтобы вернуть его.", + "No materials yet. Create one from a type with New.": "Материалов пока нет. Создайте материал из типа кнопкой «Создать».", + "No textures. Use the texture button beside a value, or add a map here.": "Текстур нет. Используйте кнопку текстуры рядом со значением или добавьте карту здесь.", + "Object space": "Пространство объекта", + "Offset U": "Смещение U", + "Offset V": "Смещение V", + "Open the node editor for this material": "Открыть редактор узлов для этого материала", + "Parameters": "Параметры", + "Pick a material first": "Сначала выберите материал", + "Pick or create a material to edit it.": "Выберите или создайте материал, чтобы его изменить.", + "Planar": "Плоская", + "Platinum": "Платина", + "Projection": "Проекция", + "RGB": "RGB", + "Range from": "Диапазон от", + "Range to": "Диапазон до", + "Reading the material": "Чтение материала", + "Red": "Красный", + "Rename material": "Переименовать материал", + "Repeat": "Повтор", + "Replace the image": "Заменить изображение", + "Reset to type": "Сбросить до типа", + "Save to library": "Сохранить в библиотеку", + "Saved {name} to your library": "{name} сохранён в вашу библиотеку", + "Saving to the library needs an engine with library.save.": "Для сохранения в библиотеку нужен движок с library.save.", + "Scale U": "Масштаб U", + "Scale V": "Масштаб V", + "Select parts in the viewport or the scene first": "Сначала выберите детали во вьюпорте или в сцене", + "Silver": "Серебро", + "Space": "Пространство", + "Specular colour": "Цвет бликов", + "Specular weight": "Вес бликов", + "Spherical": "Сферическая", + "Strength": "Сила", + "Subsurface": "Подповерхностное рассеивание", + "Subsurface colour": "Цвет подповерхностного рассеивания", + "Subsurface radius": "Радиус подповерхностного рассеивания", + "Subsurface radius scale": "Масштаб радиуса подповерхностного рассеивания", + "Texture": "Текстура", + "Texture {key}": "Текстура {key}", + "Texture ×": "Текстура ×", + "Textures": "Текстуры", + "The engine does not know the type {id}; showing the main values.": "Движок не знает тип {id}; показаны основные значения.", + "The engine lists no material types yet": "Движок пока не перечисляет типы материалов", + "The image could not be uploaded ({status})": "Не удалось загрузить изображение ({status})", + "The texture multiplies this value": "Текстура умножается на это значение", + "Thin film": "Тонкая плёнка", + "Thin glass": "Тонкое стекло", + "Thin walled": "Тонкостенный", + "Titanium": "Титан", + "Transmission": "Пропускание", + "Transmission colour": "Цвет пропускания", + "Transmission depth": "Глубина пропускания", + "Trilinear": "Трилинейная", + "Type": "Тип", + "UV set": "Набор UV", + "Used by 1 part": "Используется в 1 детали", + "Used by {n} parts": "Используется в деталях: {n}", + "Waiting for the material settings": "Ожидание настроек материала", + "Waiting for the material types": "Ожидание типов материалов", + "World space": "Мировое пространство", + "Wrap": "Обёртывание", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "Не удалось удалить {name}. {reason}", + "{name} copy": "{name} (копия)" +} diff --git a/frontend/src/i18n/modules/material/strings.json b/frontend/src/i18n/modules/material/strings.json new file mode 100644 index 00000000..c3fb7e18 --- /dev/null +++ b/frontend/src/i18n/modules/material/strings.json @@ -0,0 +1,154 @@ +[ + "A graph of 1 node", + "A graph of {n} nodes", + "A texture drives this value; the value is its fallback", + "ACEScg", + "Abbe number", + "Add a map", + "All parameters", + "Alpha", + "Aluminium", + "Anisotropy", + "Assign to selection", + "Base weight", + "Bilinear", + "Blend", + "Blue", + "Box", + "Brushed metal", + "Bump", + "Category", + "Change the material type", + "Change {from} to {to}. Keep the current values, or reset them to the new type?", + "Channel", + "Choose a texture image", + "Choose an input", + "Chromium", + "Clamp", + "Clear plastic", + "Clear the texture slot", + "Coat", + "Coat IOR", + "Coat colour", + "Coat darkening", + "Coat roughness", + "Cobalt", + "Colour space", + "Copper", + "Custom colour", + "Cylindrical", + "Data (raw)", + "Delete material", + "Diffuse", + "Diffuse roughness", + "Dispersion", + "Displacement", + "Drive {input} with a texture", + "Driven by the graph. Edit the graph to change it.", + "Drives no input yet", + "Drives {inputs}", + "Duplicate material", + "Edit graph", + "Edit the texture of {input}", + "Emission colour", + "Fallback", + "Fallback colour", + "Film IOR", + "Film thickness", + "Filter", + "Flip green (DirectX)", + "Fuzz", + "Fuzz colour", + "Fuzz roughness", + "Generic", + "Gold", + "Graph", + "Green", + "IOR", + "Images", + "In use by 1 part. Assign another material to it first.", + "In use by {n} parts. Assign another material to them first.", + "Invert", + "Iron", + "Keep this material as a preset in your library", + "Keep values", + "Labels", + "Linear sRGB", + "Luminance", + "Material types", + "Measured metals", + "Metallic paint", + "Mirror", + "Multiply by the value", + "Name", + "Nearest", + "New", + "New material", + "Nickel", + "No graph", + "No graph. This type looks right only with its graph; reset to type to get it back.", + "No materials yet. Create one from a type with New.", + "No textures. Use the texture button beside a value, or add a map here.", + "Object space", + "Offset U", + "Offset V", + "Open the node editor for this material", + "Parameters", + "Pick a material first", + "Pick or create a material to edit it.", + "Planar", + "Platinum", + "Projection", + "RGB", + "Range from", + "Range to", + "Reading the material", + "Red", + "Rename material", + "Repeat", + "Replace the image", + "Reset to type", + "Save to library", + "Saved {name} to your library", + "Saving to the library needs an engine with library.save.", + "Scale U", + "Scale V", + "Select parts in the viewport or the scene first", + "Silver", + "Space", + "Specular colour", + "Specular weight", + "Spherical", + "Strength", + "Subsurface", + "Subsurface colour", + "Subsurface radius", + "Subsurface radius scale", + "Texture", + "Texture {key}", + "Texture ×", + "Textures", + "The engine does not know the type {id}; showing the main values.", + "The engine lists no material types yet", + "The image could not be uploaded ({status})", + "The texture multiplies this value", + "Thin film", + "Thin glass", + "Thin walled", + "Titanium", + "Transmission", + "Transmission colour", + "Transmission depth", + "Trilinear", + "Type", + "UV set", + "Used by 1 part", + "Used by {n} parts", + "Waiting for the material settings", + "Waiting for the material types", + "World space", + "Wrap", + "sRGB", + "{name} cannot be deleted. {reason}", + "{name} copy" +] diff --git a/frontend/src/i18n/modules/material/sv.json b/frontend/src/i18n/modules/material/sv.json new file mode 100644 index 00000000..25220835 --- /dev/null +++ b/frontend/src/i18n/modules/material/sv.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "En graf med 1 nod", + "A graph of {n} nodes": "En graf med {n} noder", + "A texture drives this value; the value is its fallback": "En textur styr det här värdet; värdet är dess reservvärde", + "ACEScg": "ACEScg", + "Abbe number": "Abbetal", + "Add a map": "Lägg till en map", + "All parameters": "Alla parametrar", + "Alpha": "Alfa", + "Aluminium": "Aluminium", + "Anisotropy": "Anisotropi", + "Assign to selection": "Tilldela markering", + "Base weight": "Basvikt", + "Bilinear": "Bilinjär", + "Blend": "Blandning", + "Blue": "Blå", + "Box": "Box", + "Brushed metal": "Borstad metall", + "Bump": "Bump", + "Category": "Kategori", + "Change the material type": "Ändra materialtypen", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Ändra {from} till {to}. Behålla de nuvarande värdena eller återställa dem till den nya typen?", + "Channel": "Kanal", + "Choose a texture image": "Välj en texturbild", + "Choose an input": "Välj en ingång", + "Chromium": "Krom", + "Clamp": "Begränsa", + "Clear plastic": "Genomskinlig plast", + "Clear the texture slot": "Töm texturplatsen", + "Coat": "Coating", + "Coat IOR": "Coating-IOR", + "Coat colour": "Coatingfärg", + "Coat darkening": "Coating-mörkning", + "Coat roughness": "Coatingråhet", + "Cobalt": "Kobolt", + "Colour space": "Färgrymd", + "Copper": "Koppar", + "Custom colour": "Anpassad färg", + "Cylindrical": "Cylindrisk", + "Data (raw)": "Data (rå)", + "Delete material": "Radera material", + "Diffuse": "Diffus", + "Diffuse roughness": "Diffus råhet", + "Dispersion": "Dispersion", + "Displacement": "Displacement", + "Drive {input} with a texture": "Styr {input} med en textur", + "Driven by the graph. Edit the graph to change it.": "Styrs av grafen. Redigera grafen för att ändra det.", + "Drives no input yet": "Styr ingen ingång ännu", + "Drives {inputs}": "Styr {inputs}", + "Duplicate material": "Duplicera material", + "Edit graph": "Redigera graf", + "Edit the texture of {input}": "Redigera texturen för {input}", + "Emission colour": "Emissionsfärg", + "Fallback": "Reservvärde", + "Fallback colour": "Reservfärg", + "Film IOR": "Film-IOR", + "Film thickness": "Filmtjocklek", + "Filter": "Filter", + "Flip green (DirectX)": "Vänd grönt (DirectX)", + "Fuzz": "Fuzz", + "Fuzz colour": "Fuzz-färg", + "Fuzz roughness": "Fuzz-råhet", + "Generic": "Allmänt", + "Gold": "Guld", + "Graph": "Graf", + "Green": "Grön", + "IOR": "IOR", + "Images": "Bilder", + "In use by 1 part. Assign another material to it first.": "Används av 1 del. Tilldela den ett annat material först.", + "In use by {n} parts. Assign another material to them first.": "Används av {n} delar. Tilldela dem ett annat material först.", + "Invert": "Invertera", + "Iron": "Järn", + "Keep this material as a preset in your library": "Behåll det här materialet som en förinställning i ditt bibliotek", + "Keep values": "Behåll värden", + "Labels": "Etiketter", + "Linear sRGB": "Linjär sRGB", + "Luminance": "Luminans", + "Material types": "Materialtyper", + "Measured metals": "Uppmätta metaller", + "Metallic paint": "Metallic lack", + "Mirror": "Spegla", + "Multiply by the value": "Multiplicera med värdet", + "Name": "Namn", + "Nearest": "Närmaste", + "New": "Ny", + "New material": "Nytt material", + "Nickel": "Nickel", + "No graph": "Ingen graf", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Ingen graf. Den här typen ser rätt ut bara med sin graf; återställ till typen för att få tillbaka den.", + "No materials yet. Create one from a type with New.": "Inga material ännu. Skapa ett från en typ med Ny.", + "No textures. Use the texture button beside a value, or add a map here.": "Inga texturer. Använd texturknappen bredvid ett värde, eller lägg till en map här.", + "Object space": "Objektrymd", + "Offset U": "Förskjutning U", + "Offset V": "Förskjutning V", + "Open the node editor for this material": "Öppna nodredigeraren för det här materialet", + "Parameters": "Parametrar", + "Pick a material first": "Välj ett material först", + "Pick or create a material to edit it.": "Välj eller skapa ett material för att redigera det.", + "Planar": "Plan", + "Platinum": "Platina", + "Projection": "Projektion", + "RGB": "RGB", + "Range from": "Intervall från", + "Range to": "Intervall till", + "Reading the material": "Läser materialet", + "Red": "Röd", + "Rename material": "Byt namn på material", + "Repeat": "Upprepa", + "Replace the image": "Ersätt bilden", + "Reset to type": "Återställ till typ", + "Save to library": "Spara i biblioteket", + "Saved {name} to your library": "{name} har sparats i ditt bibliotek", + "Saving to the library needs an engine with library.save.": "Att spara i biblioteket kräver en motor med library.save.", + "Scale U": "Skala U", + "Scale V": "Skala V", + "Select parts in the viewport or the scene first": "Markera först delar i vyn eller scenen", + "Silver": "Silver", + "Space": "Rymd", + "Specular colour": "Spekulär färg", + "Specular weight": "Spekulär vikt", + "Spherical": "Sfärisk", + "Strength": "Styrka", + "Subsurface": "Subsurface", + "Subsurface colour": "Subsurface-färg", + "Subsurface radius": "Subsurface-radie", + "Subsurface radius scale": "Skala för subsurface-radie", + "Texture": "Textur", + "Texture {key}": "Textur {key}", + "Texture ×": "Textur ×", + "Textures": "Texturer", + "The engine does not know the type {id}; showing the main values.": "Motorn känner inte till typen {id}; visar de viktigaste värdena.", + "The engine lists no material types yet": "Motorn listar inga materialtyper ännu", + "The image could not be uploaded ({status})": "Bilden kunde inte laddas upp ({status})", + "The texture multiplies this value": "Texturen multiplicerar det här värdet", + "Thin film": "Tunn film", + "Thin glass": "Tunt glas", + "Thin walled": "Tunnväggig", + "Titanium": "Titan", + "Transmission": "Transmission", + "Transmission colour": "Transmissionsfärg", + "Transmission depth": "Transmissionsdjup", + "Trilinear": "Trilinjär", + "Type": "Typ", + "UV set": "UV-uppsättning", + "Used by 1 part": "Används av 1 del", + "Used by {n} parts": "Används av {n} delar", + "Waiting for the material settings": "Väntar på materialinställningarna", + "Waiting for the material types": "Väntar på materialtyperna", + "World space": "Världsrymd", + "Wrap": "Wrap", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} kan inte raderas. {reason}", + "{name} copy": "{name} kopia" +} diff --git a/frontend/src/i18n/modules/material/th.json b/frontend/src/i18n/modules/material/th.json new file mode 100644 index 00000000..c5e5bbba --- /dev/null +++ b/frontend/src/i18n/modules/material/th.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "กราฟ 1 โหนด", + "A graph of {n} nodes": "กราฟ {n} โหนด", + "A texture drives this value; the value is its fallback": "เท็กซ์เจอร์ควบคุมค่านี้ ส่วนค่านี้เป็นค่าสำรอง", + "ACEScg": "ACEScg", + "Abbe number": "ค่า Abbe", + "Add a map": "เพิ่มแมป", + "All parameters": "พารามิเตอร์ทั้งหมด", + "Alpha": "แอลฟา", + "Aluminium": "อะลูมิเนียม", + "Anisotropy": "แอนไอโซทรอปี", + "Assign to selection": "กำหนดให้ที่เลือก", + "Base weight": "น้ำหนักฐาน", + "Bilinear": "ไบลิเนียร์", + "Blend": "ผสม", + "Blue": "น้ำเงิน", + "Box": "กล่อง", + "Brushed metal": "โลหะขัดเป็นเส้น", + "Bump": "บัมพ์", + "Category": "หมวดหมู่", + "Change the material type": "เปลี่ยนชนิดแมทีเรียล", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "เปลี่ยน {from} เป็น {to} คงค่าปัจจุบันไว้ หรือรีเซ็ตเป็นค่าของชนิดใหม่?", + "Channel": "แชนเนล", + "Choose a texture image": "เลือกภาพเท็กซ์เจอร์", + "Choose an input": "เลือกอินพุต", + "Chromium": "โครเมียม", + "Clamp": "จำกัดขอบ", + "Clear plastic": "พลาสติกใส", + "Clear the texture slot": "ล้างช่องเท็กซ์เจอร์", + "Coat": "เคลือบ", + "Coat IOR": "IOR ของชั้นเคลือบ", + "Coat colour": "สีชั้นเคลือบ", + "Coat darkening": "ความมืดของชั้นเคลือบ", + "Coat roughness": "ความหยาบของชั้นเคลือบ", + "Cobalt": "โคบอลต์", + "Colour space": "ปริภูมิสี", + "Copper": "ทองแดง", + "Custom colour": "สีกำหนดเอง", + "Cylindrical": "ทรงกระบอก", + "Data (raw)": "ข้อมูล (ดิบ)", + "Delete material": "ลบแมทีเรียล", + "Diffuse": "ดิฟฟิวส์", + "Diffuse roughness": "ความหยาบดิฟฟิวส์", + "Dispersion": "การกระจายแสง", + "Displacement": "ดิสเพลซเมนต์", + "Drive {input} with a texture": "ควบคุม {input} ด้วยเท็กซ์เจอร์", + "Driven by the graph. Edit the graph to change it.": "ควบคุมโดยกราฟ แก้ไขกราฟเพื่อเปลี่ยนค่า", + "Drives no input yet": "ยังไม่ควบคุมอินพุตใด", + "Drives {inputs}": "ควบคุม {inputs}", + "Duplicate material": "ทำซ้ำแมทีเรียล", + "Edit graph": "แก้ไขกราฟ", + "Edit the texture of {input}": "แก้ไขเท็กซ์เจอร์ของ {input}", + "Emission colour": "สีการเปล่งแสง", + "Fallback": "ค่าสำรอง", + "Fallback colour": "สีสำรอง", + "Film IOR": "IOR ของฟิล์ม", + "Film thickness": "ความหนาของฟิล์ม", + "Filter": "ตัวกรอง", + "Flip green (DirectX)": "กลับด้านสีเขียว (DirectX)", + "Fuzz": "ขน", + "Fuzz colour": "สีขน", + "Fuzz roughness": "ความหยาบของขน", + "Generic": "ทั่วไป", + "Gold": "ทอง", + "Graph": "กราฟ", + "Green": "เขียว", + "IOR": "IOR", + "Images": "รูปภาพ", + "In use by 1 part. Assign another material to it first.": "ใช้งานโดย 1 ชิ้นส่วน กำหนดแมทีเรียลอื่นให้ชิ้นส่วนนั้นก่อน", + "In use by {n} parts. Assign another material to them first.": "ใช้งานโดย {n} ชิ้นส่วน กำหนดแมทีเรียลอื่นให้ชิ้นส่วนเหล่านั้นก่อน", + "Invert": "กลับค่า", + "Iron": "เหล็ก", + "Keep this material as a preset in your library": "เก็บแมทีเรียลนี้เป็นพรีเซ็ตในคลังของคุณ", + "Keep values": "คงค่าไว้", + "Labels": "ป้ายกำกับ", + "Linear sRGB": "Linear sRGB", + "Luminance": "ความสว่าง", + "Material types": "ชนิดแมทีเรียล", + "Measured metals": "โลหะที่วัดจริง", + "Metallic paint": "สีโลหะ", + "Mirror": "กระจกเงา", + "Multiply by the value": "คูณด้วยค่า", + "Name": "ชื่อ", + "Nearest": "ใกล้ที่สุด", + "New": "ใหม่", + "New material": "แมทีเรียลใหม่", + "Nickel": "นิกเกิล", + "No graph": "ไม่มีกราฟ", + "No graph. This type looks right only with its graph; reset to type to get it back.": "ไม่มีกราฟ ชนิดนี้ดูถูกต้องเมื่อมีกราฟเท่านั้น รีเซ็ตเป็นชนิดเพื่อนำกลับมา", + "No materials yet. Create one from a type with New.": "ยังไม่มีแมทีเรียล สร้างจากชนิดด้วยปุ่มใหม่", + "No textures. Use the texture button beside a value, or add a map here.": "ไม่มีเท็กซ์เจอร์ ใช้ปุ่มเท็กซ์เจอร์ข้างค่า หรือเพิ่มแมปที่นี่", + "Object space": "ปริภูมิวัตถุ", + "Offset U": "ออฟเซ็ต U", + "Offset V": "ออฟเซ็ต V", + "Open the node editor for this material": "เปิดตัวแก้ไขโหนดของแมทีเรียลนี้", + "Parameters": "พารามิเตอร์", + "Pick a material first": "เลือกแมทีเรียลก่อน", + "Pick or create a material to edit it.": "เลือกหรือสร้างแมทีเรียลเพื่อแก้ไข", + "Planar": "ระนาบ", + "Platinum": "แพลทินัม", + "Projection": "การโปรเจกต์", + "RGB": "RGB", + "Range from": "ช่วงจาก", + "Range to": "ช่วงถึง", + "Reading the material": "กำลังอ่านแมทีเรียล", + "Red": "แดง", + "Rename material": "เปลี่ยนชื่อแมทีเรียล", + "Repeat": "ทำซ้ำ", + "Replace the image": "แทนที่ภาพ", + "Reset to type": "รีเซ็ตเป็นชนิด", + "Save to library": "บันทึกลงคลัง", + "Saved {name} to your library": "บันทึก {name} ลงคลังของคุณแล้ว", + "Saving to the library needs an engine with library.save.": "การบันทึกลงคลังต้องใช้เอนจินที่มี library.save", + "Scale U": "สเกล U", + "Scale V": "สเกล V", + "Select parts in the viewport or the scene first": "เลือกชิ้นส่วนในวิวพอร์ตหรือซีนก่อน", + "Silver": "เงิน", + "Space": "ปริภูมิ", + "Specular colour": "สีสเปกคูลาร์", + "Specular weight": "น้ำหนักสเปกคูลาร์", + "Spherical": "ทรงกลม", + "Strength": "ความเข้ม", + "Subsurface": "ซับเซอร์เฟซ", + "Subsurface colour": "สีซับเซอร์เฟซ", + "Subsurface radius": "รัศมีซับเซอร์เฟซ", + "Subsurface radius scale": "สเกลรัศมีซับเซอร์เฟซ", + "Texture": "เท็กซ์เจอร์", + "Texture {key}": "เท็กซ์เจอร์ {key}", + "Texture ×": "เท็กซ์เจอร์ ×", + "Textures": "เท็กซ์เจอร์", + "The engine does not know the type {id}; showing the main values.": "เอนจินไม่รู้จักชนิด {id} จึงแสดงค่าหลัก", + "The engine lists no material types yet": "เอนจินยังไม่มีรายการชนิดแมทีเรียล", + "The image could not be uploaded ({status})": "อัปโหลดภาพไม่ได้ ({status})", + "The texture multiplies this value": "เท็กซ์เจอร์คูณกับค่านี้", + "Thin film": "ฟิล์มบาง", + "Thin glass": "กระจกบาง", + "Thin walled": "ผนังบาง", + "Titanium": "ไทเทเนียม", + "Transmission": "การส่องผ่าน", + "Transmission colour": "สีการส่องผ่าน", + "Transmission depth": "ความลึกการส่องผ่าน", + "Trilinear": "ไตรลิเนียร์", + "Type": "ชนิด", + "UV set": "ชุด UV", + "Used by 1 part": "ใช้โดย 1 ชิ้นส่วน", + "Used by {n} parts": "ใช้โดย {n} ชิ้นส่วน", + "Waiting for the material settings": "กำลังรอการตั้งค่าแมทีเรียล", + "Waiting for the material types": "กำลังรอชนิดแมทีเรียล", + "World space": "ปริภูมิโลก", + "Wrap": "การห่อ", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "ลบ {name} ไม่ได้ {reason}", + "{name} copy": "สำเนา {name}" +} diff --git a/frontend/src/i18n/modules/material/tr.json b/frontend/src/i18n/modules/material/tr.json new file mode 100644 index 00000000..19345169 --- /dev/null +++ b/frontend/src/i18n/modules/material/tr.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "1 düğümlü bir grafik", + "A graph of {n} nodes": "{n} düğümlü bir grafik", + "A texture drives this value; the value is its fallback": "Bu değeri bir doku belirler; değer yedek olarak kalır", + "ACEScg": "ACEScg", + "Abbe number": "Abbe sayısı", + "Add a map": "Harita ekle", + "All parameters": "Tüm parametreler", + "Alpha": "Alfa", + "Aluminium": "Alüminyum", + "Anisotropy": "Anizotropi", + "Assign to selection": "Seçime ata", + "Base weight": "Temel ağırlık", + "Bilinear": "Bilinear", + "Blend": "Karıştırma", + "Blue": "Mavi", + "Box": "Kutu", + "Brushed metal": "Fırçalanmış metal", + "Bump": "Bump", + "Category": "Kategori", + "Change the material type": "Malzeme türünü değiştir", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "{from} türü {to} olarak değiştirilsin. Mevcut değerler korunsun mu, yoksa yeni türe sıfırlansın mı?", + "Channel": "Kanal", + "Choose a texture image": "Bir doku görüntüsü seçin", + "Choose an input": "Bir girdi seçin", + "Chromium": "Krom", + "Clamp": "Sınırla", + "Clear plastic": "Şeffaf plastik", + "Clear the texture slot": "Doku yuvasını temizle", + "Coat": "Kaplama", + "Coat IOR": "Kaplama IOR'u", + "Coat colour": "Kaplama rengi", + "Coat darkening": "Kaplama koyulaşması", + "Coat roughness": "Kaplama pürüzlülüğü", + "Cobalt": "Kobalt", + "Colour space": "Renk uzayı", + "Copper": "Bakır", + "Custom colour": "Özel renk", + "Cylindrical": "Silindirik", + "Data (raw)": "Veri (ham)", + "Delete material": "Malzemeyi sil", + "Diffuse": "Yaygın yansıma", + "Diffuse roughness": "Yaygın pürüzlülük", + "Dispersion": "Dispersiyon", + "Displacement": "Yer değiştirme", + "Drive {input} with a texture": "{input} değerini bir dokuyla yönlendir", + "Driven by the graph. Edit the graph to change it.": "Grafik tarafından yönlendiriliyor. Değiştirmek için grafiği düzenleyin.", + "Drives no input yet": "Henüz hiçbir girdiyi yönlendirmiyor", + "Drives {inputs}": "{inputs} girdilerini yönlendirir", + "Duplicate material": "Malzemeyi çoğalt", + "Edit graph": "Grafiği düzenle", + "Edit the texture of {input}": "{input} dokusunu düzenle", + "Emission colour": "Emisyon rengi", + "Fallback": "Yedek", + "Fallback colour": "Yedek renk", + "Film IOR": "Film IOR'u", + "Film thickness": "Film kalınlığı", + "Filter": "Filtre", + "Flip green (DirectX)": "Yeşili çevir (DirectX)", + "Fuzz": "Tüylülük", + "Fuzz colour": "Tüy rengi", + "Fuzz roughness": "Tüy pürüzlülüğü", + "Generic": "Genel", + "Gold": "Altın", + "Graph": "Grafik", + "Green": "Yeşil", + "IOR": "IOR", + "Images": "Görüntüler", + "In use by 1 part. Assign another material to it first.": "1 parça tarafından kullanılıyor. Önce ona başka bir malzeme atayın.", + "In use by {n} parts. Assign another material to them first.": "{n} parça tarafından kullanılıyor. Önce onlara başka bir malzeme atayın.", + "Invert": "Ters çevir", + "Iron": "Demir", + "Keep this material as a preset in your library": "Bu malzemeyi kitaplığınızda hazır ayar olarak sakla", + "Keep values": "Değerleri koru", + "Labels": "Etiketler", + "Linear sRGB": "Doğrusal sRGB", + "Luminance": "Parlaklık", + "Material types": "Malzeme türleri", + "Measured metals": "Ölçülmüş metaller", + "Metallic paint": "Metalik boya", + "Mirror": "Ayna", + "Multiply by the value": "Değerle çarp", + "Name": "Ad", + "Nearest": "En yakın", + "New": "Yeni", + "New material": "Yeni malzeme", + "Nickel": "Nikel", + "No graph": "Grafik yok", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Grafik yok. Bu tür yalnızca grafiğiyle doğru görünür; geri getirmek için türe sıfırlayın.", + "No materials yet. Create one from a type with New.": "Henüz malzeme yok. Yeni ile bir türden malzeme oluşturun.", + "No textures. Use the texture button beside a value, or add a map here.": "Doku yok. Bir değerin yanındaki doku düğmesini kullanın veya buraya bir harita ekleyin.", + "Object space": "Nesne uzayı", + "Offset U": "U kaydırma", + "Offset V": "V kaydırma", + "Open the node editor for this material": "Bu malzeme için düğüm düzenleyicisini aç", + "Parameters": "Parametreler", + "Pick a material first": "Önce bir malzeme seçin", + "Pick or create a material to edit it.": "Düzenlemek için bir malzeme seçin veya oluşturun.", + "Planar": "Düzlemsel", + "Platinum": "Platin", + "Projection": "İzdüşüm", + "RGB": "RGB", + "Range from": "Aralık başı", + "Range to": "Aralık sonu", + "Reading the material": "Malzeme okunuyor", + "Red": "Kırmızı", + "Rename material": "Malzemeyi yeniden adlandır", + "Repeat": "Tekrarla", + "Replace the image": "Görüntüyü değiştir", + "Reset to type": "Türe sıfırla", + "Save to library": "Kitaplığa kaydet", + "Saved {name} to your library": "{name} kitaplığınıza kaydedildi", + "Saving to the library needs an engine with library.save.": "Kitaplığa kaydetmek için library.save destekleyen bir motor gerekir.", + "Scale U": "U ölçeği", + "Scale V": "V ölçeği", + "Select parts in the viewport or the scene first": "Önce görünüm alanında veya sahnede parçaları seçin", + "Silver": "Gümüş", + "Space": "Uzay", + "Specular colour": "Yansıma rengi", + "Specular weight": "Yansıma ağırlığı", + "Spherical": "Küresel", + "Strength": "Güç", + "Subsurface": "Yüzey altı saçılımı", + "Subsurface colour": "Yüzey altı rengi", + "Subsurface radius": "Yüzey altı yarıçapı", + "Subsurface radius scale": "Yüzey altı yarıçap ölçeği", + "Texture": "Doku", + "Texture {key}": "{key} dokusu", + "Texture ×": "Doku ×", + "Textures": "Dokular", + "The engine does not know the type {id}; showing the main values.": "Motor {id} türünü tanımıyor; ana değerler gösteriliyor.", + "The engine lists no material types yet": "Motor henüz hiçbir malzeme türü listelemiyor", + "The image could not be uploaded ({status})": "Görüntü yüklenemedi ({status})", + "The texture multiplies this value": "Doku bu değerle çarpılır", + "Thin film": "İnce film", + "Thin glass": "İnce cam", + "Thin walled": "İnce duvarlı", + "Titanium": "Titanyum", + "Transmission": "Geçirgenlik", + "Transmission colour": "Geçirgenlik rengi", + "Transmission depth": "Geçirgenlik derinliği", + "Trilinear": "Trilinear", + "Type": "Tür", + "UV set": "UV kümesi", + "Used by 1 part": "1 parça kullanıyor", + "Used by {n} parts": "{n} parça kullanıyor", + "Waiting for the material settings": "Malzeme ayarları bekleniyor", + "Waiting for the material types": "Malzeme türleri bekleniyor", + "World space": "Dünya uzayı", + "Wrap": "Sarma", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "{name} silinemez. {reason}", + "{name} copy": "{name} kopyası" +} diff --git a/frontend/src/i18n/modules/material/uk.json b/frontend/src/i18n/modules/material/uk.json new file mode 100644 index 00000000..5f2fb047 --- /dev/null +++ b/frontend/src/i18n/modules/material/uk.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Граф з 1 вузла", + "A graph of {n} nodes": "Граф із вузлів: {n}", + "A texture drives this value; the value is its fallback": "Це значення задає текстура; значення править за запасне", + "ACEScg": "ACEScg", + "Abbe number": "Число Аббе", + "Add a map": "Додати карту", + "All parameters": "Усі параметри", + "Alpha": "Альфа", + "Aluminium": "Алюміній", + "Anisotropy": "Анізотропія", + "Assign to selection": "Призначити виділеному", + "Base weight": "Базова вага", + "Bilinear": "Білінійна", + "Blend": "Змішування", + "Blue": "Синій", + "Box": "Куб", + "Brushed metal": "Шліфований метал", + "Bump": "Бамп", + "Category": "Категорія", + "Change the material type": "Змінити тип матеріалу", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Змінити {from} на {to}. Зберегти поточні значення чи скинути їх до нового типу?", + "Channel": "Канал", + "Choose a texture image": "Виберіть зображення текстури", + "Choose an input": "Виберіть вхід", + "Chromium": "Хром", + "Clamp": "Обмеження", + "Clear plastic": "Прозорий пластик", + "Clear the texture slot": "Очистити слот текстури", + "Coat": "Покриття", + "Coat IOR": "IOR покриття", + "Coat colour": "Колір покриття", + "Coat darkening": "Затемнення покриття", + "Coat roughness": "Шорсткість покриття", + "Cobalt": "Кобальт", + "Colour space": "Колірний простір", + "Copper": "Мідь", + "Custom colour": "Власний колір", + "Cylindrical": "Циліндрична", + "Data (raw)": "Дані (без обробки)", + "Delete material": "Видалити матеріал", + "Diffuse": "Дифузний", + "Diffuse roughness": "Дифузна шорсткість", + "Dispersion": "Дисперсія", + "Displacement": "Зміщення", + "Drive {input} with a texture": "Задати {input} текстурою", + "Driven by the graph. Edit the graph to change it.": "Задається графом. Змініть граф, щоб змінити значення.", + "Drives no input yet": "Поки нічого не задає", + "Drives {inputs}": "Задає: {inputs}", + "Duplicate material": "Дублювати матеріал", + "Edit graph": "Змінити граф", + "Edit the texture of {input}": "Змінити текстуру для {input}", + "Emission colour": "Колір випромінювання", + "Fallback": "Запасне значення", + "Fallback colour": "Запасний колір", + "Film IOR": "IOR плівки", + "Film thickness": "Товщина плівки", + "Filter": "Фільтр", + "Flip green (DirectX)": "Інвертувати зелений (DirectX)", + "Fuzz": "Ворсистість", + "Fuzz colour": "Колір ворсу", + "Fuzz roughness": "Шорсткість ворсу", + "Generic": "Універсальний", + "Gold": "Золото", + "Graph": "Граф", + "Green": "Зелений", + "IOR": "IOR", + "Images": "Зображення", + "In use by 1 part. Assign another material to it first.": "Використовується в 1 деталі. Спочатку призначте їй інший матеріал.", + "In use by {n} parts. Assign another material to them first.": "Використовується в деталях: {n}. Спочатку призначте їм інший матеріал.", + "Invert": "Інвертувати", + "Iron": "Залізо", + "Keep this material as a preset in your library": "Зберегти цей матеріал як пресет у вашій бібліотеці", + "Keep values": "Залишити значення", + "Labels": "Підписи", + "Linear sRGB": "Лінійний sRGB", + "Luminance": "Яскравість", + "Material types": "Типи матеріалів", + "Measured metals": "Виміряні метали", + "Metallic paint": "Металік (фарба)", + "Mirror": "Дзеркало", + "Multiply by the value": "Помножити на значення", + "Name": "Назва", + "Nearest": "Найближчий", + "New": "Створити", + "New material": "Новий матеріал", + "Nickel": "Нікель", + "No graph": "Немає графа", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Графа немає. Цей тип виглядає правильно лише з графом; скиньте до типу, щоб повернути його.", + "No materials yet. Create one from a type with New.": "Матеріалів поки немає. Створіть матеріал із типу кнопкою «Створити».", + "No textures. Use the texture button beside a value, or add a map here.": "Текстур немає. Скористайтеся кнопкою текстури поруч зі значенням або додайте карту тут.", + "Object space": "Простір об'єкта", + "Offset U": "Зміщення U", + "Offset V": "Зміщення V", + "Open the node editor for this material": "Відкрити редактор вузлів для цього матеріалу", + "Parameters": "Параметри", + "Pick a material first": "Спочатку виберіть матеріал", + "Pick or create a material to edit it.": "Виберіть або створіть матеріал, щоб його змінити.", + "Planar": "Пласка", + "Platinum": "Платина", + "Projection": "Проєкція", + "RGB": "RGB", + "Range from": "Діапазон від", + "Range to": "Діапазон до", + "Reading the material": "Читання матеріалу", + "Red": "Червоний", + "Rename material": "Перейменувати матеріал", + "Repeat": "Повтор", + "Replace the image": "Замінити зображення", + "Reset to type": "Скинути до типу", + "Save to library": "Зберегти до бібліотеки", + "Saved {name} to your library": "{name} збережено до вашої бібліотеки", + "Saving to the library needs an engine with library.save.": "Для збереження до бібліотеки потрібен рушій із library.save.", + "Scale U": "Масштаб U", + "Scale V": "Масштаб V", + "Select parts in the viewport or the scene first": "Спочатку виберіть деталі у в'юпорті або в сцені", + "Silver": "Срібло", + "Space": "Простір", + "Specular colour": "Колір відблисків", + "Specular weight": "Вага відблисків", + "Spherical": "Сферична", + "Strength": "Сила", + "Subsurface": "Підповерхневе розсіювання", + "Subsurface colour": "Колір підповерхневого розсіювання", + "Subsurface radius": "Радіус підповерхневого розсіювання", + "Subsurface radius scale": "Масштаб радіуса підповерхневого розсіювання", + "Texture": "Текстура", + "Texture {key}": "Текстура {key}", + "Texture ×": "Текстура ×", + "Textures": "Текстури", + "The engine does not know the type {id}; showing the main values.": "Рушій не знає тип {id}; показано основні значення.", + "The engine lists no material types yet": "Рушій поки не перелічує типи матеріалів", + "The image could not be uploaded ({status})": "Не вдалося завантажити зображення ({status})", + "The texture multiplies this value": "Текстура множиться на це значення", + "Thin film": "Тонка плівка", + "Thin glass": "Тонке скло", + "Thin walled": "Тонкостінний", + "Titanium": "Титан", + "Transmission": "Пропускання", + "Transmission colour": "Колір пропускання", + "Transmission depth": "Глибина пропускання", + "Trilinear": "Трилінійна", + "Type": "Тип", + "UV set": "Набір UV", + "Used by 1 part": "Використовується в 1 деталі", + "Used by {n} parts": "Використовується в деталях: {n}", + "Waiting for the material settings": "Очікування налаштувань матеріалу", + "Waiting for the material types": "Очікування типів матеріалів", + "World space": "Світовий простір", + "Wrap": "Обгортання", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "Не вдалося видалити {name}. {reason}", + "{name} copy": "{name} (копія)" +} diff --git a/frontend/src/i18n/modules/material/vi.json b/frontend/src/i18n/modules/material/vi.json new file mode 100644 index 00000000..0224af48 --- /dev/null +++ b/frontend/src/i18n/modules/material/vi.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "Một đồ thị 1 nút", + "A graph of {n} nodes": "Một đồ thị {n} nút", + "A texture drives this value; the value is its fallback": "Một kết cấu điều khiển giá trị này; giá trị này là giá trị dự phòng", + "ACEScg": "ACEScg", + "Abbe number": "Số Abbe", + "Add a map": "Thêm map", + "All parameters": "Tất cả tham số", + "Alpha": "Alpha", + "Aluminium": "Nhôm", + "Anisotropy": "Dị hướng", + "Assign to selection": "Gán cho vùng chọn", + "Base weight": "Trọng số nền", + "Bilinear": "Song tuyến tính", + "Blend": "Trộn", + "Blue": "Xanh dương", + "Box": "Hộp", + "Brushed metal": "Kim loại xước", + "Bump": "Bump", + "Category": "Danh mục", + "Change the material type": "Đổi loại vật liệu", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "Đổi {from} thành {to}. Giữ các giá trị hiện tại hay đặt lại theo loại mới?", + "Channel": "Kênh", + "Choose a texture image": "Chọn ảnh kết cấu", + "Choose an input": "Chọn một đầu vào", + "Chromium": "Crom", + "Clamp": "Kẹp", + "Clear plastic": "Nhựa trong", + "Clear the texture slot": "Xóa ô kết cấu", + "Coat": "Lớp phủ", + "Coat IOR": "IOR lớp phủ", + "Coat colour": "Màu lớp phủ", + "Coat darkening": "Độ tối lớp phủ", + "Coat roughness": "Độ nhám lớp phủ", + "Cobalt": "Coban", + "Colour space": "Không gian màu", + "Copper": "Đồng", + "Custom colour": "Màu tùy chỉnh", + "Cylindrical": "Hình trụ", + "Data (raw)": "Dữ liệu (thô)", + "Delete material": "Xóa vật liệu", + "Diffuse": "Khuếch tán", + "Diffuse roughness": "Độ nhám khuếch tán", + "Dispersion": "Tán sắc", + "Displacement": "Dịch chuyển", + "Drive {input} with a texture": "Điều khiển {input} bằng kết cấu", + "Driven by the graph. Edit the graph to change it.": "Được điều khiển bởi đồ thị. Hãy sửa đồ thị để thay đổi.", + "Drives no input yet": "Chưa điều khiển đầu vào nào", + "Drives {inputs}": "Điều khiển {inputs}", + "Duplicate material": "Nhân bản vật liệu", + "Edit graph": "Sửa đồ thị", + "Edit the texture of {input}": "Sửa kết cấu của {input}", + "Emission colour": "Màu phát sáng", + "Fallback": "Dự phòng", + "Fallback colour": "Màu dự phòng", + "Film IOR": "IOR màng", + "Film thickness": "Độ dày màng", + "Filter": "Bộ lọc", + "Flip green (DirectX)": "Lật kênh xanh lá (DirectX)", + "Fuzz": "Lông mịn", + "Fuzz colour": "Màu lông mịn", + "Fuzz roughness": "Độ nhám lông mịn", + "Generic": "Chung", + "Gold": "Vàng", + "Graph": "Đồ thị", + "Green": "Xanh lá", + "IOR": "IOR", + "Images": "Ảnh", + "In use by 1 part. Assign another material to it first.": "Đang được 1 bộ phận dùng. Hãy gán vật liệu khác cho bộ phận đó trước.", + "In use by {n} parts. Assign another material to them first.": "Đang được {n} bộ phận dùng. Hãy gán vật liệu khác cho các bộ phận đó trước.", + "Invert": "Đảo ngược", + "Iron": "Sắt", + "Keep this material as a preset in your library": "Giữ vật liệu này làm cấu hình sẵn trong thư viện của bạn", + "Keep values": "Giữ giá trị", + "Labels": "Nhãn", + "Linear sRGB": "sRGB tuyến tính", + "Luminance": "Độ chói", + "Material types": "Loại vật liệu", + "Measured metals": "Kim loại đo thực tế", + "Metallic paint": "Sơn ánh kim", + "Mirror": "Gương", + "Multiply by the value": "Nhân với giá trị", + "Name": "Tên", + "Nearest": "Gần nhất", + "New": "Mới", + "New material": "Vật liệu mới", + "Nickel": "Niken", + "No graph": "Không có đồ thị", + "No graph. This type looks right only with its graph; reset to type to get it back.": "Không có đồ thị. Loại này chỉ đúng khi có đồ thị; hãy đặt lại theo loại để lấy lại.", + "No materials yet. Create one from a type with New.": "Chưa có vật liệu nào. Hãy tạo một vật liệu từ một loại bằng nút Mới.", + "No textures. Use the texture button beside a value, or add a map here.": "Chưa có kết cấu. Dùng nút kết cấu cạnh một giá trị, hoặc thêm map tại đây.", + "Object space": "Không gian đối tượng", + "Offset U": "Độ lệch U", + "Offset V": "Độ lệch V", + "Open the node editor for this material": "Mở trình sửa nút cho vật liệu này", + "Parameters": "Tham số", + "Pick a material first": "Hãy chọn vật liệu trước", + "Pick or create a material to edit it.": "Chọn hoặc tạo một vật liệu để sửa.", + "Planar": "Phẳng", + "Platinum": "Bạch kim", + "Projection": "Phép chiếu", + "RGB": "RGB", + "Range from": "Khoảng từ", + "Range to": "Khoảng đến", + "Reading the material": "Đang đọc vật liệu", + "Red": "Đỏ", + "Rename material": "Đổi tên vật liệu", + "Repeat": "Lặp lại", + "Replace the image": "Thay ảnh", + "Reset to type": "Đặt lại theo loại", + "Save to library": "Lưu vào thư viện", + "Saved {name} to your library": "Đã lưu {name} vào thư viện của bạn", + "Saving to the library needs an engine with library.save.": "Lưu vào thư viện cần công cụ có library.save.", + "Scale U": "Tỷ lệ U", + "Scale V": "Tỷ lệ V", + "Select parts in the viewport or the scene first": "Hãy chọn bộ phận trong khung nhìn hoặc trong cảnh trước", + "Silver": "Bạc", + "Space": "Không gian", + "Specular colour": "Màu phản chiếu", + "Specular weight": "Trọng số phản chiếu", + "Spherical": "Hình cầu", + "Strength": "Cường độ", + "Subsurface": "Tán xạ dưới bề mặt", + "Subsurface colour": "Màu tán xạ dưới bề mặt", + "Subsurface radius": "Bán kính tán xạ dưới bề mặt", + "Subsurface radius scale": "Tỷ lệ bán kính tán xạ dưới bề mặt", + "Texture": "Kết cấu", + "Texture {key}": "Kết cấu {key}", + "Texture ×": "Kết cấu ×", + "Textures": "Kết cấu", + "The engine does not know the type {id}; showing the main values.": "Công cụ không biết loại {id}; đang hiện các giá trị chính.", + "The engine lists no material types yet": "Công cụ chưa liệt kê loại vật liệu nào", + "The image could not be uploaded ({status})": "Không thể tải ảnh lên ({status})", + "The texture multiplies this value": "Kết cấu nhân với giá trị này", + "Thin film": "Màng mỏng", + "Thin glass": "Kính mỏng", + "Thin walled": "Thành mỏng", + "Titanium": "Titan", + "Transmission": "Truyền sáng", + "Transmission colour": "Màu truyền sáng", + "Transmission depth": "Độ sâu truyền sáng", + "Trilinear": "Ba tuyến tính", + "Type": "Loại", + "UV set": "Bộ UV", + "Used by 1 part": "Được 1 bộ phận dùng", + "Used by {n} parts": "Được {n} bộ phận dùng", + "Waiting for the material settings": "Đang chờ cài đặt vật liệu", + "Waiting for the material types": "Đang chờ các loại vật liệu", + "World space": "Không gian thế giới", + "Wrap": "Bọc", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "Không thể xóa {name}. {reason}", + "{name} copy": "Bản sao của {name}" +} diff --git a/frontend/src/i18n/modules/material/zh-CN.json b/frontend/src/i18n/modules/material/zh-CN.json new file mode 100644 index 00000000..508dfb2b --- /dev/null +++ b/frontend/src/i18n/modules/material/zh-CN.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "1 个节点的图", + "A graph of {n} nodes": "{n} 个节点的图", + "A texture drives this value; the value is its fallback": "由纹理驱动此值;此值为其备用值", + "ACEScg": "ACEScg", + "Abbe number": "阿贝数", + "Add a map": "添加贴图", + "All parameters": "所有参数", + "Alpha": "Alpha", + "Aluminium": "铝", + "Anisotropy": "各向异性", + "Assign to selection": "分配给所选内容", + "Base weight": "基础权重", + "Bilinear": "双线性", + "Blend": "混合", + "Blue": "蓝", + "Box": "立方体", + "Brushed metal": "拉丝金属", + "Bump": "凹凸", + "Category": "类别", + "Change the material type": "更改材质类型", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "将 {from} 更改为 {to}。保留当前值,还是重置为新类型的值?", + "Channel": "通道", + "Choose a texture image": "选择纹理图像", + "Choose an input": "选择输入", + "Chromium": "铬", + "Clamp": "钳制", + "Clear plastic": "透明塑料", + "Clear the texture slot": "清除纹理槽", + "Coat": "清漆", + "Coat IOR": "清漆 IOR", + "Coat colour": "清漆颜色", + "Coat darkening": "清漆变暗", + "Coat roughness": "清漆粗糙度", + "Cobalt": "钴", + "Colour space": "色彩空间", + "Copper": "铜", + "Custom colour": "自定义颜色", + "Cylindrical": "圆柱", + "Data (raw)": "数据(原始)", + "Delete material": "删除材质", + "Diffuse": "漫反射", + "Diffuse roughness": "漫反射粗糙度", + "Dispersion": "色散", + "Displacement": "置换", + "Drive {input} with a texture": "用纹理驱动{input}", + "Driven by the graph. Edit the graph to change it.": "由图驱动。编辑图即可更改。", + "Drives no input yet": "尚未驱动任何输入", + "Drives {inputs}": "驱动 {inputs}", + "Duplicate material": "复制材质", + "Edit graph": "编辑图", + "Edit the texture of {input}": "编辑{input}的纹理", + "Emission colour": "自发光颜色", + "Fallback": "备用值", + "Fallback colour": "备用颜色", + "Film IOR": "薄膜 IOR", + "Film thickness": "薄膜厚度", + "Filter": "过滤", + "Flip green (DirectX)": "翻转绿色 (DirectX)", + "Fuzz": "绒毛", + "Fuzz colour": "绒毛颜色", + "Fuzz roughness": "绒毛粗糙度", + "Generic": "通用", + "Gold": "金", + "Graph": "图", + "Green": "绿", + "IOR": "IOR", + "Images": "图像", + "In use by 1 part. Assign another material to it first.": "有 1 个部件正在使用。请先为其分配其他材质。", + "In use by {n} parts. Assign another material to them first.": "有 {n} 个部件正在使用。请先为它们分配其他材质。", + "Invert": "反转", + "Iron": "铁", + "Keep this material as a preset in your library": "将此材质作为预设保存在你的资源库中", + "Keep values": "保留当前值", + "Labels": "标签", + "Linear sRGB": "线性 sRGB", + "Luminance": "亮度", + "Material types": "材质类型", + "Measured metals": "实测金属", + "Metallic paint": "金属漆", + "Mirror": "镜面", + "Multiply by the value": "与此值相乘", + "Name": "名称", + "Nearest": "最近邻", + "New": "新建", + "New material": "新建材质", + "Nickel": "镍", + "No graph": "无图", + "No graph. This type looks right only with its graph; reset to type to get it back.": "没有图。此类型只有配合其图才能正确显示;重置为类型即可恢复。", + "No materials yet. Create one from a type with New.": "还没有材质。请用“新建”从某个类型创建。", + "No textures. Use the texture button beside a value, or add a map here.": "没有纹理。请使用值旁边的纹理按钮,或在此添加贴图。", + "Object space": "物体空间", + "Offset U": "U 偏移", + "Offset V": "V 偏移", + "Open the node editor for this material": "打开此材质的节点编辑器", + "Parameters": "参数", + "Pick a material first": "请先选择材质", + "Pick or create a material to edit it.": "选择或创建一个材质以进行编辑。", + "Planar": "平面", + "Platinum": "铂", + "Projection": "投影", + "RGB": "RGB", + "Range from": "范围起点", + "Range to": "范围终点", + "Reading the material": "正在读取材质", + "Red": "红", + "Rename material": "重命名材质", + "Repeat": "重复", + "Replace the image": "替换图像", + "Reset to type": "重置为类型", + "Save to library": "保存到资源库", + "Saved {name} to your library": "已将 {name} 保存到你的资源库", + "Saving to the library needs an engine with library.save.": "保存到资源库需要支持 library.save 的引擎。", + "Scale U": "U 缩放", + "Scale V": "V 缩放", + "Select parts in the viewport or the scene first": "请先在视口或场景中选择部件", + "Silver": "银", + "Space": "空间", + "Specular colour": "镜面反射颜色", + "Specular weight": "镜面反射权重", + "Spherical": "球形", + "Strength": "强度", + "Subsurface": "次表面", + "Subsurface colour": "次表面颜色", + "Subsurface radius": "次表面半径", + "Subsurface radius scale": "次表面半径缩放", + "Texture": "纹理", + "Texture {key}": "纹理 {key}", + "Texture ×": "纹理 ×", + "Textures": "纹理", + "The engine does not know the type {id}; showing the main values.": "引擎不识别类型 {id};显示主要值。", + "The engine lists no material types yet": "引擎尚未列出任何材质类型", + "The image could not be uploaded ({status})": "无法上传图像 ({status})", + "The texture multiplies this value": "纹理会与此值相乘", + "Thin film": "薄膜", + "Thin glass": "薄玻璃", + "Thin walled": "薄壁", + "Titanium": "钛", + "Transmission": "透射", + "Transmission colour": "透射颜色", + "Transmission depth": "透射深度", + "Trilinear": "三线性", + "Type": "类型", + "UV set": "UV 集", + "Used by 1 part": "被 1 个部件使用", + "Used by {n} parts": "被 {n} 个部件使用", + "Waiting for the material settings": "正在等待材质设置", + "Waiting for the material types": "正在等待材质类型", + "World space": "世界空间", + "Wrap": "环绕", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "无法删除 {name}。{reason}", + "{name} copy": "{name} 副本" +} diff --git a/frontend/src/i18n/modules/material/zh-TW.json b/frontend/src/i18n/modules/material/zh-TW.json new file mode 100644 index 00000000..a09778c0 --- /dev/null +++ b/frontend/src/i18n/modules/material/zh-TW.json @@ -0,0 +1,154 @@ +{ + "A graph of 1 node": "1 個節點的圖", + "A graph of {n} nodes": "{n} 個節點的圖", + "A texture drives this value; the value is its fallback": "由紋理驅動此值;此值為其備用值", + "ACEScg": "ACEScg", + "Abbe number": "阿貝數", + "Add a map": "加入貼圖", + "All parameters": "所有參數", + "Alpha": "Alpha", + "Aluminium": "鋁", + "Anisotropy": "各向異性", + "Assign to selection": "指定給所選內容", + "Base weight": "基礎權重", + "Bilinear": "雙線性", + "Blend": "混合", + "Blue": "藍", + "Box": "立方體", + "Brushed metal": "拉絲金屬", + "Bump": "凹凸", + "Category": "類別", + "Change the material type": "變更材質類型", + "Change {from} to {to}. Keep the current values, or reset them to the new type?": "將 {from} 變更為 {to}。保留目前的值,還是重設為新類型的值?", + "Channel": "色版", + "Choose a texture image": "選擇紋理影像", + "Choose an input": "選擇輸入", + "Chromium": "鉻", + "Clamp": "夾制", + "Clear plastic": "透明塑膠", + "Clear the texture slot": "清除紋理槽", + "Coat": "透明塗層", + "Coat IOR": "透明塗層 IOR", + "Coat colour": "透明塗層顏色", + "Coat darkening": "透明塗層變暗", + "Coat roughness": "透明塗層粗糙度", + "Cobalt": "鈷", + "Colour space": "色彩空間", + "Copper": "銅", + "Custom colour": "自訂顏色", + "Cylindrical": "圓柱", + "Data (raw)": "資料(原始)", + "Delete material": "刪除材質", + "Diffuse": "漫射", + "Diffuse roughness": "漫射粗糙度", + "Dispersion": "色散", + "Displacement": "置換", + "Drive {input} with a texture": "用紋理驅動{input}", + "Driven by the graph. Edit the graph to change it.": "由圖驅動。編輯圖即可變更。", + "Drives no input yet": "尚未驅動任何輸入", + "Drives {inputs}": "驅動 {inputs}", + "Duplicate material": "複製材質", + "Edit graph": "編輯圖", + "Edit the texture of {input}": "編輯{input}的紋理", + "Emission colour": "自發光顏色", + "Fallback": "備用值", + "Fallback colour": "備用顏色", + "Film IOR": "薄膜 IOR", + "Film thickness": "薄膜厚度", + "Filter": "篩選", + "Flip green (DirectX)": "翻轉綠色 (DirectX)", + "Fuzz": "絨毛", + "Fuzz colour": "絨毛顏色", + "Fuzz roughness": "絨毛粗糙度", + "Generic": "通用", + "Gold": "金", + "Graph": "圖", + "Green": "綠", + "IOR": "IOR", + "Images": "影像", + "In use by 1 part. Assign another material to it first.": "有 1 個零件正在使用。請先為其指定其他材質。", + "In use by {n} parts. Assign another material to them first.": "有 {n} 個零件正在使用。請先為它們指定其他材質。", + "Invert": "反轉", + "Iron": "鐵", + "Keep this material as a preset in your library": "將此材質作為預設集儲存在你的資源庫中", + "Keep values": "保留目前的值", + "Labels": "標籤", + "Linear sRGB": "線性 sRGB", + "Luminance": "亮度", + "Material types": "材質類型", + "Measured metals": "實測金屬", + "Metallic paint": "金屬漆", + "Mirror": "鏡面", + "Multiply by the value": "與此值相乘", + "Name": "名稱", + "Nearest": "最近鄰", + "New": "新增", + "New material": "新增材質", + "Nickel": "鎳", + "No graph": "無圖", + "No graph. This type looks right only with its graph; reset to type to get it back.": "沒有圖。此類型只有搭配其圖才能正確顯示;重設為類型即可恢復。", + "No materials yet. Create one from a type with New.": "還沒有材質。請用「新增」從某個類型建立。", + "No textures. Use the texture button beside a value, or add a map here.": "沒有紋理。請使用值旁邊的紋理按鈕,或在此加入貼圖。", + "Object space": "物件空間", + "Offset U": "U 偏移", + "Offset V": "V 偏移", + "Open the node editor for this material": "開啟此材質的節點編輯器", + "Parameters": "參數", + "Pick a material first": "請先選擇材質", + "Pick or create a material to edit it.": "選擇或建立一個材質以進行編輯。", + "Planar": "平面", + "Platinum": "鉑", + "Projection": "投影", + "RGB": "RGB", + "Range from": "範圍起點", + "Range to": "範圍終點", + "Reading the material": "正在讀取材質", + "Red": "紅", + "Rename material": "重新命名材質", + "Repeat": "重複", + "Replace the image": "取代影像", + "Reset to type": "重設為類型", + "Save to library": "儲存到資源庫", + "Saved {name} to your library": "已將 {name} 儲存到你的資源庫", + "Saving to the library needs an engine with library.save.": "儲存到資源庫需要支援 library.save 的引擎。", + "Scale U": "U 縮放", + "Scale V": "V 縮放", + "Select parts in the viewport or the scene first": "請先在視埠或場景中選擇零件", + "Silver": "銀", + "Space": "空間", + "Specular colour": "鏡面反射顏色", + "Specular weight": "鏡面反射權重", + "Spherical": "球形", + "Strength": "強度", + "Subsurface": "次表面", + "Subsurface colour": "次表面顏色", + "Subsurface radius": "次表面半徑", + "Subsurface radius scale": "次表面半徑縮放", + "Texture": "紋理", + "Texture {key}": "紋理 {key}", + "Texture ×": "紋理 ×", + "Textures": "紋理", + "The engine does not know the type {id}; showing the main values.": "引擎不認識類型 {id};顯示主要值。", + "The engine lists no material types yet": "引擎尚未列出任何材質類型", + "The image could not be uploaded ({status})": "無法上傳影像 ({status})", + "The texture multiplies this value": "紋理會與此值相乘", + "Thin film": "薄膜", + "Thin glass": "薄玻璃", + "Thin walled": "薄壁", + "Titanium": "鈦", + "Transmission": "透射", + "Transmission colour": "透射顏色", + "Transmission depth": "透射深度", + "Trilinear": "三線性", + "Type": "類型", + "UV set": "UV 集", + "Used by 1 part": "被 1 個零件使用", + "Used by {n} parts": "被 {n} 個零件使用", + "Waiting for the material settings": "正在等待材質設定", + "Waiting for the material types": "正在等待材質類型", + "World space": "世界空間", + "Wrap": "環繞", + "sRGB": "sRGB", + "{name} cannot be deleted. {reason}": "無法刪除 {name}。{reason}", + "{name} copy": "{name} 副本" +} diff --git a/frontend/src/modules.ts b/frontend/src/modules.ts index ddb26cea..00b3f39a 100644 --- a/frontend/src/modules.ts +++ b/frontend/src/modules.ts @@ -4,6 +4,9 @@ import { mount as settings } from './shell/settings'; import { mount as menu } from './shell/topbar'; import { mount as dock } from './shell/dock-adapter'; import { mount as home } from './shell/home'; +import { mount as importer } from './ui/import/index'; +import { mount as handoff } from './ui/handoff/index'; +import { mount as cad } from './ui/cad/index'; export const MODULES: readonly ShellModule[] = [ { id: 'workspace', mount: workspace }, @@ -11,4 +14,7 @@ export const MODULES: readonly ShellModule[] = [ { id: 'menu', mount: menu }, { id: 'dock', mount: dock }, { id: 'home', mount: home }, + { id: 'import', mount: importer }, + { id: 'handoff', mount: handoff }, + { id: 'cad', mount: cad }, ]; diff --git a/frontend/src/shell/commands.ts b/frontend/src/shell/commands.ts index a1b0725e..0c1d9878 100644 --- a/frontend/src/shell/commands.ts +++ b/frontend/src/shell/commands.ts @@ -214,6 +214,10 @@ export function registerWorkspaceCommands(client: EngineClient, render: RenderLo { id: 'workspace.state', label: 'Project State', group: 'File', palette: false, run: () => workspaceState() }, ])); + offs.push(client.onDispatch((n) => { + if (n.change === 'none' && client.entry(n.name)?.mutates === true) client.scheduleRefresh(); + })); + offs.push(registerMenu({ id: 'view', items: [{ command: 'viewport.screenshot', section: 1 }] })); offs.push(registerMenu({ id: 'render', items: [{ command: 'viewport.pause', section: 0 }] })); diff --git a/frontend/src/shell/home.ts b/frontend/src/shell/home.ts index 5843884f..36b90905 100644 --- a/frontend/src/shell/home.ts +++ b/frontend/src/shell/home.ts @@ -337,6 +337,12 @@ ${nav('start', icon('home', 16), 'Start')}${nav('recent', icon('layers', 16), 'R const file = files.find((f) => extOf(f.name) === PROJECT_EXT) ?? files.find((f) => MODEL_EXTS.includes(extOf(f.name))); if (!file) { toast(t('FormShot opens .fshot projects and {formats} models.', { formats: MODEL_EXTS.map((x) => x.toUpperCase()).join(', ') }), 'error'); return; } if (this.busy) return; + if (extOf(file.name) !== PROJECT_EXT && getCommand('import.files')) { + const before = this.doc; + await this.create(DEFAULT_TEMPLATE, baseName(file.name)); + if (this.doc !== before && this.doc.hasDocument) runCommand('import.files', { files }); + return; + } this.busy = true; const project = extOf(file.name) === PROJECT_EXT; try { diff --git a/frontend/src/styles/material.css b/frontend/src/styles/material.css new file mode 100644 index 00000000..246f9749 --- /dev/null +++ b/frontend/src/styles/material.css @@ -0,0 +1,103 @@ +.fsh-mat-status { margin-bottom: var(--space-1); } + +.fsh-mat-tools { display: flex; align-items: center; gap: var(--space-1); height: var(--ctl-md); margin-bottom: var(--space-2); } +.fsh-mat-tools-gap { flex: 1; } +.fsh-mat-new { display: inline-flex; align-items: center; gap: var(--space-1); } +.fsh-mat-tools .fsh-icon-btn[aria-disabled="true"] { opacity: 0.5; } + +.fsh-mat-list { display: flex; flex-direction: column; gap: 1px; } +.fsh-mat-row { position: relative; display: grid; grid-template-columns: 28px minmax(0, 1fr) auto; align-items: center; gap: var(--space-2); height: 40px; padding: 0 var(--space-2); border-radius: var(--radius-md); cursor: pointer; outline: none; } +.fsh-mat-row:hover { background: var(--bg-hover); } +.fsh-mat-row:focus-visible { box-shadow: inset 0 0 0 1px var(--accent-color); } +.fsh-mat-row[aria-selected="true"] { background: var(--accent-tint); } +.fsh-mat-row.is-in-selection::before { content: ""; position: absolute; left: 0; top: var(--space-2); bottom: var(--space-2); width: 2px; border-radius: var(--radius-pill); background: var(--accent-color); } +.fsh-mat-swatch { width: 28px; height: 28px; border-radius: 50%; background: var(--surface-3); } +.fsh-mat-row-text { display: flex; flex-direction: column; min-width: 0; line-height: var(--lh-tight); } +.fsh-mat-row-name { overflow: hidden; color: var(--text-primary); font-size: var(--fs-12); text-overflow: ellipsis; white-space: nowrap; } +.fsh-mat-row-type { overflow: hidden; color: var(--text-faint); font-size: var(--fs-10); text-overflow: ellipsis; white-space: nowrap; } +.fsh-mat-row-uses { min-width: 3ch; color: var(--text-muted); font-size: var(--fs-11); text-align: right; } +.fsh-mat-row.is-renaming .fsh-mat-row-text { visibility: hidden; } +.fsh-mat-rename-input { position: absolute; left: calc(28px + var(--space-4)); right: var(--space-6); height: var(--ctl-sm); font-size: var(--fs-12); } +.fsh-mat-rename-input[hidden] { display: none; } +.fsh-mat-list-empty { margin: var(--space-1) 0 0; color: var(--text-muted); font-size: var(--fs-12); } +.fsh-mat-list-empty[hidden] { display: none; } + +.fsh-mat-pop { position: fixed; left: var(--fsh-mat-pop-x, 0); top: var(--fsh-mat-pop-y, 0); z-index: var(--z-menu); max-height: min(70vh, 560px); overflow-y: auto; padding: var(--space-2); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); background: var(--glass-bg); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); pointer-events: auto; } +.fsh-mat-pop[hidden] { display: none; } +.fsh-mat-pop-empty { margin: var(--space-2); color: var(--text-muted); font-size: var(--fs-12); } +.fsh-mat-types { width: 300px; } +.fsh-mat-type-group + .fsh-mat-type-group { margin-top: var(--space-2); } +.fsh-mat-type-group h4 { margin: 0 0 var(--space-1); padding: 0 var(--space-1); color: var(--text-faint); font-size: var(--fs-10); font-weight: var(--fw-semibold); letter-spacing: 0.06em; text-transform: uppercase; } +.fsh-mat-type-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 2px; } +.fsh-mat-type, .fsh-mat-metal { display: flex; align-items: center; gap: var(--space-2); height: var(--ctl-sm); padding: 0 var(--space-2); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-primary); font: inherit; font-size: var(--fs-12); text-align: left; cursor: pointer; } +.fsh-mat-type:hover, .fsh-mat-metal:hover, .fsh-mat-type:focus-visible, .fsh-mat-metal:focus-visible { background: var(--bg-hover); outline: none; } +.fsh-mat-metals { display: grid; grid-template-columns: 1fr 1fr; gap: 2px; margin-top: 2px; padding-top: var(--space-1); border-top: 1px solid var(--line-1); } +.fsh-mat-metal-chip { flex: none; width: 12px; height: 12px; border-radius: 50%; background: var(--fsh-mat-chip, var(--surface-3)); box-shadow: inset 0 0 0 1px var(--line-2); } + +.fsh-mat-none { margin: 0; color: var(--text-muted); font-size: var(--fs-12); } +.fsh-mat-none[hidden], .fsh-mat-params-wrap[hidden], .fsh-mat-slots[hidden] { display: none; } +.fsh-mat-params { display: flex; flex-direction: column; gap: var(--space-1); } +.fsh-mat-prow { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: var(--space-1); min-height: var(--ctl-md); } +.fsh-mat-prow[hidden] { display: none; } +.fsh-mat-pctl { min-width: 0; } +.fsh-mat-pextra:empty { display: none; } +.fsh-mat-pextra { display: flex; width: var(--ctl-md); justify-content: center; } +.fsh-mat-plabel { overflow: hidden; color: var(--text-secondary); font-size: var(--fs-12); text-overflow: ellipsis; white-space: nowrap; } +.fsh-mat-colour, .fsh-mat-toggle, .fsh-mat-selectrow { display: grid; align-items: center; gap: var(--space-2); height: var(--ctl-md); } +.fsh-mat-colour { grid-template-columns: minmax(0, 1fr) 8ch 40px; padding: 0 var(--space-1) 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); cursor: pointer; } +.fsh-mat-hex { color: var(--text-muted); font: var(--fs-11) var(--mono); text-align: right; } +.fsh-mat-colour-input { width: 40px; height: 20px; padding: 0; border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: transparent; cursor: pointer; } +.fsh-mat-colour-input:disabled { cursor: default; } +.fsh-mat-toggle { grid-template-columns: minmax(0, 1fr) auto; padding: 0 var(--space-2); cursor: pointer; } +.fsh-mat-toggle input { width: 16px; height: 16px; margin: 0; accent-color: var(--accent-color); cursor: pointer; } +.fsh-mat-selectrow { grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr); padding-left: var(--space-2); } +.fsh-mat-select { width: 100%; height: var(--ctl-md); padding: 0 var(--space-1); cursor: pointer; } +.fsh-mat-select:disabled { opacity: 0.5; cursor: default; } +.fsh-mat-prow.is-disabled .fsh-mat-colour, .fsh-mat-prow.is-disabled .fsh-mat-toggle { opacity: 0.55; cursor: default; } +.fsh-mat-tag { padding: 0 var(--space-1); border-radius: var(--radius-sm); background: var(--accent-soft); color: var(--accent-ink); font-size: var(--fs-10); line-height: 18px; white-space: nowrap; } +.fsh-mat-tag[hidden] { display: none; } +.fsh-mat-typerow { margin-bottom: var(--space-1); } +.fsh-mat-params-note { margin: var(--space-1) 0 0; color: var(--text-muted); font-size: var(--fs-11); } +.fsh-mat-params-note[hidden] { display: none; } +.fsh-mat-slotbtn { width: var(--ctl-sm); height: var(--ctl-sm); color: var(--text-faint); } +.fsh-mat-slotbtn[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent-color); } + +.fsh-mat-all { margin-top: var(--space-2); border-top: 1px solid var(--line-0); } +.fsh-mat-all-head { display: flex; align-items: center; height: var(--ctl-md); color: var(--text-muted); font-size: var(--fs-11); cursor: pointer; list-style: none; } +.fsh-mat-all-head::-webkit-details-marker { display: none; } +.fsh-mat-all-head::before { content: ""; width: 0; height: 0; margin-right: var(--space-2); border-top: 4px solid transparent; border-bottom: 4px solid transparent; border-left: 5px solid currentColor; transition: transform var(--dur-fast); } +.fsh-mat-all[open] > .fsh-mat-all-head::before { transform: rotate(90deg); } + +.fsh-mat-typechoice { width: 260px; } +.fsh-mat-choice { display: flex; flex-wrap: wrap; gap: var(--space-2); padding: var(--space-1); } +.fsh-mat-choice-text { flex-basis: 100%; margin: 0 0 var(--space-1); color: var(--text-secondary); font-size: var(--fs-12); } + +.fsh-mat-slot-list { display: flex; flex-direction: column; gap: var(--space-1); } +.fsh-mat-slot { border: 1px solid var(--line-1); border-radius: var(--radius-md); background: var(--surface-1); } +.fsh-mat-slot.is-driven { opacity: 0.7; } +.fsh-mat-slot-head { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 2px; height: var(--ctl); padding-right: var(--space-1); } +.fsh-mat-slot-toggle { display: flex; align-items: center; gap: var(--space-2); min-width: 0; height: 100%; padding: 0 var(--space-2); border: 0; background: transparent; color: var(--text-primary); font: inherit; font-size: var(--fs-12); text-align: left; cursor: pointer; } +.fsh-mat-slot-toggle .fsh-icon { flex: none; transition: transform var(--dur-fast); } +.fsh-mat-slot.is-open .fsh-mat-slot-toggle .fsh-icon { transform: rotate(90deg); } +.fsh-mat-slot-input { flex: none; } +.fsh-mat-slot-file { min-width: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-mat-slot-body { display: flex; flex-direction: column; gap: var(--space-1); padding: var(--space-1) var(--space-2) var(--space-2); border-top: 1px solid var(--line-0); } +.fsh-mat-slot-body[hidden] { display: none; } +.fsh-mat-slots-empty { margin: 0; color: var(--text-muted); font-size: var(--fs-12); } +.fsh-mat-slots-empty[hidden] { display: none; } +.fsh-mat-addmap { margin-top: var(--space-1); } +.fsh-mat-addmap.is-shown .fsh-mat-select { opacity: 0.6; } +.fsh-mat-slotbtn.is-shown { color: var(--accent-color); } + +.fsh-mat-graph { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: var(--space-2); min-height: 44px; } +.fsh-mat-graph-text { display: flex; flex-direction: column; min-width: 0; gap: 2px; } +.fsh-mat-graph-state { color: var(--text-secondary); font-size: var(--fs-12); } +.fsh-mat-graph-drives { min-height: 1.3em; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-mat-graph-edit, .fsh-mat-lib-save { display: inline-flex; align-items: center; gap: var(--space-1); } + +.fsh-mat-labels { min-height: 120px; } + +.fsh-mat-lib { display: flex; align-items: center; gap: var(--space-2); min-height: var(--ctl-md); } +.fsh-mat-lib-why { min-width: 0; color: var(--text-faint); font-size: var(--fs-11); } +.fsh-mat-lib-form { display: flex; flex-direction: column; gap: var(--space-3); min-width: 320px; } +.fsh-mat-lib-field { display: flex; flex-direction: column; gap: var(--space-1); color: var(--text-secondary); font-size: var(--fs-12); } diff --git a/frontend/src/ui/cad/cad.css b/frontend/src/ui/cad/cad.css new file mode 100644 index 00000000..84638394 --- /dev/null +++ b/frontend/src/ui/cad/cad.css @@ -0,0 +1,70 @@ +.fsh-cad-settings { display: grid; gap: var(--space-4); color: var(--text-primary); font-size: var(--fs-12); } +.fsh-cad-settings .fsh-note { margin: 0; line-height: var(--lh); } +.fsh-cad-block { display: grid; gap: var(--space-2); } +.fsh-cad-head { margin: 0; color: var(--text-secondary); font-size: var(--fs-11); font-weight: var(--fw-semibold); letter-spacing: 0.04em; text-transform: uppercase; } + +.fsh-cad-facts { display: grid; margin: 0; } +.fsh-cad-facts > div { display: grid; grid-template-columns: 14ch minmax(0, 1fr); align-items: center; gap: var(--space-3); height: 26px; border-bottom: 1px solid var(--line-1); } +.fsh-cad-facts dt { overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-cad-facts dd { display: flex; align-items: center; gap: var(--space-2); min-width: 0; margin: 0; overflow: hidden; color: var(--text-primary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-cad-facts dd.fsh-cad-path { display: block; font-family: var(--font-mono); font-size: var(--fs-11); direction: rtl; text-align: left; } +.fsh-cad-dot { flex: none; width: 8px; height: 8px; border-radius: var(--radius-pill); background: var(--text-faint); } +.fsh-cad-dot[data-state="ok"] { background: var(--ok); } +.fsh-cad-dot[data-state="off"] { background: var(--warn); } + +.fsh-cad-reason { height: calc(var(--fs-12) * var(--lh) * 2); margin: 0; overflow: hidden; color: var(--text-muted); line-height: var(--lh); } +.fsh-cad-actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); min-height: var(--ctl-md); } +.fsh-cad-actions [data-a="fetch"] { min-width: 26ch; } +.fsh-cad-actions [data-a="refresh"] { margin-left: auto; } + +.fsh-cad-progress { display: grid; grid-template-columns: 22ch minmax(0, 1fr) 5ch; align-items: center; gap: var(--space-3); height: 22px; visibility: hidden; } +.fsh-cad-progress.is-on { visibility: visible; } +.fsh-cad-stage { overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-cad-bar { position: relative; height: 6px; overflow: hidden; border-radius: var(--radius-pill); background: var(--line-2); } +.fsh-cad-fill { position: absolute; inset: 0; border-radius: inherit; background: var(--accent-color); transform: scaleX(var(--fsh-cad-fraction, 0)); transform-origin: left center; transition: transform var(--dur-fast) linear; } +.fsh-cad-pct { color: var(--text-muted); text-align: right; } +.fsh-cad-detail { height: 1.5em; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-cad-result { min-height: calc(var(--fs-12) * var(--lh) * 2); margin: 0; color: var(--text-secondary); line-height: var(--lh); overflow-wrap: anywhere; } +.fsh-cad-result.is-error { color: var(--danger-text); } +.fsh-cad-result.is-ok { color: var(--ok); } + +.fsh-cad-quality { display: grid; gap: var(--space-2); } +.fsh-cad-presets { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 2px; padding: 2px; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); } +.fsh-cad-preset { position: relative; display: flex; align-items: center; justify-content: center; height: var(--ctl-sm); border-radius: var(--radius); color: var(--text-secondary); cursor: pointer; } +.fsh-cad-preset input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; } +.fsh-cad-preset:has(input:checked) { background: var(--accent-soft); color: var(--accent-color); } +.fsh-cad-preset:has(input:focus-visible) { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fsh-cad-preset:has(input:disabled) { opacity: 0.5; cursor: default; } +.fsh-cad-custom { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--space-3); } +.fsh-cad-field { display: grid; grid-template-columns: auto 10ch minmax(0, 1fr); align-items: center; gap: var(--space-2); height: var(--ctl-md); color: var(--text-secondary); } +.fsh-cad-field input { width: 100%; text-align: right; } +.fsh-cad-field input:disabled { opacity: 0.6; } +.fsh-cad-unit { overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-cad-quality-line { height: 1.5em; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-cad-quality-line.is-error { color: var(--danger-text); } + +.fsh-cad-offer { position: relative; display: grid; grid-template-columns: 14px minmax(0, 1fr) auto; align-items: center; gap: var(--space-2); height: 36px; padding: 0 var(--space-2); overflow: hidden; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface-1); color: var(--text-secondary); font-size: var(--fs-11); line-height: var(--lh-tight); visibility: hidden; } +.fsh-cad-offer.is-on { visibility: visible; } +.fsh-cad-offer-icon { display: inline-flex; color: var(--warn); } +.fsh-cad-offer.is-ok .fsh-cad-offer-icon { color: var(--ok); } +.fsh-cad-offer.is-error .fsh-cad-offer-icon { color: var(--danger); } +.fsh-cad-offer-text { display: -webkit-box; overflow: hidden; -webkit-box-orient: vertical; -webkit-line-clamp: 2; } +.fsh-cad-offer-btn { min-width: 12ch; } +.fsh-cad-offer-btn[data-hidden] { visibility: hidden; } +.fsh-cad-offer-bar { position: absolute; right: 0; bottom: 0; left: 0; height: 2px; visibility: hidden; } +.fsh-cad-offer.is-running .fsh-cad-offer-bar { visibility: visible; } + +.fsh-cad-dialog { width: min(520px, calc(100vw - 48px)); } +.fsh-cad-dialog .fsh-dialog-foot .fsh-btn { min-width: 96px; } +.fsh-cad-retess { display: grid; gap: var(--space-2); color: var(--text-primary); font-size: var(--fs-12); } +.fsh-cad-scope { display: grid; gap: 0; margin: 0; padding: 0; border: 0; } +.fsh-cad-scope legend { margin-bottom: var(--space-1); padding: 0; } +.fsh-cad-scope-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--space-2); height: var(--ctl-md); cursor: pointer; } +.fsh-cad-scope-row input { margin: 0; accent-color: var(--accent-color); } +.fsh-cad-scope-row:has(input:disabled) { color: var(--text-muted); cursor: default; } +.fsh-cad-scope-count { min-width: 10ch; color: var(--text-muted); text-align: right; } +.fsh-cad-scope-why { height: 1.5em; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-cad-now { margin-bottom: var(--space-2); } +.fsh-cad-estimate { height: 1.5em; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-cad-progress.is-indeterminate .fsh-cad-fill { width: 30%; transform: none; animation: fsh-cad-slide calc(var(--dur-slow) * 3) ease-in-out infinite; } +@keyframes fsh-cad-slide { from { transform: translateX(-100%); } to { transform: translateX(340%); } } diff --git a/frontend/src/ui/cad/index.ts b/frontend/src/ui/cad/index.ts new file mode 100644 index 00000000..c9d4f7b4 --- /dev/null +++ b/frontend/src/ui/cad/index.ts @@ -0,0 +1,87 @@ +import './cad.css'; +import type { ModuleContext } from '../../shell/app-shell'; +import { t } from '../../i18n'; +import { attachSheet } from './offer'; +import { cadIndex } from './parts'; +import { ESTIMATE, openRetessellate, RETESSELLATE } from './retess'; +import { worker } from './service'; +import { settingsPage } from './settings'; + +const SETTINGS_PAGE = 'cad'; + +export function mount(ctx: ModuleContext): void { + const { registry } = ctx; + registry.registerSettingsPage({ + id: SETTINGS_PAGE, title: 'CAD Import', icon: 'import', order: 62, group: 'Files', + keywords: ['STEP', 'IGES', 'STP', 'IGS', 'CAD', 'worker', 'OpenCascade', 'tessellation', 'quality', 'chord', 'angle'], + mount: settingsPage, + }); + registry.registerCommands([ + { + id: 'cad.settings', label: 'CAD Import Settings...', group: 'File', icon: 'settings', + description: 'The CAD worker that opens STEP and IGES files, and the default CAD quality.', + run: () => registry.runCommand('app.settings', { page: SETTINGS_PAGE }), + }, + { + id: 'cad.fetchWorker', label: 'Download the CAD Worker', group: 'File', icon: 'import', + description: 'Download and check the program that opens STEP and IGES files.', + enabled: () => !worker.running, + run: () => { registry.runCommand('app.settings', { page: SETTINGS_PAGE }); return worker.start(); }, + }, + { + id: 'cad.sheet', label: 'CAD Options in the Import Sheet', group: 'File', palette: false, + run: (args) => { + const select = args?.select, row = args?.row; + if (select instanceof HTMLSelectElement && row instanceof HTMLElement) attachSheet(select, row); + }, + }, + ]); + worker.onChange(() => registry.refreshState()); + + const engine = new Set<string>(); + let catalogueRead = false; + const readCatalogue = (): void => { + void ctx.api.catalogue({ timeoutMs: 8000 }).then((c) => { + engine.clear(); + for (const cmd of c.commands) if (typeof cmd.name === 'string') engine.add(cmd.name); + catalogueRead = true; + update(); + }, () => undefined); + }; + const why = (): string => { + if (catalogueRead && !engine.has(RETESSELLATE)) return t('This engine cannot re-tessellate CAD parts.'); + if (cadIndex.state !== 'ready') return ''; + if (!cadIndex.parts.size) return t('Nothing in this document came from a STEP or IGES file.'); + if (cadIndex.selection.length && !cadIndex.selected().length) return t('None of the selected parts came from a STEP or IGES file. Clear the selection to rebuild every CAD part.'); + return ''; + }; + const DESCRIPTION = 'Rebuild the meshes of parts imported from STEP or IGES at another quality, as one undo step.'; + let shown = ''; + const update = (): void => { + const reason = why(); + if (reason === shown) return; + shown = reason; + const cmd = registry.getCommand(RETESSELLATE); + if (cmd) cmd.description = reason || DESCRIPTION; + registry.refreshState(); + }; + registry.registerCommand({ + id: RETESSELLATE, label: 'Re-tessellate CAD Parts...', group: 'Scene', icon: 'refresh', description: DESCRIPTION, + enabled: () => { cadIndex.touch(); return why() === ''; }, + run: () => openRetessellate(() => engine.has(ESTIMATE)), + }); + registry.registerMenu({ id: 'scene', items: [{ command: RETESSELLATE, section: 3 }] }); + registry.registerMenu({ id: 'context.part', items: [{ command: RETESSELLATE, section: 5 }] }); + registry.registerMenu({ id: 'file', items: [{ command: 'cad.settings', section: 2 }] }); + if (!registry.getCommand('file.importCad')) registry.registerCommand({ + id: 'file.importCad', label: 'Import CAD (STEP, IGES)...', group: 'File', icon: 'import', + description: 'Choose STEP or IGES files to import; they open through the CAD worker.', + enabled: () => registry.getCommand('file.import') !== undefined, + run: () => registry.runCommand('file.import'), + }); + cadIndex.onChange(update); + registry.onCommandRun((cmd) => { if (cmd.id !== RETESSELLATE && !cmd.id.startsWith('cad.')) cadIndex.schedule(); }); + ctx.events.on('hello', readCatalogue); + ctx.events.on('resync', readCatalogue); + ctx.onReady(readCatalogue); +} diff --git a/frontend/src/ui/cad/offer.ts b/frontend/src/ui/cad/offer.ts new file mode 100644 index 00000000..7ab1170d --- /dev/null +++ b/frontend/src/ui/cad/offer.ts @@ -0,0 +1,81 @@ +import { el, q, setAttr, setClass, setDisabled, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { defaultQuality, isPreset, qualityName, toEngine, valuesText } from './quality'; +import { bytesText, stageText, worker } from './service'; + +export const CUSTOM_OPTION = 'custom'; + +function applyDefault(select: HTMLSelectElement): void { + const qv = defaultQuality(); + if (isPreset(qv)) { + if (Array.from(select.options).some((o) => o.value === qv)) select.value = qv; + return; + } + const opt = document.createElement('option'); + opt.value = CUSTOM_OPTION; + opt.textContent = qualityName(qv); + opt.dataset.quality = JSON.stringify(toEngine(qv)); + opt.title = valuesText(qv); + opt.setAttribute('data-no-i18n', ''); + select.appendChild(opt); + select.value = CUSTOM_OPTION; +} + +export function attachSheet(select: HTMLSelectElement, row: HTMLElement): void { + applyDefault(select); + const offer = el(`<div class="fsh-cad-offer" aria-live="polite"> +<span class="fsh-cad-offer-icon">${icon('warning', 14)}</span> +<span class="fsh-cad-offer-text" data-no-i18n></span> +<button type="button" class="fsh-btn is-sm fsh-cad-offer-btn"></button> +<span class="fsh-cad-offer-bar"><span class="fsh-cad-fill"></span></span> +</div>`); + const btn = q<HTMLButtonElement>(offer, 'button'); + btn.addEventListener('click', () => void worker.start()); + row.after(offer); + let started = false; + let asked = false; + + const paint = (): void => { + if (!row.isConnected) { off(); observer.disconnect(); return; } + const cad = !row.classList.contains('is-off'); + const job = worker.fetch; + const running = job.state === 'running'; + if (running) started = true; + if (cad && !worker.status && !asked) { asked = true; void worker.refresh(); } + const have = worker.installed || (started && job.state === 'done'); + const missing = worker.status !== null && !have; + const show = cad && (missing || running || (started && job.state !== 'idle')); + setClass(offer, 'is-on', show); + setClass(offer, 'is-running', running); + setClass(offer, 'is-ok', !running && have); + setClass(offer, 'is-error', !running && job.state === 'failed'); + let text = '', label = '', title = ''; + if (running) { + text = t('CAD worker: {stage}, {pct}%', { stage: stageText(job.stage), pct: Math.round(job.fraction * 100) }); + } else if (have) { + text = t('The CAD worker is installed. You can import this file now.'); + } else if (job.state === 'failed' && started) { + text = t('The download failed: {reason}', { reason: job.message || t('no reason was given') }); + label = t('Try Again'); + } else { + const p = worker.status?.published; + text = p && !p.available + ? t('STEP and IGES files need the CAD worker, and none is published for this computer.') + : t('STEP and IGES files need the CAD worker, which is not installed yet.'); + label = t('Download'); + title = p?.available ? t('{tag}, {size} unpacked, checked file by file', { tag: p.tag, size: bytesText(p.bytes ?? 0) }) : p?.reason ?? ''; + } + setText(q(offer, '.fsh-cad-offer-text'), text); + setText(btn, label); + setAttr(btn, 'data-hidden', label ? null : 'true'); + setTitle(btn, title); + setDisabled(btn, running || worker.status?.published.available === false); + setStyleVar(offer, '--fsh-cad-fraction', String(running ? job.fraction : 0)); + }; + + const off = worker.onChange(paint); + const observer = new MutationObserver(paint); + observer.observe(row, { attributes: true, attributeFilter: ['class'] }); + paint(); +} diff --git a/frontend/src/ui/cad/parts.ts b/frontend/src/ui/cad/parts.ts new file mode 100644 index 00000000..e1700288 --- /dev/null +++ b/frontend/src/ui/cad/parts.ts @@ -0,0 +1,139 @@ +import { api } from '../../shell/api'; +import { events } from '../../shell/events'; +import { parseQuality, type Quality } from './quality'; + +export interface CadPart { + id: string; + name: string; + source: string; + file: string; + quality: Quality | null; + qualityText: string; + triangles: number; +} + +export interface SceneNode { id: string; name: string; kind: string; parent: string | null; triangles: number } + +const PARTS = 'cad.parts'; +const SUMMARY = 'scene.summary'; +const REFRESH_EVENTS = ['scene.changed', 'document.changed', 'history.changed', 'selection.changed', 'hello', 'resync', 'ui.import.done', 'ui.cad.retessellated']; +const DEBOUNCE_MS = 250; +const STALE_MS = 800; + +type Obj = Record<string, unknown>; +const obj = (v: unknown): Obj => (v && typeof v === 'object' && !Array.isArray(v) ? v as Obj : {}); +const idText = (v: unknown): string => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : ''); + +const baseName = (p: string): string => p.split(/[\\/]/).pop() ?? p; +const text = (v: unknown): string => (typeof v === 'string' ? v : ''); + +function readParts(reply: unknown): Map<string, CadPart> { + const out = new Map<string, CadPart>(); + for (const raw of Array.isArray(obj(reply).parts) ? obj(reply).parts as unknown[] : []) { + const p = obj(raw); + const id = idText(p.id); + const source = text(p.source); + if (!id || !source) continue; + const quality = text(p.quality); + out.set(id, { + id, name: text(p.name), source, + file: baseName(text(p.path) || source), quality: parseQuality(quality), qualityText: quality, triangles: 0, + }); + } + return out; +} + +export type IndexState = 'unknown' | 'ready' | 'failed'; + +class CadIndex { + state: IndexState = 'unknown'; + error = ''; + parts = new Map<string, CadPart>(); + nodes = new Map<string, SceneNode>(); + selection: string[] = []; + private loadedAt = -Infinity; + private timer = 0; + private running: Promise<void> | null = null; + private again = false; + private readonly fns = new Set<() => void>(); + private wired = false; + + onChange(fn: () => void): () => void { + this.fns.add(fn); + this.wire(); + return () => { this.fns.delete(fn); }; + } + + private wire(): void { + if (this.wired) return; + this.wired = true; + for (const type of REFRESH_EVENTS) events.on(type, () => this.schedule()); + this.schedule(); + } + + schedule(delay = DEBOUNCE_MS): void { + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => void this.refresh(), delay); + } + + touch(): void { + if (!this.running && performance.now() - this.loadedAt > STALE_MS) this.schedule(0); + } + + refresh(): Promise<void> { + if (this.running) { this.again = true; return this.running; } + this.running = this.load().finally(() => { + this.running = null; + this.loadedAt = performance.now(); + for (const fn of this.fns) fn(); + if (this.again) { this.again = false; void this.refresh(); } + }); + return this.running; + } + + private async load(): Promise<void> { + let summary: Obj; + try { + summary = obj(await api.dispatch(SUMMARY, {}, { timeoutMs: 15000 })); + } catch (err) { + this.state = 'failed'; + this.error = err instanceof Error ? err.message : String(err); + return; + } + const nodes = new Map<string, SceneNode>(); + for (const raw of Array.isArray(summary.nodes) ? summary.nodes : []) { + const n = obj(raw); + const id = idText(n.id); + if (!id) continue; + nodes.set(id, { id, name: typeof n.name === 'string' ? n.name : '', kind: typeof n.kind === 'string' ? n.kind : '', parent: idText(n.parent) || null, triangles: typeof n.triangles === 'number' ? n.triangles : 0 }); + } + this.nodes = nodes; + this.selection = (Array.isArray(summary.selection) ? summary.selection : []).map(idText).filter(Boolean); + try { + this.parts = readParts(await api.dispatch(PARTS, {}, { timeoutMs: 15000 })); + this.state = 'ready'; + this.error = ''; + } catch (err) { + this.state = 'failed'; + this.error = err instanceof Error ? err.message : String(err); + return; + } + for (const p of this.parts.values()) p.triangles = nodes.get(p.id)?.triangles ?? 0; + for (const id of [...this.parts.keys()]) if (!nodes.has(id)) this.parts.delete(id); + } + + under(ids: readonly string[]): CadPart[] { + if (!ids.length) return []; + const chosen = new Set(ids); + const inside = (id: string): boolean => { + for (let cur: string | null = id, guard = 0; cur && guard < 4096; cur = this.nodes.get(cur)?.parent ?? null, guard++) if (chosen.has(cur)) return true; + return false; + }; + return [...this.parts.values()].filter((p) => inside(p.id)); + } + + selected(): CadPart[] { return this.under(this.selection); } + all(): CadPart[] { return [...this.parts.values()]; } +} + +export const cadIndex = new CadIndex(); diff --git a/frontend/src/ui/cad/picker.ts b/frontend/src/ui/cad/picker.ts new file mode 100644 index 00000000..4009a562 --- /dev/null +++ b/frontend/src/ui/cad/picker.ts @@ -0,0 +1,95 @@ +import { el, q, setChecked, setClass, setDisabled, setText, setValue } from '../../shell/dom'; +import { t } from '../../i18n'; +import { + ANGLE_MAX, ANGLE_MIN, CHORD_MAX_PERCENT, CHORD_MIN_PERCENT, PRESET_LABELS, PRESETS, + chordPercent, isPreset, valuesOf, valuesText, validCustom, type Quality, +} from './quality'; + +let seq = 0; + +export class QualityPicker { + readonly el: HTMLElement; + private readonly radios: HTMLInputElement[]; + private readonly chord: HTMLInputElement; + private readonly angle: HTMLInputElement; + private readonly line: HTMLElement; + private current: Quality; + + constructor(initial: Quality, private readonly changed: (q: Quality | null) => void, label = 'Quality') { + const name = `fsh-cad-q${++seq}`; + this.el = el(`<div class="fsh-cad-quality"> +<div class="fsh-cad-presets" role="radiogroup" aria-label="${t(label)}"></div> +<div class="fsh-cad-custom"> +<label class="fsh-cad-field"><span class="fsh-cad-field-label">${t('Chord')}</span><input class="fsh-input fsh-tabular" type="number" data-v="chord" min="${CHORD_MIN_PERCENT}" max="${CHORD_MAX_PERCENT}" step="0.001" inputmode="decimal"><span class="fsh-cad-unit">${t('% of the model size')}</span></label> +<label class="fsh-cad-field"><span class="fsh-cad-field-label">${t('Angle')}</span><input class="fsh-input fsh-tabular" type="number" data-v="angle" min="${ANGLE_MIN}" max="${ANGLE_MAX}" step="1" inputmode="decimal"><span class="fsh-cad-unit">${t('degrees')}</span></label> +</div> +<p class="fsh-cad-quality-line" role="status" data-no-i18n></p> +</div>`); + const group = q(this.el, '.fsh-cad-presets'); + for (const v of [...PRESETS, 'custom']) { + const text = v === 'custom' ? t('Custom') : t(PRESET_LABELS[v as keyof typeof PRESET_LABELS]); + const r = el(`<label class="fsh-cad-preset"><input type="radio" name="${name}" value="${v}"><span>${text}</span></label>`); + group.appendChild(r); + } + this.radios = Array.from(group.querySelectorAll<HTMLInputElement>('input')); + this.chord = q<HTMLInputElement>(this.el, '[data-v="chord"]'); + this.angle = q<HTMLInputElement>(this.el, '[data-v="angle"]'); + this.line = q(this.el, '.fsh-cad-quality-line'); + this.chord.setAttribute('aria-label', t('Chord as a percentage of the model size')); + this.angle.setAttribute('aria-label', t('Angle in degrees')); + this.current = initial; + group.addEventListener('change', () => { + const v = this.radios.find((r) => r.checked)?.value ?? 'medium'; + if (isPreset(v)) this.current = v; + else this.current = validCustom({ chord: Number(this.chord.value) / 100, angle: Number(this.angle.value) }) ?? { ...valuesOf(this.current) }; + this.paint(); + this.changed(this.value()); + }); + const edit = (): void => { + const v = this.value(); + if (v) this.current = v; + this.paint(true); + this.changed(this.value()); + }; + this.chord.addEventListener('input', edit); + this.angle.addEventListener('input', edit); + this.paint(); + } + + value(): Quality | null { + if (this.custom()) return validCustom({ chord: Number(this.chord.value) / 100, angle: Number(this.angle.value) }); + return this.current; + } + + set(qv: Quality): void { + this.current = qv; + this.paint(); + } + + setDisabled(off: boolean): void { + for (const r of this.radios) setDisabled(r, off); + setDisabled(this.chord, off || !this.custom()); + setDisabled(this.angle, off || !this.custom()); + } + + private custom(): boolean { return this.radios.find((r) => r.checked)?.value === 'custom'; } + + private paint(typing = false): void { + const cur = this.current; + const key = isPreset(cur) ? cur : 'custom'; + for (const r of this.radios) setChecked(r, r.value === key); + const custom = key === 'custom'; + setDisabled(this.chord, !custom); + setDisabled(this.angle, !custom); + if (!typing) { + const v = valuesOf(cur); + setValue(this.chord, String(chordPercent(v.chord))); + setValue(this.angle, String(v.angle)); + } + const val = this.value(); + setClass(this.line, 'is-error', val === null); + setText(this.line, val === null + ? t('Chord must be above 0 and at most {max}% of the model size; angle from {min} to {amax} degrees.', { max: CHORD_MAX_PERCENT, min: ANGLE_MIN, amax: ANGLE_MAX }) + : valuesText(val)); + } +} diff --git a/frontend/src/ui/cad/quality.ts b/frontend/src/ui/cad/quality.ts new file mode 100644 index 00000000..59879e75 --- /dev/null +++ b/frontend/src/ui/cad/quality.ts @@ -0,0 +1,75 @@ +import { events } from '../../shell/events'; +import { t } from '../../i18n'; + +export type Preset = 'draft' | 'medium' | 'high' | 'ultra'; +export interface Custom { chord: number; angle: number } +export type Quality = Preset | Custom; + +export const PRESETS: readonly Preset[] = ['draft', 'medium', 'high', 'ultra']; +export const PRESET_VALUES: Readonly<Record<Preset, Custom>> = { + draft: { chord: 0.002, angle: 30 }, + medium: { chord: 0.0005, angle: 20 }, + high: { chord: 0.00015, angle: 12 }, + ultra: { chord: 0.00005, angle: 6 }, +}; +export const PRESET_LABELS: Readonly<Record<Preset, string>> = { draft: 'Draft', medium: 'Medium', high: 'High', ultra: 'Ultra' }; + +export const CHORD_MIN_PERCENT = 0.001; +export const CHORD_MAX_PERCENT = 10; +export const ANGLE_MIN = 1; +export const ANGLE_MAX = 90; + +const KEY = 'formshot.cad.quality'; +export const DEFAULT_QUALITY: Quality = 'medium'; +export const QUALITY_EVENT = 'ui.cad.quality'; + +export const isPreset = (v: unknown): v is Preset => typeof v === 'string' && (PRESETS as readonly string[]).includes(v); + +export function validCustom(v: unknown): Custom | null { + if (!v || typeof v !== 'object') return null; + const o = v as Record<string, unknown>; + const chord = Number(o.chord), angle = Number(o.angle); + if (!Number.isFinite(chord) || !Number.isFinite(angle)) return null; + if (chord <= 0 || chord > CHORD_MAX_PERCENT / 100 || angle < ANGLE_MIN || angle > ANGLE_MAX) return null; + return { chord, angle }; +} + +export function parseQuality(v: unknown): Quality | null { + if (isPreset(v)) return v; + if (typeof v === 'string') { + const [c, a] = v.split(','); + return validCustom({ chord: c, angle: a }); + } + return validCustom(v); +} + +export function defaultQuality(): Quality { + try { + return parseQuality(JSON.parse(localStorage.getItem(KEY) ?? 'null')) ?? DEFAULT_QUALITY; + } catch { + return DEFAULT_QUALITY; + } +} + +export function setDefaultQuality(q: Quality): void { + try { localStorage.setItem(KEY, JSON.stringify(q)); } catch { return; } + events.emit({ type: QUALITY_EVENT, quality: q }); +} + +export const valuesOf = (q: Quality): Custom => (isPreset(q) ? PRESET_VALUES[q] : q); + +const fmt = (v: number, digits = 4): string => new Intl.NumberFormat(undefined, { maximumSignificantDigits: digits }).format(v); + +export const chordPercent = (chord: number): number => Number((chord * 100).toPrecision(4)); + +export function valuesText(q: Quality): string { + const v = valuesOf(q); + return t('Chord {chord}% of the model size, angle {angle} degrees', { chord: fmt(chordPercent(v.chord)), angle: fmt(v.angle, 3) }); +} + +export function qualityName(q: Quality): string { + if (isPreset(q)) return t(PRESET_LABELS[q]); + return t('Custom ({chord}%, {angle}°)', { chord: fmt(chordPercent(q.chord)), angle: fmt(q.angle, 3) }); +} + +export const toEngine = (q: Quality): string | Custom => (isPreset(q) ? q : { chord: q.chord, angle: q.angle }); diff --git a/frontend/src/ui/cad/retess.ts b/frontend/src/ui/cad/retess.ts new file mode 100644 index 00000000..3218baab --- /dev/null +++ b/frontend/src/ui/cad/retess.ts @@ -0,0 +1,194 @@ +import { api } from '../../shell/api'; +import { Dialog } from '../../shell/dialog'; +import { el, q, setChecked, setClass, setDisabled, setText, setTitle } from '../../shell/dom'; +import { events } from '../../shell/events'; +import { runCommand } from '../../shell/registry'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import { cadIndex, type CadPart } from './parts'; +import { QualityPicker } from './picker'; +import { defaultQuality, qualityName, toEngine, type Quality } from './quality'; +import { errorText } from './service'; + +export const RETESSELLATE = 'scene.retessellate'; +export const ESTIMATE = 'cad.estimate'; + +type Scope = 'selected' | 'all'; +type Obj = Record<string, unknown>; +const obj = (v: unknown): Obj => (v && typeof v === 'object' && !Array.isArray(v) ? v as Obj : {}); +const count = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : Array.isArray(v) ? v.length : null); +const number = (n: number): string => new Intl.NumberFormat().format(n); + +let open: Dialog | null = null; + +function qualityLine(parts: readonly CadPart[]): string { + const texts = new Set(parts.map((p) => p.qualityText)); + if (texts.size > 1) return t('Mixed'); + const p = parts[0]; + if (!p) return ''; + return p.quality ? qualityName(p.quality) : p.qualityText || t('Not recorded'); +} + +function sourcesLine(parts: readonly CadPart[]): string { + const files = [...new Set(parts.map((p) => p.file))]; + if (files.length === 1) return files[0]; + return t('{n} files', { n: files.length }); +} + +export function openRetessellate(hasEstimate: () => boolean): void { + if (open) return; + const d = new Dialog('Re-tessellate CAD Parts'); + open = d; + d.scrim.querySelector('.fsh-dialog')?.classList.add('fsh-cad-dialog'); + const root = el(`<div class="fsh-cad-retess"> +<fieldset class="fsh-cad-scope"> +<legend class="fsh-cad-head">Parts</legend> +<label class="fsh-cad-scope-row"><input type="radio" name="fsh-cad-scope" value="selected"><span class="fsh-cad-scope-name">Selected CAD parts</span><span class="fsh-cad-scope-count fsh-tabular" data-s="selected" data-no-i18n></span></label> +<label class="fsh-cad-scope-row"><input type="radio" name="fsh-cad-scope" value="all"><span class="fsh-cad-scope-name">All CAD parts</span><span class="fsh-cad-scope-count fsh-tabular" data-s="all" data-no-i18n></span></label> +<p class="fsh-cad-scope-why" data-no-i18n></p> +</fieldset> +<dl class="fsh-cad-facts fsh-cad-now"> +<div><dt>Source</dt><dd data-f="source" data-no-i18n></dd></div> +<div><dt>Quality now</dt><dd data-f="quality" data-no-i18n></dd></div> +<div><dt>Triangles now</dt><dd data-f="triangles" class="fsh-tabular" data-no-i18n></dd></div> +</dl> +<h3 class="fsh-cad-head">New quality</h3> +<div class="fsh-cad-picker"></div> +<p class="fsh-cad-estimate" data-no-i18n></p> +<div class="fsh-cad-progress is-indeterminate" aria-live="polite"><span class="fsh-cad-stage"></span><span class="fsh-cad-bar"><span class="fsh-cad-fill"></span></span><span class="fsh-cad-pct fsh-tabular" data-no-i18n></span></div> +<p class="fsh-cad-result" role="status" data-no-i18n></p> +</div>`); + d.body.appendChild(root); + const radios = Array.from(root.querySelectorAll<HTMLInputElement>('input[name="fsh-cad-scope"]')); + const progress = q(root, '.fsh-cad-progress'); + const result = q(root, '.fsh-cad-result'); + let scope: Scope | null = null; + let chosen = false; + let running = false; + let started = 0; + let tick = 0; + let estimateSeq = 0; + + const picker = new QualityPicker(defaultQuality(), () => { sync(); estimate(); }, 'New quality'); + q(root, '.fsh-cad-picker').appendChild(picker.el); + const closeBtn = d.action('Cancel', () => d.close()); + const applyBtn = d.action('Apply', () => void apply(), 'primary'); + + const inScope = (): CadPart[] => (scope === 'selected' ? cadIndex.selected() : cadIndex.all()); + + const estimate = (): void => { + const line = q(root, '.fsh-cad-estimate'); + const qv = picker.value(); + const parts = inScope(); + if (!hasEstimate() || !qv || !parts.length) { + setText(line, cadIndex.state === 'ready' && parts.length ? t('The engine gives no estimate; finer qualities take longer and make more triangles.') : ''); + return; + } + const seq = ++estimateSeq; + const args: Obj = { quality: toEngine(qv) }; + if (scope === 'selected') args.nodes = cadIndex.selection; + void api.dispatch<unknown>(ESTIMATE, args, { timeoutMs: 30000 }).then((raw) => { + if (seq !== estimateSeq) return; + const n = count(obj(raw).triangles); + setText(line, n === null ? '' : t('About {n} triangles afterwards.', { n: number(n) })); + }, () => { if (seq === estimateSeq) setText(line, ''); }); + }; + + const sync = (): void => { + const selected = cadIndex.selected(); + const all = cadIndex.all(); + const known = cadIndex.state === 'ready'; + if (!chosen && known) scope = selected.length ? 'selected' : 'all'; + if (scope === 'selected' && !selected.length && known) scope = 'all'; + for (const r of radios) { + setChecked(r, r.value === scope); + setDisabled(r, running || (r.value === 'selected' ? !selected.length : !all.length)); + } + const parts = (n: number): string => (n === 1 ? t('1 part') : t('{n} parts', { n: number(n) })); + setText(q(root, '[data-s="selected"]'), known ? parts(selected.length) : ''); + setText(q(root, '[data-s="all"]'), known ? parts(all.length) : ''); + let why = ''; + if (cadIndex.state === 'failed') why = t('The parts could not be read: {reason}', { reason: cadIndex.error }); + else if (known && !all.length) why = t('Nothing in this document came from a STEP or IGES file.'); + else if (known && !selected.length && cadIndex.selection.length) why = t('None of the selected parts came from a STEP or IGES file.'); + else if (known && !selected.length) why = t('Nothing is selected, so every CAD part is rebuilt.'); + setText(q(root, '.fsh-cad-scope-why'), why); + const list = inScope(); + setText(q(root, '[data-f="source"]'), sourcesLine(list)); + setText(q(root, '[data-f="quality"]'), qualityLine(list)); + setText(q(root, '[data-f="triangles"]'), list.length ? number(list.reduce((s, p) => s + p.triangles, 0)) : ''); + picker.setDisabled(running); + const qv = picker.value(); + setDisabled(applyBtn, running || !qv || !list.length); + setTitle(applyBtn, !list.length && why ? why : ''); + setText(closeBtn, running ? t('Close') : t('Cancel')); + }; + + const paintProgress = (): void => { + setClass(progress, 'is-on', running); + const secs = Math.round((performance.now() - started) / 1000); + setText(q(progress, '.fsh-cad-stage'), running ? t('Re-tessellating') : ''); + setText(q(progress, '.fsh-cad-pct'), running ? `${secs} s` : ''); + }; + + const apply = async (): Promise<void> => { + const qv: Quality | null = picker.value(); + const list = inScope(); + if (running || !qv || !list.length) return; + running = true; + started = performance.now(); + setText(result, ''); + setClass(result, 'is-error', false); + tick = window.setInterval(paintProgress, 500); + paintProgress(); + sync(); + const args: Obj = { quality: toEngine(qv) }; + if (scope === 'selected') args.nodes = cadIndex.selection; + try { + const reply = obj(await api.dispatch<unknown>(RETESSELLATE, args, { timeoutMs: 900000 })); + const partsDone = count(reply.parts) ?? list.length; + const before = count(reply.triangles_before), after = count(reply.triangles_after); + const warnings = Array.isArray(reply.warnings) ? reply.warnings.filter((w) => typeof w === 'string') as string[] : []; + const vars = { parts: partsDone, quality: qualityName(qv), before: number(before ?? 0), after: number(after ?? 0) }; + const counted = before !== null && after !== null; + let text = partsDone === 1 + ? (counted ? t('Re-tessellated 1 CAD part at {quality}: {before} to {after} triangles.', vars) : t('Re-tessellated 1 CAD part at {quality}.', vars)) + : (counted ? t('Re-tessellated {parts} CAD parts at {quality}: {before} to {after} triangles.', vars) : t('Re-tessellated {parts} CAD parts at {quality}.', vars)); + if (warnings.length) text = `${text} ${warnings.join(' ')}`; + for (const type of ['scene.changed', 'document.changed']) events.emit({ type }); + events.emit({ type: 'ui.cad.retessellated', parts: partsDone, quality: toEngine(qv) }); + toast(text, 'info', { label: 'Undo', run: () => { runCommand('edit.undo'); } }); + running = false; + window.clearInterval(tick); + d.close(); + return; + } catch (err) { + setClass(result, 'is-error', true); + setText(result, t('Could not re-tessellate: {reason}', { reason: errorText(err) })); + } + running = false; + window.clearInterval(tick); + paintProgress(); + sync(); + }; + + root.addEventListener('change', (e) => { + const target = e.target as HTMLElement; + if (!(target instanceof HTMLInputElement) || target.name !== 'fsh-cad-scope') return; + scope = target.value === 'selected' ? 'selected' : 'all'; + chosen = true; + sync(); + estimate(); + }); + const off = cadIndex.onChange(() => { if (!running) { sync(); estimate(); } }); + d.onClose = () => { + off(); + if (!running) window.clearInterval(tick); + open = null; + }; + sync(); + paintProgress(); + estimate(); + d.open(); + void cadIndex.refresh(); +} diff --git a/frontend/src/ui/cad/service.ts b/frontend/src/ui/cad/service.ts new file mode 100644 index 00000000..39eee939 --- /dev/null +++ b/frontend/src/ui/cad/service.ts @@ -0,0 +1,200 @@ +import { api, ApiError } from '../../shell/api'; +import { events, type EngineEvent } from '../../shell/events'; +import { t } from '../../i18n'; + +export interface WorkerStatus { + available: boolean; + path?: string; + tag?: string; + origin?: string; + cache?: string; + installed?: { tag: string; path: string }[]; + protocol?: number; + reason?: string; + code?: string; + occt?: string; + worker_protocol?: number; +} + +export interface Published { + tag: string; + release?: string; + triple: string; + source?: string; + available: boolean; + reason?: string; + archive?: string; + files?: number; + bytes?: number; + minimum_os?: string; +} + +export type FetchState = 'idle' | 'running' | 'done' | 'failed' | 'cancelled'; + +export interface FetchJob { + state: FetchState; + stage: string; + fraction: number; + message: string; + tag?: string; + done?: number; + total?: number; + cancellable?: boolean; +} + +export interface Status { + worker: WorkerStatus; + published: Published; + installed: { tag: string; path: string }[]; + cache: string; + fetch: FetchJob; +} + +export const STATUS_ROUTE = '/api/cad/worker'; +export const FETCH_ROUTE = '/api/cad/worker/fetch'; +export const WORKER_EVENT = 'cad.worker'; + +const STAGES: Record<string, string> = { + record: 'Reading the published record', + download: 'Downloading', + unpack: 'Unpacking', + verify: 'Checking every file', + done: 'Installed', +}; + +export function stageText(stage: string): string { + const known = STAGES[stage]; + if (known) return t(known); + return stage ? stage.charAt(0).toUpperCase() + stage.slice(1) : t('Starting'); +} + +export function bytesText(n: number): string { + if (!Number.isFinite(n) || n <= 0) return ''; + const units = ['B', 'KB', 'MB', 'GB']; + let v = n, i = 0; + while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; } + return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`; +} + +export function errorText(err: unknown): string { + if (err instanceof ApiError) { + if (err.status === 0) return t('The FormShot service is not reachable.'); + if (err.status === 403) return t('The service refused the request from this window.'); + return err.message; + } + return err instanceof Error ? err.message : String(err); +} + +const obj = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : {}); +const num = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined); + +function fetchOf(v: unknown): FetchJob { + const o = obj(v); + const state = typeof o.state === 'string' && ['idle', 'running', 'done', 'failed', 'cancelled'].includes(o.state) ? o.state as FetchState : 'idle'; + return { + state, + stage: typeof o.stage === 'string' ? o.stage : '', + fraction: Math.min(1, Math.max(0, num(o.fraction) ?? 0)), + message: typeof o.message === 'string' ? o.message : '', + tag: typeof o.tag === 'string' ? o.tag : undefined, + done: num(o.done) ?? num(o.bytes_done), + total: num(o.total) ?? num(o.bytes_total), + cancellable: o.cancellable === true, + }; +} + +type Listener = () => void; + +class WorkerStore { + status: Status | null = null; + error = ''; + fetch: FetchJob = { state: 'idle', stage: '', fraction: 0, message: '' }; + probe: WorkerStatus | null = null; + probing = false; + private loading: Promise<void> | null = null; + private readonly fns = new Set<Listener>(); + private wired = false; + + onChange(fn: Listener): () => void { + this.fns.add(fn); + this.wire(); + return () => { this.fns.delete(fn); }; + } + + private changed(): void { for (const fn of this.fns) fn(); } + + private wire(): void { + if (this.wired) return; + this.wired = true; + events.on(WORKER_EVENT, (e) => this.take(e)); + events.on('resync', () => { if (this.status) void this.refresh(); }); + } + + get installed(): boolean { return this.status?.worker.available === true; } + get running(): boolean { return this.fetch.state === 'running'; } + + refresh(): Promise<void> { + if (this.loading) return this.loading; + this.loading = api.get<Status>(STATUS_ROUTE, { timeoutMs: 30000 }).then((s) => { + this.status = { ...s, worker: obj(s.worker) as unknown as WorkerStatus, published: obj(s.published) as unknown as Published, installed: Array.isArray(s.installed) ? s.installed : [] }; + const job = fetchOf(s.fetch); + if (!(this.running && job.state !== 'running')) this.fetch = job; + this.error = ''; + }).catch((err: unknown) => { + this.error = errorText(err); + }).finally(() => { + this.loading = null; + this.changed(); + }); + return this.loading; + } + + private take(e: EngineEvent): void { + const before = this.fetch.state; + this.fetch = fetchOf(e); + this.changed(); + if (before === 'running' && this.fetch.state !== 'running') { + this.probe = null; + void this.refresh(); + } + } + + async start(): Promise<void> { + if (this.running) return; + this.fetch = { state: 'running', stage: 'record', fraction: 0, message: '' }; + this.changed(); + try { + const reply = obj(await api.post<unknown>(FETCH_ROUTE, {}, { timeoutMs: 60000 })); + const job = fetchOf(reply.fetch); + if (job.state !== 'idle' && this.fetch.state === 'running' && this.fetch.stage === 'record' && this.fetch.fraction === 0) this.fetch = job; + } catch (err) { + this.fetch = { state: 'failed', stage: '', fraction: 0, message: errorText(err) }; + } + this.changed(); + } + + async cancel(): Promise<void> { + if (!this.running || !this.fetch.cancellable) return; + try { + await api.del(FETCH_ROUTE, { timeoutMs: 15000 }); + } catch (err) { + this.fetch = { ...this.fetch, message: errorText(err) }; + this.changed(); + } + } + + async check(): Promise<void> { + if (this.probing) return; + this.probing = true; + this.changed(); + try { + this.probe = obj(await api.dispatch<unknown>('cad.status', { probe: true }, { timeoutMs: 120000 })) as unknown as WorkerStatus; + } catch (err) { + this.probe = { available: false, reason: errorText(err) }; + } + this.probing = false; + this.changed(); + } +} + +export const worker = new WorkerStore(); diff --git a/frontend/src/ui/cad/settings.ts b/frontend/src/ui/cad/settings.ts new file mode 100644 index 00000000..15fbd504 --- /dev/null +++ b/frontend/src/ui/cad/settings.ts @@ -0,0 +1,125 @@ +import { el, q, setAttr, setClass, setDisabled, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { QualityPicker } from './picker'; +import { defaultQuality, setDefaultQuality } from './quality'; +import { bytesText, stageText, worker } from './service'; + +const ORIGINS: Record<string, string> = { + env: 'Named by FORMSHOT_CAD_WORKER', + app: 'Beside the FormShot engine', + cache: 'Downloaded into the cache folder', +}; + +const number = (n: number): string => new Intl.NumberFormat().format(n); + +export function settingsPage(host: HTMLElement): () => void { + const root = el(`<div class="fsh-cad-settings"> +<p class="fsh-note fsh-cad-lede">STEP and IGES files are opened by FormCAD's kernel worker, a separate program that FormShot downloads once, checks file by file and keeps in your cache folder. Other model formats do not need it.</p> +<section class="fsh-cad-block" aria-labelledby="fsh-cad-worker-head"> +<h3 class="fsh-cad-head" id="fsh-cad-worker-head">CAD worker</h3> +<dl class="fsh-cad-facts"> +<div><dt>Status</dt><dd data-f="state"><span class="fsh-cad-dot"></span><span class="fsh-cad-state-text"></span></dd></div> +<div><dt>Version</dt><dd data-f="version" class="fsh-tabular" data-no-i18n></dd></div> +<div><dt>Program</dt><dd class="fsh-cad-path fsh-selectable" data-no-i18n><bdi data-f="path" dir="ltr"></bdi></dd></div> +<div><dt>Found in</dt><dd data-f="origin"></dd></div> +<div><dt>This computer</dt><dd data-f="platform" class="fsh-tabular" data-no-i18n></dd></div> +<div><dt>Published</dt><dd data-f="published" class="fsh-tabular" data-no-i18n></dd></div> +</dl> +<p class="fsh-cad-reason" role="status" data-no-i18n></p> +<div class="fsh-cad-actions"> +<button type="button" class="fsh-btn is-primary" data-a="fetch">${icon('import', 14)}<span class="fsh-cad-fetch-label">Download the CAD worker</span></button> +<button type="button" class="fsh-btn" data-a="cancel">Cancel</button> +<button type="button" class="fsh-btn" data-a="check">Check the worker</button> +<button type="button" class="fsh-icon-btn" data-a="refresh" aria-label="Read the status again" title="Read the status again">${icon('refresh', 16)}</button> +</div> +<div class="fsh-cad-progress" aria-live="polite"><span class="fsh-cad-stage"></span><span class="fsh-cad-bar"><span class="fsh-cad-fill"></span></span><span class="fsh-cad-pct fsh-tabular" data-no-i18n></span></div> +<p class="fsh-cad-detail fsh-tabular" data-no-i18n></p> +<p class="fsh-cad-result" role="status" data-no-i18n></p> +</section> +<section class="fsh-cad-block" aria-labelledby="fsh-cad-quality-head"> +<h3 class="fsh-cad-head" id="fsh-cad-quality-head">Default CAD quality</h3> +<p class="fsh-note fsh-cad-sub">How finely STEP and IGES surfaces become triangles when they are imported. Chord is the largest gap between a triangle and the true surface, as a share of the whole model's size; angle is the largest bend between neighbouring triangles. Finer settings take longer and make larger files. The import sheet starts with this choice; you can change it for one import there.</p> +<div class="fsh-cad-picker"></div> +</section> +</div>`); + const fetchBtn = q<HTMLButtonElement>(root, '[data-a="fetch"]'); + const cancelBtn = q<HTMLButtonElement>(root, '[data-a="cancel"]'); + const checkBtn = q<HTMLButtonElement>(root, '[data-a="check"]'); + const refreshBtn = q<HTMLButtonElement>(root, '[data-a="refresh"]'); + const progress = q(root, '.fsh-cad-progress'); + const field = (name: string): HTMLElement => q(root, `[data-f="${name}"]`); + + const picker = new QualityPicker(defaultQuality(), (v) => { if (v) setDefaultQuality(v); }, 'Default CAD quality'); + q(root, '.fsh-cad-picker').appendChild(picker.el); + + fetchBtn.addEventListener('click', () => void worker.start()); + cancelBtn.addEventListener('click', () => void worker.cancel()); + checkBtn.addEventListener('click', () => void worker.check()); + refreshBtn.addEventListener('click', () => void worker.refresh()); + + const paint = (): void => { + const s = worker.status; + const w = s?.worker; + const p = s?.published; + const job = worker.fetch; + const running = job.state === 'running'; + const known = s !== null; + const have = w?.available === true; + setClass(root, 'is-installed', have); + setText(q(root, '.fsh-cad-state-text'), !known ? (worker.error ? t('Unknown') : t('Reading...')) : have ? t('Installed') : t('Not installed')); + setAttr(q(root, '.fsh-cad-dot'), 'data-state', !known ? 'unknown' : have ? 'ok' : 'off'); + const probe = worker.probe; + let version = w?.tag ?? ''; + if (have && probe?.available && probe.occt) version = t('{tag}, OpenCascade {occt}, protocol {protocol}', { tag: version || probe.tag || '', occt: probe.occt, protocol: String(probe.worker_protocol ?? probe.protocol ?? '') }); + setText(field('version'), have ? version || t('Not named') : ''); + setText(field('path'), have ? w?.path ?? '' : ''); + setTitle(field('path'), have ? w?.path ?? '' : ''); + setText(field('origin'), have && w?.origin ? t(ORIGINS[w.origin] ?? w.origin) : ''); + setText(field('platform'), p?.triple ?? ''); + let pub = ''; + if (p?.available) pub = t('{tag}: {files} files, {size} unpacked', { tag: p.tag, files: number(p.files ?? 0), size: bytesText(p.bytes ?? 0) }); + else if (p) pub = t('{tag}: none for this computer', { tag: p.tag }); + setText(field('published'), pub); + + let reason = ''; + if (worker.error) reason = t('The status could not be read: {reason}', { reason: worker.error }); + else if (known && !have && w?.code === 'cad_worker_missing') reason = t('Not installed yet. FormShot looks for it in {folder}; download it here to open STEP and IGES files.', { folder: w.cache ?? s.cache }); + else if (known && !have) reason = w?.reason ? t('Not available: {reason}', { reason: w.reason }) : t('Not available.'); + if (!reason && known && p && !p.available && !have) reason = p.reason ?? ''; + if (probe && !probe.available && probe.reason) reason = t('The worker did not answer: {reason}', { reason: probe.reason }); + setText(q(root, '.fsh-cad-reason'), reason); + + setDisabled(fetchBtn, running || !known || p?.available === false); + setTitle(fetchBtn, p?.available === false ? p.reason ?? '' : ''); + setDisabled(cancelBtn, !running || !job.cancellable); + setTitle(cancelBtn, running && !job.cancellable ? t('The service cannot stop a download once it has started.') : ''); + setDisabled(checkBtn, !have || running || worker.probing); + setAttr(checkBtn, 'aria-busy', worker.probing ? 'true' : null); + setDisabled(refreshBtn, running); + + setClass(progress, 'is-on', running); + setText(q(progress, '.fsh-cad-stage'), running ? stageText(job.stage) : ''); + setStyleVar(progress, '--fsh-cad-fraction', String(running ? job.fraction : 0)); + setText(q(progress, '.fsh-cad-pct'), running ? `${Math.round(job.fraction * 100)}%` : ''); + let detail = ''; + if (running && job.done !== undefined) detail = job.total ? t('{done} of {total}', { done: bytesText(job.done), total: bytesText(job.total) }) : bytesText(job.done); + else if (running) detail = job.message; + setText(q(root, '.fsh-cad-detail'), detail); + + const result = q(root, '.fsh-cad-result'); + let text = ''; + if (job.state === 'done') text = job.message || t('The CAD worker is installed.'); + else if (job.state === 'failed') text = t('The download failed: {reason}', { reason: job.message || t('no reason was given') }); + else if (job.state === 'cancelled') text = t('The download was cancelled. Nothing was installed.'); + setClass(result, 'is-error', job.state === 'failed'); + setClass(result, 'is-ok', job.state === 'done'); + setText(result, text); + }; + + const off = worker.onChange(paint); + host.appendChild(root); + paint(); + void worker.refresh(); + return off; +} diff --git a/frontend/src/ui/graph/canvas.ts b/frontend/src/ui/graph/canvas.ts new file mode 100644 index 00000000..737ec07a --- /dev/null +++ b/frontend/src/ui/graph/canvas.ts @@ -0,0 +1,152 @@ +import { el, q, setStyleVar } from '../../shell/dom'; + +export interface View { x: number; y: number; z: number } +export interface Rect { x: number; y: number; w: number; h: number } + +export const MIN_ZOOM = 0.2; +export const MAX_ZOOM = 2.5; +const GRID = 24; +const SVG_NS = 'http://www.w3.org/2000/svg'; + +const clampZoom = (z: number): number => Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, z)); + +export class GraphCanvas { + readonly host: HTMLElement; + readonly layer: HTMLElement; + readonly nodes: HTMLElement; + readonly links: SVGSVGElement; + readonly band: HTMLElement; + view: View = { x: 0, y: 0, z: 1 }; + spaceHeld = false; + onView: (() => void) | null = null; + private panning = -1; + private panFrom = { x: 0, y: 0, vx: 0, vy: 0 }; + private readonly touches = new Map<number, { x: number; y: number }>(); + private pinch: { d: number; cx: number; cy: number } | null = null; + + constructor(parent: HTMLElement, label: string) { + this.host = el(`<div class="fsh-graph-canvas" tabindex="0" role="application"><div class="fsh-graph-layer"><div class="fsh-graph-nodes"></div></div><div class="fsh-graph-band" hidden></div></div>`); + this.host.setAttribute('aria-label', label); + this.layer = q(this.host, '.fsh-graph-layer'); + this.nodes = q(this.host, '.fsh-graph-nodes'); + this.band = q(this.host, '.fsh-graph-band'); + this.links = document.createElementNS(SVG_NS, 'svg'); + this.links.classList.add('fsh-graph-links'); + this.links.setAttribute('aria-hidden', 'true'); + this.layer.insertBefore(this.links, this.nodes); + parent.appendChild(this.host); + this.apply(); + this.listen(); + } + + toCanvas(clientX: number, clientY: number): [number, number] { + const r = this.host.getBoundingClientRect(); + return [(clientX - r.left - this.view.x) / this.view.z, (clientY - r.top - this.view.y) / this.view.z]; + } + + setView(v: View): void { + const z = clampZoom(v.z); + if (v.x === this.view.x && v.y === this.view.y && z === this.view.z) return; + this.view = { x: v.x, y: v.y, z }; + this.apply(); + this.onView?.(); + } + + zoomAt(clientX: number, clientY: number, factor: number): void { + const r = this.host.getBoundingClientRect(); + const px = clientX - r.left, py = clientY - r.top; + const z = clampZoom(this.view.z * factor); + const k = z / this.view.z; + this.setView({ x: px - (px - this.view.x) * k, y: py - (py - this.view.y) * k, z }); + } + + zoomCentre(factor: number): void { + const r = this.host.getBoundingClientRect(); + this.zoomAt(r.left + r.width / 2, r.top + r.height / 2, factor); + } + + frame(box: Rect | null, size?: { w: number; h: number }): void { + const w = size?.w ?? this.host.clientWidth, h = size?.h ?? this.host.clientHeight; + if (!box || w <= 0 || h <= 0) { this.setView({ x: w / 2, y: h / 2, z: 1 }); return; } + const pad = 48; + const z = clampZoom(Math.min(1, (w - pad * 2) / Math.max(1, box.w), (h - pad * 2) / Math.max(1, box.h))); + this.setView({ x: Math.round(w / 2 - (box.x + box.w / 2) * z), y: Math.round(h / 2 - (box.y + box.h / 2) * z), z }); + } + + private apply(): void { + const { x, y, z } = this.view; + const tr = `translate(${x}px, ${y}px) scale(${z})`; + if (this.layer.style.transform !== tr) this.layer.style.transform = tr; + const step = GRID * z; + setStyleVar(this.host, '--fsh-graph-grid', `${step}px`); + setStyleVar(this.host, '--fsh-graph-gx', `${x % (step * 4)}px`); + setStyleVar(this.host, '--fsh-graph-gy', `${y % (step * 4)}px`); + } + + private listen(): void { + const h = this.host; + h.addEventListener('pointerdown', (e) => { + if (e.pointerType === 'touch') { + this.touches.set(e.pointerId, { x: e.clientX, y: e.clientY }); + if (this.touches.size === 2) { this.beginPinch(); e.preventDefault(); e.stopPropagation(); return; } + } + const pan = e.button === 1 || (e.button === 0 && this.spaceHeld); + if (!pan) return; + this.panning = e.pointerId; + this.panFrom = { x: e.clientX, y: e.clientY, vx: this.view.x, vy: this.view.y }; + h.setPointerCapture(e.pointerId); + h.classList.add('is-panning'); + e.preventDefault(); + e.stopPropagation(); + }, true); + h.addEventListener('pointermove', (e) => { + if (this.touches.has(e.pointerId)) { + this.touches.set(e.pointerId, { x: e.clientX, y: e.clientY }); + if (this.pinch) { this.movePinch(); e.stopPropagation(); return; } + } + if (e.pointerId !== this.panning) return; + this.setView({ x: this.panFrom.vx + e.clientX - this.panFrom.x, y: this.panFrom.vy + e.clientY - this.panFrom.y, z: this.view.z }); + e.stopPropagation(); + }, true); + const end = (e: PointerEvent): void => { + this.touches.delete(e.pointerId); + if (this.touches.size < 2) this.pinch = null; + if (e.pointerId !== this.panning) return; + this.panning = -1; + h.classList.remove('is-panning'); + e.stopPropagation(); + }; + h.addEventListener('pointerup', end, true); + h.addEventListener('pointercancel', end, true); + h.addEventListener('auxclick', (e) => { if (e.button === 1) e.preventDefault(); }); + h.addEventListener('wheel', (e) => { + if ((e.target as HTMLElement).closest('.fsh-graph-scroll')) return; + e.preventDefault(); + const legacy = (e as WheelEvent & { wheelDeltaY?: number }).wheelDeltaY; + const mouse = e.deltaMode !== 0 || (e.deltaX === 0 && typeof legacy === 'number' && legacy !== 0 && legacy % 120 === 0); + if (e.ctrlKey || e.metaKey || (mouse && !e.shiftKey)) { + const d = e.deltaMode === 1 ? e.deltaY * 33 : e.deltaY; + this.zoomAt(e.clientX, e.clientY, Math.exp(-d * (e.ctrlKey && !mouse ? 0.01 : 0.0015))); + return; + } + const dx = e.shiftKey && e.deltaX === 0 ? e.deltaY : e.deltaX; + const dy = e.shiftKey && e.deltaX === 0 ? 0 : e.deltaY; + this.setView({ x: this.view.x - dx, y: this.view.y - dy, z: this.view.z }); + }, { passive: false }); + } + + private beginPinch(): void { + const [a, b] = [...this.touches.values()]; + this.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2 }; + } + + private movePinch(): void { + const p = this.pinch; + if (!p) return; + const [a, b] = [...this.touches.values()]; + const d = Math.hypot(a.x - b.x, a.y - b.y), cx = (a.x + b.x) / 2, cy = (a.y + b.y) / 2; + this.setView({ x: this.view.x + cx - p.cx, y: this.view.y + cy - p.cy, z: this.view.z }); + if (p.d > 0 && d > 0) this.zoomAt(cx, cy, d / p.d); + this.pinch = { d, cx, cy }; + } +} diff --git a/frontend/src/ui/graph/colour.ts b/frontend/src/ui/graph/colour.ts new file mode 100644 index 00000000..c6cc2ab6 --- /dev/null +++ b/frontend/src/ui/graph/colour.ts @@ -0,0 +1,37 @@ +import type { Rgb } from './model'; + +const TO_SRGB: readonly number[] = [1.70505, -0.62179, -0.08326, -0.13026, 1.1408, -0.01055, -0.024, -0.12897, 1.15297]; +const TO_ACESCG: readonly number[] = [0.6131, 0.33952, 0.04738, 0.07019, 0.91636, 0.01345, 0.02062, 0.10958, 0.8698]; + +function mul(m: readonly number[], c: Rgb): Rgb { + return [m[0] * c[0] + m[1] * c[1] + m[2] * c[2], m[3] * c[0] + m[4] * c[1] + m[5] * c[2], m[6] * c[0] + m[7] * c[1] + m[8] * c[2]]; +} + +const encode = (v: number): number => (v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055); +const decode = (v: number): number => (v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4)); +const clamp01 = (v: number): number => (Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : 0); + +export function displayRgb(acescg: Rgb): Rgb { + return mul(TO_SRGB, acescg).map((v) => clamp01(encode(clamp01(v)))) as Rgb; +} + +export function hexOf(acescg: Rgb): string { + return '#' + displayRgb(acescg).map((v) => Math.round(v * 255).toString(16).padStart(2, '0')).join(''); +} + +export function cssOf(acescg: Rgb): string { + const [r, g, b] = displayRgb(acescg).map((v) => Math.round(v * 255)); + return `rgb(${r} ${g} ${b})`; +} + +export function fromHex(hex: string): Rgb { + const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); + if (!m) return [0, 0, 0]; + const n = parseInt(m[1], 16); + const lin: Rgb = [decode(((n >> 16) & 255) / 255), decode(((n >> 8) & 255) / 255), decode((n & 255) / 255)]; + return mul(TO_ACESCG, lin).map((v) => Math.round(Math.max(0, v) * 1e5) / 1e5) as Rgb; +} + +export function lerpRgba(a: number[], b: number[], f: number): number[] { + return a.map((v, i) => v + ((b[i] ?? v) - v) * f); +} diff --git a/frontend/src/ui/graph/commit.ts b/frontend/src/ui/graph/commit.ts new file mode 100644 index 00000000..3661b22a --- /dev/null +++ b/frontend/src/ui/graph/commit.ts @@ -0,0 +1,101 @@ +import type { Workspace } from '../context'; +import { frameLater } from '../context'; + +export interface CommitResult { ok: boolean; error: string; graph: string } + +const SET = 'material.set_graph'; +const BARRIER = 'history.barrier'; +const IDLE_MS = 2000; + +export class Committer { + private chain: Promise<void> = Promise.resolve(); + private merging = false; + private pendingLive: Record<string, unknown> | null = null; + private queued = 0; + private sent = 0; + readonly own = new WeakSet<object>(); + onResult: ((r: CommitResult, live: boolean) => void) | null = null; + onIdle: (() => void) | null = null; + private idleTimer: number | undefined; + private readonly flushLive = frameLater(() => { + const g = this.pendingLive; + if (!g || this.queued > 0) { if (g) this.flushLive(); return; } + this.pendingLive = null; + this.send(g, true); + }); + + constructor(private readonly ws: Workspace, private readonly material: () => string | null) {} + + get busy(): boolean { return this.queued > 0 || this.pendingLive !== null || this.merging; } + get open(): boolean { return this.merging; } + get count(): number { return this.sent; } + + live(graph: Record<string, unknown>): void { + this.merging = true; + this.pendingLive = graph; + this.flushLive(); + window.clearTimeout(this.idleTimer); + this.idleTimer = window.setTimeout(() => { if (this.merging) this.onIdle?.(); }, IDLE_MS); + } + + commit(graph: Record<string, unknown>): void { + window.clearTimeout(this.idleTimer); + this.pendingLive = null; + const merged = this.merging; + this.send(graph, false, merged); + if (merged) { + this.merging = false; + this.enqueue(BARRIER, {}); + } + } + + private send(graph: Record<string, unknown>, live: boolean, merge = live): void { + const key = this.material(); + if (!key) return; + const text = JSON.stringify(graph); + this.sent++; + const args: Record<string, unknown> = merge ? { key, graph, merge: true } : { key, graph }; + this.enqueue(SET, args, (ok, error) => this.onResult?.({ ok, error, graph: text }, live)); + } + + private enqueue(name: string, args: Record<string, unknown>, done?: (ok: boolean, error: string) => void): void { + this.queued++; + this.own.add(args); + this.chain = this.chain.then(async () => { + try { + await this.ws.client.dispatch(name, args); + done?.(true, ''); + } catch (err) { + done?.(false, err instanceof Error ? err.message : String(err)); + } finally { + this.queued--; + } + }); + } + + run(name: string, args: Record<string, unknown>): Promise<unknown> { + return new Promise((resolve, reject) => { + this.queued++; + this.own.add(args); + this.chain = this.chain.then(async () => { + try { resolve(await this.ws.client.dispatch(name, args)); } catch (err) { reject(err); } finally { this.queued--; } + }); + }); + } + + idle(): Promise<void> { return this.chain; } +} + +export interface ErrorPlace { nodes: Set<number>; links: Array<[number, string, number, string]>; inputs: Array<[number, string]> } + +export function placeError(message: string): ErrorPlace { + const place: ErrorPlace = { nodes: new Set(), links: [], inputs: [] }; + const link = /(\d+) (\w+) -> (\d+) (\w+)/.exec(message) ?? /output (\d+) (\w+) cannot feed \w+ input (\d+) (\w+)/.exec(message); + if (link) place.links.push([Number(link[1]), link[2], Number(link[3]), link[4]]); + const fed = /input (\d+) (\w+) has more than one link/.exec(message); + if (fed) place.inputs.push([Number(fed[1]), fed[2]]); + for (const m of message.matchAll(/(?:node|nodes\.|cycle through node) ?(\d+)/g)) place.nodes.add(Number(m[1])); + const out = /output (\d+) \w+ cannot drive/.exec(message); + if (out) place.nodes.add(Number(out[1])); + return place; +} diff --git a/frontend/src/ui/graph/editor.ts b/frontend/src/ui/graph/editor.ts new file mode 100644 index 00000000..8dce614d --- /dev/null +++ b/frontend/src/ui/graph/editor.ts @@ -0,0 +1,681 @@ +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { GraphCanvas, type Rect, type View } from './canvas'; +import { el } from '../../shell/dom'; +import { icon, type IconName } from '../../shell/icons'; +import { comboOf } from '../../shell/registry'; +import { Committer, placeError, type CommitResult } from './commit'; +import { HelpPopover } from './help'; +import { Interaction } from './interact'; +import { actionFor, type ActionId } from './keys'; +import { groupOf, words } from './labels'; +import { LinkLayer, type Point } from './links'; +import { PickMenu, type PickItem } from './menu'; +import { + cloneNode, converts, emptyGraph, graphJson, graphSig, inputSpec, linkKey, materialInputType, MAX_NODES, newNode, nextId, OUTPUT_NODE, outputKey, + outputType, parseGraph, removeNodes, type Catalogue, type GLink, type GNode, type Graph, type SocketType, type SocketValue, +} from './model'; +import { pickImage } from './images'; +import { baseName, GraphSource, type MaterialData, type TextureInfo } from './source'; +import { StatusLine } from './status'; +import { NodeView, OutputView, shapeOf, type NodeHost } from './views'; +import { EditorWindow } from './window'; + +interface Session { view: View; out: Point } + +const PREVIEW_SIZE = 96; +const FOLLOW_DELAY_MS = 120; +const QUIET = /^(scene\.(summary|meshes|mesh_data)|material\.(preview_maps|node_kinds|types|program|get|labels)|render\.|view\.|camera\.|selection\.|app\.|file\.snapshot|history\.(barrier|begin_group|end_group))/; +const OUTSIDE_EVENTS = ['agent.activity', 'scene.changed', 'document.changed', 'history.changed', 'resync', 'hello']; + +export class GraphEditor implements NodeHost { + readonly win: EditorWindow; + readonly source: GraphSource; + material: string | null = null; + cat: Catalogue = { kinds: [], byId: new Map(), inputs: [] }; + graph: Graph = emptyGraph(); + canvas: GraphCanvas | null = null; + links: LinkLayer | null = null; + out: OutputView | null = null; + readonly views = new Map<number, NodeView>(); + readonly selection = new Set<number>(); + private textureList: TextureInfo[] = []; + private outPos: Point = [0, 0]; + private readonly sessions = new Map<string, Session>(); + private opening = 0; + readonly committer: Committer; + readonly status: StatusLine; + readonly menu: PickMenu; + readonly help: HelpPopover; + interaction: Interaction | null = null; + private good = ''; + private goodSig = ''; + private failed = false; + private previewToken = 0; + private readTimer: number | undefined; + private reading = false; + + constructor(readonly ws: Workspace) { + this.win = new EditorWindow(ws.ctx.slots.overlayRoot); + this.source = new GraphSource(ws); + this.status = new StatusLine(this.win.status, () => this.revert()); + this.committer = new Committer(ws, () => this.material); + this.committer.onResult = (r, live) => this.result(r, live); + this.committer.onIdle = () => this.finish(); + this.menu = new PickMenu(ws.ctx.slots.overlayRoot); + this.help = new HelpPopover(this.win.root); + this.tools(); + this.win.root.addEventListener('keydown', (e) => this.key(e)); + this.win.root.addEventListener('keyup', (e) => { if (e.key === ' ') this.space(false); }); + window.addEventListener('blur', () => this.space(false)); + this.win.onClose = () => { + this.space(false); + this.menu.close(false); + this.help.close(false); + if (this.committer.open) this.finish(); + this.remember(); + }; + ws.client.onDispatch((n) => { + if (this.committer.own.has(n.args) || QUIET.test(n.name)) return; + this.dirty(); + }); + for (const type of OUTSIDE_EVENTS) ws.ctx.events.on(type, () => this.dirty()); + } + + private tools(): void { + const button = (name: IconName, label: string, keys: string, run: () => void): void => { + const b = el<HTMLButtonElement>(`<button type="button" class="fsh-icon-btn">${icon(name, 16)}</button>`); + b.setAttribute('aria-label', t(label)); + b.title = `${t(label)} (${keys})`; + b.addEventListener('click', run); + this.win.tools.appendChild(b); + }; + button('plus', 'Add a node', 'Tab', () => { + const r = this.canvas?.host.getBoundingClientRect(); + if (r) this.openAddMenu(r.left + r.width / 2 - 130, r.top + 24); + }); + button('fit', 'Frame all nodes', 'F', () => this.frameAll()); + button('help', 'Show these keys', '?', () => this.help.toggle()); + } + + private space(on: boolean): void { + if (!this.canvas || this.canvas.spaceHeld === on) return; + this.canvas.spaceHeld = on; + this.canvas.host.classList.toggle('is-space', on); + } + + textures(): TextureInfo[] { return this.textureList; } + + async open(material: string): Promise<void> { + const token = ++this.opening; + if (this.win.open && this.material === material) { this.focus(); return; } + try { + const cat = await this.source.catalogue(); + const data = await this.source.read(material); + if (token !== this.opening) return; + this.remember(); + const fresh = this.material !== material || !this.canvas; + this.cat = cat; + this.win.setTitle(data.name ? t('Node editor: {name}', { name: data.name }) : t('Node editor')); + this.win.show(); + this.ensureCanvas(); + if (fresh) this.reset(); + this.material = material; + this.textureList = data.textures; + this.adopt(data.graph); + if (fresh) this.restore(material); + this.refreshPreview(); + this.focus(); + } catch (err) { + this.ws.ctx.toast(t('The node editor could not open: {reason}', { reason: err instanceof Error ? err.message : String(err) }), 'error'); + } + } + + focus(): void { this.canvas?.host.focus({ preventScroll: true }); } + + private ensureCanvas(): void { + if (this.canvas) return; + this.canvas = new GraphCanvas(this.win.body, t('Node canvas')); + this.links = new LinkLayer(this.canvas.links); + this.out = new OutputView(this.cat); + this.canvas.nodes.appendChild(this.out.el); + this.out.measure(); + this.interaction = new Interaction(this); + this.canvas.onView = () => this.status.setZoom(this.canvas?.view.z ?? 1); + this.status.setZoom(1); + } + + private reset(): void { + for (const v of this.views.values()) v.el.remove(); + this.views.clear(); + for (const k of this.links?.keys() ?? []) this.links?.remove(k); + this.selection.clear(); + this.graph = emptyGraph(); + } + + private remember(): void { + if (this.material && this.canvas) this.sessions.set(this.material, { view: { ...this.canvas.view }, out: [...this.outPos] }); + } + + private restore(material: string): void { + const s = this.sessions.get(material); + if (s) { + this.outPos = [...s.out]; + this.placeOutput(); + this.canvas?.setView(s.view); + return; + } + const b = this.bounds(false); + this.outPos = b ? [Math.round(b.x + b.w + 96), Math.round(b.y)] : [240, -120]; + this.placeOutput(); + this.frameAll(); + } + + private adopt(g: Graph): void { + this.good = JSON.stringify(graphJson(g)); + this.goodSig = graphSig(g); + this.apply(g); + this.showError(null); + } + + apply(next: Graph): void { + const g = next; + for (const [id, v] of [...this.views]) { + const n = g.nodes.get(id); + if (!n || v.shape !== shapeOf(n)) { v.el.remove(); this.views.delete(id); this.selection.delete(id); } + } + for (const n of g.nodes.values()) { + let v = this.views.get(n.id); + if (!v) { + v = new NodeView(this, n); + this.canvas?.nodes.insertBefore(v.el, this.out?.el ?? null); + v.place(n.position[0], n.position[1]); + v.measure(); + this.views.set(n.id, v); + } else { + v.update(n); + v.place(n.position[0], n.position[1]); + } + v.setSelected(this.selection.has(n.id)); + } + this.graph = g; + this.relinkAll(); + } + + private placeOutput(): void { + if (this.out?.place(this.outPos[0], this.outPos[1])) this.relinkAll(); + } + + socketPos(node: number, dir: 'in' | 'out', name: string): Point | null { + const v = node === OUTPUT_NODE ? this.out : this.views.get(node); + return v?.socketAt(dir, name) ?? null; + } + + private nodeName(id: number): string { + const n = this.graph.nodes.get(id); + return n ? t(this.cat.byId.get(n.kind)?.label ?? n.kind) : ''; + } + + private drawLink(l: GLink): void { + const a = this.socketPos(l.from[0], 'out', l.from[1]); + const b = this.socketPos(l.to[0], 'in', l.to[1]); + const from = this.graph.nodes.get(l.from[0]); + if (!a || !b || !from) { this.links?.remove(linkKey(l)); return; } + this.links?.set(linkKey(l), a, b, outputType(this.cat, from, l.from[1]) ?? 'float'); + } + + private drawOutput(input: string, r: [number, string]): void { + const key = outputKey(input, r); + const a = this.socketPos(r[0], 'out', r[1]); + const b = this.socketPos(OUTPUT_NODE, 'in', input); + const from = this.graph.nodes.get(r[0]); + if (!a || !b || !from) { this.links?.remove(key); return; } + this.links?.set(key, a, b, outputType(this.cat, from, r[1]) ?? materialInputType(this.cat, input)); + } + + relinkAll(): void { + const want = new Set<string>(); + for (const l of this.graph.links) { want.add(linkKey(l)); this.drawLink(l); } + for (const [input, r] of this.graph.outputs) { want.add(outputKey(input, r)); this.drawOutput(input, r); } + for (const k of this.links?.keys() ?? []) if (!want.has(k)) this.links?.remove(k); + this.markLinked(); + this.status.setCount(this.graph.nodes.size, want.size); + } + + relinkNodes(ids: ReadonlySet<number>): void { + for (const l of this.graph.links) if (ids.has(l.from[0]) || ids.has(l.to[0])) this.drawLink(l); + for (const [input, r] of this.graph.outputs) if (ids.has(r[0]) || ids.has(OUTPUT_NODE)) this.drawOutput(input, r); + } + + private markLinked(): void { + const fed = new Map<string, string>(); + for (const l of this.graph.links) fed.set(`${l.to[0]}:${l.to[1]}`, this.nodeName(l.from[0])); + for (const [id, v] of this.views) { + for (const s of v.sockets.values()) if (s.dir === 'in') v.setLinked(s.name, fed.has(`${id}:${s.name}`), fed.get(`${id}:${s.name}`) ?? ''); + } + for (const i of this.cat.inputs) { + const r = this.graph.outputs.get(i.name); + this.out?.setLinked(i.name, r !== undefined, r ? this.nodeName(r[0]) : ''); + } + } + + bounds(withOutput = true): Rect | null { + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + const add = (x: number, y: number, w: number, h: number): void => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x + w); y1 = Math.max(y1, y + h); }; + for (const v of this.views.values()) add(v.x, v.y, v.w, v.h); + if (withOutput && this.out) add(this.out.x, this.out.y, this.out.w, this.out.h); + return Number.isFinite(x0) ? { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } : null; + } + + frameAll(): void { this.canvas?.frame(this.bounds(true)); } + + editInput(node: number, socket: string, value: SocketValue, live: boolean): void { + const n = this.graph.nodes.get(node); + if (!n) return; + n.inputs[socket] = value; + this.changed(live); + } + + editSetting(node: number, name: string, value: unknown, live: boolean): void { + const n: GNode | undefined = this.graph.nodes.get(node); + if (!n) return; + const shape = shapeOf(n); + n.settings[name] = value; + if (name === 'stops' && Array.isArray(value)) value.sort((a, b) => Number((a as { position: number }).position) - Number((b as { position: number }).position)); + if (shapeOf(n) !== shape) { + const ty = outputType(this.cat, n, 'value'); + this.graph.links = this.graph.links.filter((l) => l.from[0] !== node || !ty || converts(ty, this.inputType(l.to[0], l.to[1]))); + for (const [k, r] of [...this.graph.outputs]) if (r[0] === node && ty && !converts(ty, materialInputType(this.cat, k))) this.graph.outputs.delete(k); + this.apply(this.graph); + } else if (name === 'interpolation') this.views.get(node)?.update(n); + this.changed(live); + } + + inputType(node: number, socket: string): SocketType { + if (node === OUTPUT_NODE) return materialInputType(this.cat, socket); + const n = this.graph.nodes.get(node); + return (n && inputSpec(this.cat, n, socket)?.ty) ?? 'float'; + } + + addImage(node: number): void { void this.addImageTo(node); } + + private async addImageTo(node: number): Promise<void> { + let path: string | null; + try { path = await pickImage(); } catch (err) { this.ws.ctx.toast(err instanceof Error ? err.message : String(err), 'error'); return; } + if (!path || !this.graph.nodes.has(node)) return; + const label = t('Add an image to a node'); + try { + if (this.ws.client.has('history.begin_group')) void this.committer.run('history.begin_group', { label }).catch(() => undefined); + const reply = await this.committer.run('texture.add', { texture: { path, role: 'other', uv_set: 0, colour_space: null } }) as { created?: unknown[] } | null; + const key = Array.isArray(reply?.created) ? reply?.created[0] : undefined; + const n = this.graph.nodes.get(node); + if (key === undefined || !n) throw new Error(t('The engine did not add the image.')); + this.textureList = [...this.textureList.filter((x) => x.key !== String(key)), { key: String(key), path, name: baseName(path) }].sort((a, b) => Number(a.key) - Number(b.key)); + for (const v of this.views.values()) v.refreshTextures(); + n.settings.texture = Number(key); + this.views.get(node)?.update(n); + this.finish(); + } catch (err) { + this.ws.ctx.toast(err instanceof Error ? err.message : String(err), 'error'); + } finally { + if (this.ws.client.has('history.end_group')) void this.committer.run('history.end_group', {}).catch(() => undefined); + } + } + + private dirty(): void { + if (!this.win.open || !this.material) return; + window.clearTimeout(this.readTimer); + this.readTimer = window.setTimeout(() => { void this.follow(); }, FOLLOW_DELAY_MS); + } + + private async follow(): Promise<void> { + const material = this.material; + if (!material || !this.win.open) return; + if (this.reading || this.committer.busy || this.interaction?.active) { this.dirty(); return; } + this.reading = true; + const before = this.committer.count; + let data: MaterialData; + try { + data = await this.source.read(material); + } catch (err) { + this.reading = false; + if (this.material !== material) return; + const gone = !(this.ws.client.summary?.materials ?? []).some((m) => String(m.key) === material); + if (gone) { this.win.close(); this.ws.ctx.toast(t('The material was removed, so the node editor closed.')); } + else this.ws.client.message(err instanceof Error ? err.message : String(err), 'error'); + return; + } + this.reading = false; + if (this.material !== material) return; + if (this.committer.count !== before || this.committer.busy || this.interaction?.active) { this.dirty(); return; } + if (data.name) this.win.setTitle(t('Node editor: {name}', { name: data.name })); + const texSig = (l: TextureInfo[]): string => l.map((x) => `${x.key}=${x.path}`).join('|'); + if (texSig(data.textures) !== texSig(this.textureList)) { + this.textureList = data.textures; + for (const v of this.views.values()) v.refreshTextures(); + } + const sig = graphSig(data.graph); + if (sig === this.goodSig) return; + const keep = new Set([...this.selection].filter((id) => id === OUTPUT_NODE || data.graph.nodes.has(id))); + this.adopt(data.graph); + this.select(keep); + this.refreshPreview(); + } + + select(ids: ReadonlySet<number>): void { + for (const [id, v] of this.views) v.setSelected(ids.has(id)); + this.out?.setSelected(ids.has(OUTPUT_NODE)); + this.selection.clear(); + for (const id of ids) this.selection.add(id); + } + + position(id: number): Point | null { + if (id === OUTPUT_NODE) return [...this.outPos]; + const n = this.graph.nodes.get(id); + return n ? [n.position[0], n.position[1]] : null; + } + + moveTo(id: number, p: Point): void { + if (id === OUTPUT_NODE) { this.outPos = [p[0], p[1]]; this.out?.place(p[0], p[1]); return; } + const n = this.graph.nodes.get(id); + if (!n) return; + n.position = [p[0], p[1]]; + this.views.get(id)?.place(p[0], p[1]); + } + + finishMove(ids: number[]): void { + this.relinkNodes(new Set(ids)); + if (ids.some((id) => id !== OUTPUT_NODE)) this.finish(); + } + + connect(from: [number, string], toNode: number, toName: string, picked: string | null): void { + if (picked) this.dropLink(picked); + if (toNode === OUTPUT_NODE) this.graph.outputs.set(toName, [from[0], from[1]]); + else { + this.graph.links = this.graph.links.filter((l) => !(l.to[0] === toNode && l.to[1] === toName)); + this.graph.links.push({ from: [from[0], from[1]], to: [toNode, toName] }); + } + this.relinkAll(); + this.finish(); + } + + disconnect(key: string): void { + this.dropLink(key); + this.relinkAll(); + this.finish(); + } + + private dropLink(key: string): void { + this.graph.links = this.graph.links.filter((l) => linkKey(l) !== key); + for (const [k, r] of [...this.graph.outputs]) if (outputKey(k, r) === key) this.graph.outputs.delete(k); + } + + addNode(kind: string, at: Point): number | null { + const spec = this.cat.byId.get(kind); + if (!spec) return null; + if (this.graph.nodes.size >= MAX_NODES) { this.ws.ctx.toast(t('A graph holds at most {n} nodes.', { n: MAX_NODES }), 'error'); return null; } + const id = nextId(this.graph); + this.graph.nodes.set(id, newNode(spec, id, [Math.round(at[0]), Math.round(at[1])])); + this.apply(this.graph); + this.select(new Set([id])); + this.views.get(id)?.el.focus({ preventScroll: true }); + this.finish(); + return id; + } + + openAddMenu(clientX: number, clientY: number): void { + const canvas = this.canvas; + if (!canvas) return; + const at = canvas.toCanvas(clientX, clientY); + const items: PickItem[] = this.cat.kinds.map((k) => ({ id: k.id, label: t(k.label), group: t(groupOf(k)) })); + this.menu.show(t('Add a node'), items, clientX, clientY, (item) => { this.addNode(item.id, at); }); + } + + changed(live: boolean): void { + if (live) { this.committer.live(graphJson(this.graph)); return; } + this.finish(); + } + + finish(): void { + if (!this.material) return; + if (graphSig(this.graph) === this.goodSig && !this.failed && !this.committer.open) return; + this.committer.commit(graphJson(this.graph)); + } + + private result(r: CommitResult, live: boolean): void { + if (r.ok) { + if (live) return; + this.good = r.graph; + this.goodSig = graphSig(parseGraph(JSON.parse(r.graph))); + this.showError(null); + this.refreshPreview(); + return; + } + this.showError(r.error); + } + + private showError(message: string | null): void { + const place = message ? placeError(message) : { nodes: new Set<number>(), links: [], inputs: [] }; + this.failed = message !== null; + for (const [a, , b] of place.links) { place.nodes.add(a); place.nodes.add(b); } + for (const [b] of place.inputs) place.nodes.add(b); + for (const [id, v] of this.views) v.setError(place.nodes.has(id) ? message : null); + for (const k of this.links?.keys() ?? []) this.links?.setClass(k, 'is-error', false); + for (const [a, as, b, bs] of place.links) this.links?.setClass(linkKey({ from: [a, as], to: [b, bs] }), 'is-error', true); + for (const [b, bs] of place.inputs) for (const l of this.graph.links) if (l.to[0] === b && l.to[1] === bs) this.links?.setClass(linkKey(l), 'is-error', true); + this.status.error(message ? t('Not applied: {reason}. The material keeps its last working graph.', { reason: message }) : ''); + } + + revert(): void { + if (!this.good) return; + this.apply(parseGraph(JSON.parse(this.good))); + this.showError(null); + } + + refreshPreview(): void { + const material = this.material; + if (!material || !this.out) return; + const token = ++this.previewToken; + void this.source.preview(material, PREVIEW_SIZE).then((src) => { + if (token === this.previewToken && this.material === material) void this.out?.setPreview(src); + }).catch(() => undefined); + } + + private key(e: KeyboardEvent): void { + if (e.defaultPrevented || e.isComposing) return; + const target = e.target as HTMLElement; + const node = target.closest<HTMLElement>('.fsh-graph-node'); + const onSurface = target === this.canvas?.host || target === node; + if (e.key === 'Escape') { + if (node && target !== node) node.focus({ preventScroll: true }); + else if (node) this.focus(); + else if (this.selection.size && target === this.canvas?.host) this.select(new Set()); + else this.win.close(); + e.preventDefault(); + e.stopPropagation(); + return; + } + if (e.key === ' ' && onSurface) { this.space(true); e.preventDefault(); e.stopPropagation(); return; } + if (!onSurface) return; + const combo = comboOf(e); + const action = e.key === '?' ? 'help' : actionFor(combo); + if (!action || !this.run(action, combo, node)) return; + e.preventDefault(); + e.stopPropagation(); + } + + private run(action: ActionId, combo: string, node: HTMLElement | null): boolean { + const focused = node ? Number(node.dataset.node) : null; + switch (action) { + case 'add': { + const p = this.interaction?.pointer; + const r = this.canvas?.host.getBoundingClientRect(); + if (p) this.openAddMenu(p[0], p[1]); + else if (r) this.openAddMenu(r.left + r.width / 2, r.top + r.height / 2); + return true; + } + case 'links': if (focused !== null) this.openLinksMenu(focused); return focused !== null; + case 'delete': this.deleteSelection(); return true; + case 'duplicate': this.duplicate(); return true; + case 'copy': this.copy(); return true; + case 'cut': this.copy(); this.deleteSelection(); return true; + case 'paste': this.paste(); return true; + case 'selectAll': this.select(new Set(this.views.keys())); return true; + case 'frame': this.frameAll(); return true; + case 'zoomIn': this.canvas?.zoomCentre(1.25); return true; + case 'zoomOut': this.canvas?.zoomCentre(0.8); return true; + case 'zoomReset': { const v = this.canvas?.view; if (v) this.canvas?.zoomCentre(1 / v.z); return true; } + case 'next': this.focusNext(focused, combo); return true; + case 'nudge': this.nudge(combo); return true; + case 'enter': { + const first = node?.querySelector<HTMLElement>('select, input, .fsh-ws-num[tabindex="0"], .fsh-graph-ramp-stop[tabindex="0"], button:not(.fsh-graph-sock)'); + first?.focus(); + return first !== null && first !== undefined; + } + case 'help': this.help.toggle(); return true; + default: return false; + } + } + + private focusNext(from: number | null, combo: string): void { + const all: Array<[number, number, number]> = [...this.views.values()].map((v) => [v.id, v.x + v.w / 2, v.y + v.h / 2]); + if (this.out) all.push([OUTPUT_NODE, this.out.x + this.out.w / 2, this.out.y + this.out.h / 2]); + if (!all.length) return; + const cur = all.find((a) => a[0] === from); + let pick: [number, number, number] | undefined; + if (!cur) pick = all.sort((a, b) => a[1] - b[1] || a[2] - b[2])[0]; + else { + const dir = combo === 'Left' ? [-1, 0] : combo === 'Right' ? [1, 0] : combo === 'Up' ? [0, -1] : [0, 1]; + let best = Infinity; + for (const a of all) { + if (a[0] === cur[0]) continue; + const dx = a[1] - cur[1], dy = a[2] - cur[2]; + const along = dx * dir[0] + dy * dir[1]; + if (along <= 0) continue; + const score = along + Math.abs(dx * dir[1] - dy * dir[0]) * 2; + if (score < best) { best = score; pick = a; } + } + } + if (!pick) return; + this.select(new Set([pick[0]])); + const v = pick[0] === OUTPUT_NODE ? this.out : this.views.get(pick[0]); + v?.el.focus({ preventScroll: true }); + this.reveal(pick[0]); + } + + private reveal(id: number): void { + const c = this.canvas, v = id === OUTPUT_NODE ? this.out : this.views.get(id); + if (!c || !v) return; + const { x, y, z } = c.view, w = c.host.clientWidth, h = c.host.clientHeight; + const sx = v.x * z + x, sy = v.y * z + y; + let nx = x, ny = y; + if (sx < 16) nx += 16 - sx; else if (sx + v.w * z > w - 16) nx -= sx + v.w * z - (w - 16); + if (sy < 16) ny += 16 - sy; else if (sy + v.h * z > h - 16) ny -= sy + v.h * z - (h - 16); + c.setView({ x: nx, y: ny, z }); + } + + private nudge(combo: string): void { + const step = 24; + const d: Point = combo.endsWith('Left') ? [-step, 0] : combo.endsWith('Right') ? [step, 0] : combo.endsWith('Up') ? [0, -step] : [0, step]; + const ids = [...this.selection]; + if (!ids.length) return; + for (const id of ids) { const p = this.position(id); if (p) this.moveTo(id, [p[0] + d[0], p[1] + d[1]]); } + this.finishMove(ids); + } + + deleteSelection(): void { + const ids = new Set([...this.selection].filter((id) => id !== OUTPUT_NODE && this.graph.nodes.has(id))); + if (!ids.size) return; + removeNodes(this.graph, ids); + this.apply(this.graph); + this.select(new Set()); + this.focus(); + this.finish(); + } + + private grab(): Clip | null { + const ids = [...this.selection].filter((id) => this.graph.nodes.has(id)); + if (!ids.length) return null; + const set = new Set(ids); + return { + nodes: ids.map((id) => cloneNode(this.graph.nodes.get(id) as GNode)), + links: this.graph.links.filter((l) => set.has(l.from[0]) && set.has(l.to[0])).map((l) => ({ from: [...l.from] as [number, string], to: [...l.to] as [number, string] })), + }; + } + + copy(): void { + const c = this.grab(); + if (c) { clipboard = c; this.status.note(t('Copied {n} nodes.', { n: c.nodes.length }), true); } + } + + paste(): void { + if (clipboard) this.place(clipboard, null); + } + + duplicate(): void { + const c = this.grab(); + if (c) this.place(c, [24, 24]); + } + + private place(clip: Clip, offset: Point | null): void { + if (this.graph.nodes.size + clip.nodes.length > MAX_NODES) { this.ws.ctx.toast(t('A graph holds at most {n} nodes.', { n: MAX_NODES }), 'error'); return; } + let d: Point = offset ?? [24, 24]; + const p = this.interaction?.pointer; + if (!offset && p && this.canvas) { + const at = this.canvas.toCanvas(p[0], p[1]); + const x0 = Math.min(...clip.nodes.map((n) => n.position[0])), y0 = Math.min(...clip.nodes.map((n) => n.position[1])); + d = [at[0] - x0, at[1] - y0]; + } + const ids = new Map<number, number>(); + let next = nextId(this.graph); + for (const n of clip.nodes) { + const id = next++; + ids.set(n.id, id); + const copy = cloneNode(n, id); + copy.position = [Math.round(n.position[0] + d[0]), Math.round(n.position[1] + d[1])]; + if (copy.kind === 'texture' && copy.settings.texture !== null && !this.textureList.some((x) => x.key === String(copy.settings.texture))) copy.settings.texture = null; + this.graph.nodes.set(id, copy); + } + for (const l of clip.links) this.graph.links.push({ from: [ids.get(l.from[0]) as number, l.from[1]], to: [ids.get(l.to[0]) as number, l.to[1]] }); + this.apply(this.graph); + this.select(new Set(ids.values())); + this.finish(); + } + + private openLinksMenu(id: number): void { + const items: PickItem[] = []; + const ends: Array<{ node: number; dir: 'in' | 'out'; name: string; ty: SocketType; label: string }> = []; + const all = [...this.views.values(), ...(this.out ? [this.out] : [])]; + for (const v of all) for (const s of v.sockets.values()) ends.push({ node: v.id, dir: s.dir, name: s.name, ty: s.ty, label: `${v.id === OUTPUT_NODE ? t('Material output') : `${this.nodeName(v.id)} ${v.id}`}: ${s.label}` }); + const mine = ends.filter((e) => e.node === id); + const actions = new Map<string, () => void>(); + for (const a of mine) { + for (const b of ends) { + if (b.node === id || b.dir === a.dir || this.interaction?.refusal(a, b, null)) continue; + const out = a.dir === 'out' ? a : b, inp = a.dir === 'out' ? b : a; + const key = `c:${out.node}:${out.name}>${inp.node}:${inp.name}`; + items.push({ id: key, label: `${out.label} > ${inp.label}`, group: t('Connect') }); + actions.set(key, () => this.connect([out.node, out.name], inp.node, inp.name, null)); + } + } + for (const l of this.graph.links) { + if (l.from[0] !== id && l.to[0] !== id) continue; + const key = `d:${linkKey(l)}`; + items.push({ id: key, label: `${this.nodeName(l.from[0])} ${l.from[0]}: ${t(words(l.from[1]))} > ${this.nodeName(l.to[0])} ${l.to[0]}: ${t(words(l.to[1]))}`, group: t('Disconnect') }); + actions.set(key, () => this.disconnect(linkKey(l))); + } + for (const [input, r] of this.graph.outputs) { + if (r[0] !== id && id !== OUTPUT_NODE) continue; + const key = `d:${outputKey(input, r)}`; + items.push({ id: key, label: `${this.nodeName(r[0])} ${r[0]}: ${t(words(r[1]))} > ${t('Material output')}: ${t(words(input))}`, group: t('Disconnect') }); + actions.set(key, () => this.disconnect(outputKey(input, r))); + } + const v = id === OUTPUT_NODE ? this.out : this.views.get(id); + const r = v?.el.getBoundingClientRect(); + this.menu.show(t('Connect or disconnect'), items, r ? r.right + 8 : 100, r ? r.top : 100, (item) => actions.get(item.id)?.()); + } +} + +interface Clip { nodes: GNode[]; links: GLink[] } + +let clipboard: Clip | null = null; diff --git a/frontend/src/ui/graph/fields.ts b/frontend/src/ui/graph/fields.ts new file mode 100644 index 00000000..c4e7dacb --- /dev/null +++ b/frontend/src/ui/graph/fields.ts @@ -0,0 +1,62 @@ +import { el, escapeHtml, q, setChecked, setValue } from '../../shell/dom'; +import { t } from '../../i18n'; +import { NumberField } from '../number-field'; +import { fromHex, hexOf } from './colour'; +import type { Rgb } from './model'; + +export type Edit = (value: unknown, live: boolean) => void; + +export interface Control { + el: HTMLElement; + set(value: unknown): void; +} + +export interface NumberOptions { step: number; min?: number; max?: number; integer?: boolean } + +export function stepFor(value: number): number { + const a = Math.abs(value); + if (a >= 100) return 1; + if (a >= 10) return 0.1; + if (a > 0 && a < 0.01) return 0.0001; + return 0.01; +} + +export function numberControl(label: string, opts: NumberOptions, edit: Edit): Control { + const field = new NumberField({ + label, step: opts.step, min: opts.min, max: opts.max, integer: opts.integer, + onInput: (v) => edit(v, true), + onCommit: (v) => edit(v, false), + }); + field.root.classList.add('fsh-graph-num'); + return { el: field.root, set: (v) => { if (typeof v === 'number') field.set(v); } }; +} + +export function colourControl(label: string, edit: Edit): Control { + const node = el(`<label class="fsh-graph-field is-colour"><span class="fsh-graph-field-label">${escapeHtml(t(label))}</span><input class="fsh-graph-swatch" type="color" aria-label="${escapeHtml(t(label))}"></label>`); + const input = q<HTMLInputElement>(node, 'input'); + input.addEventListener('input', () => edit(fromHex(input.value), true)); + input.addEventListener('change', () => edit(fromHex(input.value), false)); + return { + el: node, + set: (v) => { + if (!Array.isArray(v)) return; + const hex = hexOf([Number(v[0]), Number(v[1]), Number(v[2])] as Rgb); + if (document.activeElement !== input) setValue(input, hex); + }, + }; +} + +export function selectControl(label: string, options: ReadonlyArray<readonly [string, string]>, edit: Edit): Control & { select: HTMLSelectElement } { + const opts = options.map(([v, l]) => `<option value="${escapeHtml(v)}">${escapeHtml(t(l))}</option>`).join(''); + const node = el(`<label class="fsh-graph-field is-select"><span class="fsh-graph-field-label">${escapeHtml(t(label))}</span><select class="fsh-input fsh-graph-select" aria-label="${escapeHtml(t(label))}">${opts}</select></label>`); + const select = q<HTMLSelectElement>(node, 'select'); + select.addEventListener('change', () => edit(select.value, false)); + return { el: node, select, set: (v) => setValue(select, v === null || v === undefined ? '' : String(v)) }; +} + +export function boolControl(label: string, edit: Edit): Control { + const node = el(`<label class="fsh-graph-field is-bool"><input type="checkbox"><span class="fsh-graph-field-label">${escapeHtml(t(label))}</span></label>`); + const input = q<HTMLInputElement>(node, 'input'); + input.addEventListener('change', () => edit(input.checked, false)); + return { el: node, set: (v) => setChecked(input, v === true) }; +} diff --git a/frontend/src/ui/graph/graph.css b/frontend/src/ui/graph/graph.css new file mode 100644 index 00000000..58fa7497 --- /dev/null +++ b/frontend/src/ui/graph/graph.css @@ -0,0 +1,113 @@ +.fsh-graph-win { position: fixed; left: 0; top: 0; z-index: var(--z-popover); display: grid; grid-template-rows: 36px minmax(0, 1fr) 24px; min-width: 0; min-height: 0; overflow: hidden; background: var(--surface); border: 1px solid var(--glass-border); border-radius: var(--radius-xl); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--shadow-window); color: var(--text-primary); font: var(--fs-12) var(--font-ui); contain: layout paint; } +.fsh-graph-win[hidden] { display: none; } +.fsh-graph-head { display: flex; align-items: center; gap: var(--space-2); min-width: 0; padding: 0 var(--space-1) 0 var(--space-3); border-bottom: 1px solid var(--line-0); background: linear-gradient(to bottom, var(--bg-node), var(--surface-1)); cursor: grab; touch-action: none; } +.fsh-graph-head:active { cursor: grabbing; } +.fsh-graph-grip { flex: none; width: 8px; height: 14px; background-image: radial-gradient(circle, var(--text-faint) 1px, transparent 1.4px); background-size: 4px 4px; } +.fsh-graph-title { flex: 1 1 auto; min-width: 0; margin: 0; overflow: hidden; font-size: var(--fs-13); font-weight: var(--fw-semibold); text-overflow: ellipsis; white-space: nowrap; } +.fsh-graph-tools { display: flex; flex: none; align-items: center; gap: var(--space-0); } +.fsh-graph-close { flex: none; margin-inline-start: var(--space-1); } +.fsh-graph-body { position: relative; min-width: 0; min-height: 0; overflow: hidden; } +.fsh-graph-status { display: flex; align-items: center; gap: var(--space-3); min-width: 0; padding: 0 var(--space-3); overflow: hidden; border-top: 1px solid var(--line-0); background: var(--bg-secondary); color: var(--text-muted); font-size: var(--fs-11); white-space: nowrap; } +.fsh-graph-edge { position: absolute; z-index: var(--z-raised); touch-action: none; } +.fsh-graph-edge.is-n, .fsh-graph-edge.is-s { left: 8px; right: 8px; height: 6px; cursor: ns-resize; } +.fsh-graph-edge.is-e, .fsh-graph-edge.is-w { top: 8px; bottom: 8px; width: 6px; cursor: ew-resize; } +.fsh-graph-edge.is-n { top: 0; } +.fsh-graph-edge.is-s { bottom: 0; } +.fsh-graph-edge.is-e { right: 0; } +.fsh-graph-edge.is-w { left: 0; } +.fsh-graph-edge.is-ne, .fsh-graph-edge.is-nw, .fsh-graph-edge.is-se, .fsh-graph-edge.is-sw { width: 18px; height: 18px; } +.fsh-graph-edge.is-ne { top: 0; right: 0; cursor: nesw-resize; } +.fsh-graph-edge.is-sw { bottom: 0; left: 0; cursor: nesw-resize; } +.fsh-graph-edge.is-nw { top: 0; left: 0; cursor: nwse-resize; } +.fsh-graph-edge.is-se { bottom: 0; right: 0; cursor: nwse-resize; } + +.fsh-graph-canvas { --fsh-graph-minor: color-mix(in srgb, var(--text) 4%, transparent); --fsh-graph-major: color-mix(in srgb, var(--text) 8%, transparent); --fsh-graph-grid: 24px; --fsh-graph-gx: 0px; --fsh-graph-gy: 0px; position: absolute; inset: 0; overflow: hidden; outline: none; background-color: var(--canvas-bg); background-image: linear-gradient(to right, var(--fsh-graph-major) 1px, transparent 1px), linear-gradient(to bottom, var(--fsh-graph-major) 1px, transparent 1px), linear-gradient(to right, var(--fsh-graph-minor) 1px, transparent 1px), linear-gradient(to bottom, var(--fsh-graph-minor) 1px, transparent 1px); background-size: calc(var(--fsh-graph-grid) * 4) calc(var(--fsh-graph-grid) * 4), calc(var(--fsh-graph-grid) * 4) calc(var(--fsh-graph-grid) * 4), var(--fsh-graph-grid) var(--fsh-graph-grid), var(--fsh-graph-grid) var(--fsh-graph-grid); background-position: var(--fsh-graph-gx) var(--fsh-graph-gy); touch-action: none; cursor: default; } +.fsh-graph-canvas:focus-visible { box-shadow: inset 0 0 0 1px var(--accent-line); } +.fsh-graph-canvas.is-panning, .fsh-graph-canvas.is-space { cursor: grab; } +.fsh-graph-canvas.is-panning { cursor: grabbing; } +.fsh-graph-layer { position: absolute; left: 0; top: 0; width: 0; height: 0; transform-origin: 0 0; will-change: transform; } +.fsh-graph-nodes { position: absolute; left: 0; top: 0; } +.fsh-graph-links { position: absolute; left: 0; top: 0; width: 1px; height: 1px; overflow: visible; pointer-events: none; } +.fsh-graph-link { fill: none; stroke: var(--fsh-graph-wire, var(--text-muted)); stroke-width: 2px; vector-effect: non-scaling-stroke; } +.fsh-graph-link.is-float { --fsh-graph-wire: var(--text-muted); } +.fsh-graph-link.is-colour { --fsh-graph-wire: var(--warn); } +.fsh-graph-link.is-vector { --fsh-graph-wire: var(--accent-color); } +.fsh-graph-link.is-normal { --fsh-graph-wire: var(--ok); } +.fsh-graph-link.is-temp { stroke-dasharray: 6 4; } +.fsh-graph-link.is-refused { --fsh-graph-wire: var(--danger); } +.fsh-graph-link.is-error { --fsh-graph-wire: var(--danger); stroke-dasharray: 3 3; } +.fsh-graph-link.is-picked { opacity: 0.25; } +.fsh-graph-band { position: absolute; left: 0; top: 0; border: 1px solid var(--accent-line); background: var(--accent-wash); pointer-events: none; } + +.fsh-graph-node { position: absolute; left: 0; top: 0; width: 208px; border: 1px solid var(--line-2); border-radius: var(--radius-lg); background: var(--surface-raised); box-shadow: var(--shadow-sm); color: var(--text-primary); font-size: var(--fs-11); outline: none; } +.fsh-graph-node.is-output { width: 196px; } +.fsh-graph-node.is-selected { border-color: var(--accent-color); box-shadow: 0 0 0 1px var(--accent-color), var(--shadow-md); } +.fsh-graph-node:focus-visible { box-shadow: 0 0 0 2px var(--accent-color), var(--shadow-md); } +.fsh-graph-node.is-error { border-color: var(--danger); } +.fsh-graph-node-head { display: flex; align-items: center; gap: var(--space-1); height: 26px; padding: 0 var(--space-2); border-bottom: 1px solid var(--line-1); border-radius: var(--radius-lg) var(--radius-lg) 0 0; background: var(--bg-node); cursor: grab; } +.fsh-graph-node.is-pattern .fsh-graph-node-head { background: color-mix(in srgb, var(--accent) 12%, var(--bg-node)); } +.fsh-graph-node.is-output .fsh-graph-node-head { background: color-mix(in srgb, var(--ok) 14%, var(--bg-node)); } +.fsh-graph-node-title { flex: 1 1 auto; min-width: 0; overflow: hidden; font-size: var(--fs-12); font-weight: var(--fw-semibold); text-overflow: ellipsis; white-space: nowrap; } +.fsh-graph-node-badge { display: inline-grid; place-items: center; flex: none; width: 16px; height: 16px; border-radius: var(--radius-pill); background: var(--danger); color: var(--text-on-accent); font-size: var(--fs-10); font-weight: var(--fw-semibold); cursor: help; } +.fsh-graph-node-badge[hidden] { display: none; } +.fsh-graph-node-body { padding: var(--space-1) 0; } +.fsh-graph-row { position: relative; display: flex; align-items: center; gap: var(--space-1); height: 26px; padding: 0 var(--space-3); } +.fsh-graph-row.is-out { justify-content: flex-end; } +.fsh-graph-row-label { min-width: 0; overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-graph-row.has-field:not(.is-linked) > .fsh-graph-row-label { display: none; } +.fsh-graph-row.is-linked > .fsh-graph-num, .fsh-graph-row.is-linked > .fsh-graph-field { display: none; } +.fsh-graph-row.is-ramp { height: 76px; align-items: stretch; padding-top: var(--space-1); padding-bottom: var(--space-1); } +.fsh-graph-sock { position: absolute; top: 50%; width: 12px; height: 12px; margin: -6px 0 0; padding: 0; border: 2px solid var(--surface-raised); border-radius: var(--radius-pill); background: var(--fsh-graph-wire, var(--text-muted)); cursor: crosshair; } +.fsh-graph-sock.is-in { left: -7px; } +.fsh-graph-sock.is-out { right: -7px; } +.fsh-graph-sock.is-float { --fsh-graph-wire: var(--text-muted); } +.fsh-graph-sock.is-colour { --fsh-graph-wire: var(--warn); } +.fsh-graph-sock.is-vector { --fsh-graph-wire: var(--accent-color); } +.fsh-graph-sock.is-normal { --fsh-graph-wire: var(--ok); border-radius: var(--radius-xs); } +.fsh-graph-sock:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fsh-graph-sock::before { content: ""; position: absolute; inset: -7px; } +.fsh-graph-canvas.is-linking .fsh-graph-sock { opacity: 0.3; } +.fsh-graph-canvas.is-linking .fsh-graph-sock.is-ok { opacity: 1; box-shadow: 0 0 0 3px var(--accent-wash), 0 0 0 1px var(--accent-color); } +.fsh-graph-msg { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.fsh-graph-msg.is-error { color: var(--danger-text); } +.fsh-graph-revert { flex: none; height: 18px; padding: 0 var(--space-2); font-size: var(--fs-11); } +.fsh-graph-revert[hidden] { display: none; } +.fsh-graph-count { flex: none; min-width: 16ch; text-align: end; } +.fsh-graph-zoom { flex: none; min-width: 5ch; text-align: end; } +.fsh-graph-menu { position: fixed; left: var(--fsh-graph-mx, 0px); top: var(--fsh-graph-my, 0px); z-index: var(--z-menu); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; width: 260px; max-height: 340px; padding: var(--space-1); background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: var(--radius-xl); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); color: var(--text-primary); font-size: var(--fs-12); } +.fsh-graph-menu[hidden] { display: none; } +.fsh-graph-menu-search { height: var(--ctl-md); margin-bottom: var(--space-1); } +.fsh-graph-menu-list { min-height: 0; overflow-y: auto; } +.fsh-graph-menu-group { padding: var(--space-2) var(--space-2) var(--space-0); color: var(--text-faint); font-size: var(--fs-10); font-weight: var(--fw-semibold); letter-spacing: 0.04em; text-transform: uppercase; } +.fsh-graph-menu-item { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); min-height: 26px; padding: var(--space-1) var(--space-2); border-radius: var(--radius); cursor: default; } +.fsh-graph-menu-item.is-active { background: var(--accent-soft); } +.fsh-graph-menu-hint { color: var(--text-faint); font-size: var(--fs-11); } +.fsh-graph-menu-empty { margin: var(--space-2); color: var(--text-muted); } +.fsh-graph-menu-empty[hidden] { display: none; } +.fsh-graph-help { position: absolute; top: 40px; right: var(--space-2); z-index: var(--z-raised); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; width: 360px; max-height: calc(100% - 72px); padding: var(--space-3); background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: var(--radius-xl); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); outline: none; } +.fsh-graph-help[hidden] { display: none; } +.fsh-graph-help-title { margin: 0 0 var(--space-2); font-size: var(--fs-13); font-weight: var(--fw-semibold); } +.fsh-graph-help-list { min-height: 0; overflow-y: auto; } +.fsh-graph-help-row { display: grid; grid-template-columns: 128px minmax(0, 1fr); align-items: baseline; gap: var(--space-2); padding: var(--space-1) 0; border-top: 1px solid var(--line-1); color: var(--text-secondary); } +.fsh-graph-help-keys { display: flex; flex-wrap: wrap; gap: var(--space-0); } +.fsh-graph-help kbd { padding: 0 var(--space-1); border: 1px solid var(--line-2); border-radius: var(--radius-xs); background: var(--bg-input); color: var(--text-primary); font: var(--fs-11) var(--mono); } +.fsh-graph-help-note { margin: var(--space-2) 0 0; color: var(--text-faint); font-size: var(--fs-11); } +.fsh-graph-num { flex: 1 1 auto; min-width: 0; height: 22px; } +.fsh-graph-field { display: flex; flex: 1 1 auto; align-items: center; gap: var(--space-2); min-width: 0; height: 22px; } +.fsh-graph-field-label { flex: 1 1 auto; min-width: 0; overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-graph-select { flex: 0 1 112px; min-width: 0; height: 22px; padding: 0 var(--space-1); font-size: var(--fs-11); } +.fsh-graph-swatch { flex: none; width: 40px; height: 18px; padding: 0; border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: none; cursor: pointer; } +.fsh-graph-swatch::-webkit-color-swatch-wrapper { padding: 0; } +.fsh-graph-swatch::-webkit-color-swatch { border: 0; border-radius: var(--radius-xs); } +.fsh-graph-field.is-bool { justify-content: flex-start; } +.fsh-graph-preview { height: 88px; margin: 0 var(--space-3) var(--space-1); overflow: hidden; border: 1px solid var(--line-1); border-radius: var(--radius); background: var(--bg-input); } +.fsh-graph-preview img { display: block; width: 100%; height: 100%; object-fit: cover; } +.fsh-graph-preview.is-empty img { visibility: hidden; } +.fsh-graph-ramp { display: grid; grid-template-columns: minmax(0, 1fr); grid-template-rows: 16px 10px 24px; gap: var(--space-0); flex: 1 1 0; min-width: 0; } +.fsh-graph-ramp-bar { border: 1px solid var(--line-2); border-radius: var(--radius-sm); cursor: copy; } +.fsh-graph-ramp-track { position: relative; margin: 0 1px; cursor: copy; } +.fsh-graph-ramp-stop { position: absolute; top: 0; left: var(--fsh-graph-at, 0%); width: 10px; height: 10px; margin-left: -5px; padding: 0; border: 1px solid var(--text-muted); border-radius: var(--radius-xs); background: var(--fsh-graph-stop, var(--text)); cursor: ew-resize; } +.fsh-graph-ramp-stop.is-active { border-color: var(--accent-color); box-shadow: 0 0 0 1px var(--accent-color); } +.fsh-graph-ramp-row { display: flex; align-items: center; gap: var(--space-1); } +.fsh-graph-ramp-pos { flex: 1 1 0; width: 0; min-width: 0; height: 22px; padding: 0 var(--space-1); font: var(--fs-11) var(--mono); } +.fsh-graph-ramp-del { width: 22px; height: 22px; } diff --git a/frontend/src/ui/graph/help.ts b/frontend/src/ui/graph/help.ts new file mode 100644 index 00000000..a10ef2fd --- /dev/null +++ b/frontend/src/ui/graph/help.ts @@ -0,0 +1,43 @@ +import { el, escapeHtml, setHidden } from '../../shell/dom'; +import { formatKeys } from '../../shell/registry'; +import { t } from '../../i18n'; +import { KEY_ACTIONS } from './keys'; + +export class HelpPopover { + readonly root: HTMLElement; + private before: HTMLElement | null = null; + + constructor(host: HTMLElement) { + const rows = KEY_ACTIONS.map((a) => { + const keys = a.shown.map((k) => `<kbd>${escapeHtml(k === 'Space' ? t('Space bar') : formatKeys(k))}</kbd>`).join(' '); + return `<div class="fsh-graph-help-row" role="listitem"><span class="fsh-graph-help-keys" data-no-i18n>${keys}</span><span>${escapeHtml(t(a.label))}</span></div>`; + }).join(''); + this.root = el(`<div class="fsh-graph-help" role="dialog" aria-label="${escapeHtml(t('Node editor keys'))}" tabindex="-1" hidden> +<h3 class="fsh-graph-help-title">${escapeHtml(t('Node editor keys'))}</h3> +<div class="fsh-graph-help-list fsh-graph-scroll" role="list">${rows}</div> +<p class="fsh-graph-help-note">${escapeHtml(t('Undo and redo use the app keys, Mod+Z and Shift+Mod+Z.'))}</p> +</div>`); + host.appendChild(this.root); + this.root.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.close(); } + }); + this.root.addEventListener('focusout', (e) => { + if (!this.root.contains(e.relatedTarget as Node | null)) this.close(false); + }); + } + + get open(): boolean { return !this.root.hidden; } + + toggle(): void { + if (this.open) { this.close(); return; } + this.before = document.activeElement instanceof HTMLElement ? document.activeElement : null; + setHidden(this.root, false); + this.root.focus({ preventScroll: true }); + } + + close(refocus = true): void { + if (this.root.hidden) return; + setHidden(this.root, true); + if (refocus && this.before?.isConnected) this.before.focus({ preventScroll: true }); + } +} diff --git a/frontend/src/ui/graph/images.ts b/frontend/src/ui/graph/images.ts new file mode 100644 index 00000000..cd1f6d0c --- /dev/null +++ b/frontend/src/ui/graph/images.ts @@ -0,0 +1,57 @@ +import { api } from '../../shell/api'; +import { inTauri } from '../../shell/dom'; +import { t } from '../../i18n'; + +const ROUTE = '/api/textures'; +const EXTS = ['png', 'jpg', 'jpeg', 'hdr', 'exr']; + +let route: Promise<boolean> | null = null; + +function hasRoute(): Promise<boolean> { + if (!route) { + route = fetch(api.url(ROUTE), { method: 'POST', body: new FormData(), cache: 'no-store' }).then((r) => r.status !== 404 && r.status !== 405).catch(() => false); + route.then((ok) => { if (!ok) route = null; }).catch(() => undefined); + } + return route; +} + +function chooseFile(): Promise<File | null> { + return new Promise((resolve) => { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = EXTS.map((e) => `.${e}`).join(','); + input.hidden = true; + let done = false; + const finish = (f: File | null): void => { if (done) return; done = true; input.remove(); resolve(f); }; + input.addEventListener('change', () => finish(input.files?.[0] ?? null)); + input.addEventListener('cancel', () => finish(null)); + document.body.appendChild(input); + input.click(); + }); +} + +async function upload(file: File): Promise<string> { + const form = new FormData(); + form.append('file', file, file.name); + const res = await fetch(api.url(ROUTE), { method: 'POST', body: form }); + const body = await res.json().catch(() => ({})) as { path?: unknown; detail?: unknown }; + if (!res.ok || typeof body.path !== 'string') throw new Error(typeof body.detail === 'string' ? body.detail : t('The image could not be stored ({status})', { status: res.status })); + return body.path; +} + +async function desktopPath(): Promise<string | null> { + const { invoke } = await import('@tauri-apps/api/core'); + const picked = await invoke<string | string[] | null>('plugin:dialog|open', { + options: { multiple: false, directory: false, title: t('Add image'), filters: [{ name: t('Images'), extensions: EXTS }] }, + }); + return Array.isArray(picked) ? picked[0] ?? null : picked; +} + +export async function pickImage(): Promise<string | null> { + if (await hasRoute()) { + const file = await chooseFile(); + return file ? upload(file) : null; + } + if (inTauri()) return desktopPath(); + throw new Error(t('Adding images needs the desktop app or a service that stores uploads.')); +} diff --git a/frontend/src/ui/graph/index.ts b/frontend/src/ui/graph/index.ts new file mode 100644 index 00000000..e55bad12 --- /dev/null +++ b/frontend/src/ui/graph/index.ts @@ -0,0 +1,10 @@ +import './graph.css'; +import type { Workspace } from '../context'; +import { GraphEditor } from './editor'; + +let editor: GraphEditor | null = null; + +export function openGraphEditor(ws: Workspace, material: string): void { + if (!editor || editor.ws !== ws) editor = new GraphEditor(ws); + void editor.open(String(material)); +} diff --git a/frontend/src/ui/graph/interact.ts b/frontend/src/ui/graph/interact.ts new file mode 100644 index 00000000..072cebbb --- /dev/null +++ b/frontend/src/ui/graph/interact.ts @@ -0,0 +1,220 @@ +import { setClass } from '../../shell/dom'; +import { t } from '../../i18n'; +import type { GraphEditor } from './editor'; +import { TYPE_WORDS } from './labels'; +import type { Point } from './links'; +import { converts, linkInto, linkKey, OUTPUT_NODE, outputKey, outputType, reaches, type SocketRef, type SocketType } from './model'; + +const DRAG_SLOP = 4; + +interface End { node: number; dir: 'in' | 'out'; name: string; ty: SocketType } + +interface LinkDrag { + kind: 'link'; + pointer: number; + fixed: End; + picked: string | null; + over: End | null; + reason: string; +} + +interface NodeDrag { + kind: 'nodes'; + pointer: number; + start: Point; + ids: number[]; + from: Map<number, Point>; + moved: boolean; + clickSelect: number | null; +} + +interface BoxDrag { kind: 'box'; pointer: number; start: Point; add: boolean; base: Set<number>; moved: boolean } + +type Gesture = LinkDrag | NodeDrag | BoxDrag; + +function endOf(sock: HTMLElement): End | null { + const node = sock.closest<HTMLElement>('.fsh-graph-node'); + if (!node) return null; + return { node: Number(node.dataset.node), dir: sock.dataset.dir === 'out' ? 'out' : 'in', name: sock.dataset.sock ?? '', ty: (sock.dataset.ty ?? 'float') as SocketType }; +} + +export class Interaction { + private g: Gesture | null = null; + pointer: Point | null = null; + + constructor(private readonly ed: GraphEditor) { + const host = ed.canvas?.host; + if (!host) return; + host.addEventListener('pointerdown', (e) => this.down(e)); + host.addEventListener('pointermove', (e) => this.move(e)); + host.addEventListener('pointerup', (e) => this.up(e, false)); + host.addEventListener('pointercancel', (e) => this.up(e, true)); + host.addEventListener('pointerleave', () => { if (!this.g) this.pointer = null; }); + host.addEventListener('contextmenu', (e) => { + e.preventDefault(); + if ((e.target as HTMLElement).closest('input, select, textarea')) return; + this.ed.openAddMenu(e.clientX, e.clientY); + }); + } + + get active(): boolean { return this.g !== null; } + + private down(e: PointerEvent): void { + const ed = this.ed, canvas = ed.canvas; + if (!canvas || e.button !== 0 || this.g) return; + const target = e.target as HTMLElement; + const sock = target.closest<HTMLElement>('.fsh-graph-sock'); + if (sock) { this.beginLink(e, sock); return; } + if (target.closest('input, select, textarea, button, .fsh-graph-num, .fsh-graph-ramp, label')) return; + const nodeEl = target.closest<HTMLElement>('.fsh-graph-node'); + const at = canvas.toCanvas(e.clientX, e.clientY); + if (nodeEl) { + const id = Number(nodeEl.dataset.node); + let clickSelect: number | null = null; + if (e.shiftKey || e.ctrlKey || e.metaKey) { + const next = new Set(ed.selection); + if (next.has(id)) next.delete(id); else next.add(id); + ed.select(next); + } else if (!ed.selection.has(id)) ed.select(new Set([id])); + else clickSelect = id; + const ids = [...ed.selection]; + const from = new Map<number, Point>(); + for (const i of ids) { const p = ed.position(i); if (p) from.set(i, p); } + this.g = { kind: 'nodes', pointer: e.pointerId, start: at, ids, from, moved: false, clickSelect }; + nodeEl.focus({ preventScroll: true }); + } else { + this.g = { kind: 'box', pointer: e.pointerId, start: at, add: e.shiftKey || e.ctrlKey || e.metaKey, base: new Set(ed.selection), moved: false }; + canvas.host.focus({ preventScroll: true }); + } + canvas.host.setPointerCapture(e.pointerId); + e.preventDefault(); + } + + private beginLink(e: PointerEvent, sock: HTMLElement): void { + const ed = this.ed; + const end = endOf(sock); + if (!end || !ed.canvas) return; + let fixed = end, picked: string | null = null; + if (end.dir === 'in') { + const existing = end.node === OUTPUT_NODE ? ed.graph.outputs.get(end.name) : linkInto(ed.graph, end.node, end.name)?.from; + if (existing) { + const from = ed.graph.nodes.get(existing[0]); + fixed = { node: existing[0], dir: 'out', name: existing[1], ty: (from && outputType(ed.cat, from, existing[1])) ?? 'float' }; + picked = end.node === OUTPUT_NODE ? outputKey(end.name, existing) : linkKey({ from: existing, to: [end.node, end.name] }); + ed.links?.setClass(picked, 'is-picked', true); + } + } + this.g = { kind: 'link', pointer: e.pointerId, fixed, picked, over: null, reason: '' }; + this.mark(fixed, picked); + ed.canvas.host.setPointerCapture(e.pointerId); + e.preventDefault(); + e.stopPropagation(); + this.move(e); + } + + refusal(a: End, b: End, picked: string | null): string { + if (a.dir === b.dir) return a.dir === 'out' ? t('Connect an output to an input.') : t('Connect an input to an output.'); + const out = a.dir === 'out' ? a : b, inp = a.dir === 'out' ? b : a; + if (out.node === inp.node) return t('A node cannot feed itself.'); + if (!converts(out.ty, inp.ty)) return t('A {from} output cannot feed a {to} input.', { from: t(TYPE_WORDS[out.ty]), to: t(TYPE_WORDS[inp.ty]) }); + if (inp.node !== OUTPUT_NODE) { + const g = this.ed.graph; + const links = picked ? g.links.filter((l) => linkKey(l) !== picked) : g.links; + if (reaches({ ...g, links }, inp.node, out.node)) return t('That link would make a loop.'); + } + return ''; + } + + private mark(fixed: End, picked: string | null): void { + const ed = this.ed; + setClass(ed.canvas?.host ?? null, 'is-linking', true); + const all = [...ed.views.values(), ...(ed.out ? [ed.out] : [])]; + for (const v of all) { + for (const s of v.sockets.values()) { + const ok = this.refusal(fixed, { node: v.id, dir: s.dir, name: s.name, ty: s.ty }, picked) === ''; + setClass(s.el, 'is-ok', ok); + } + } + } + + private unmark(): void { + const ed = this.ed; + setClass(ed.canvas?.host ?? null, 'is-linking', false); + for (const v of [...ed.views.values(), ...(ed.out ? [ed.out] : [])]) for (const s of v.sockets.values()) setClass(s.el, 'is-ok', false); + } + + private move(e: PointerEvent): void { + const ed = this.ed, canvas = ed.canvas; + if (!canvas) return; + const at = canvas.toCanvas(e.clientX, e.clientY); + this.pointer = [e.clientX, e.clientY]; + const g = this.g; + if (!g || e.pointerId !== g.pointer) return; + if (g.kind === 'link') { + const hit = document.elementFromPoint(e.clientX, e.clientY)?.closest<HTMLElement>('.fsh-graph-sock') ?? null; + const over = hit ? endOf(hit) : null; + g.over = over; + g.reason = over ? this.refusal(g.fixed, over, g.picked) : ''; + const fixedPos = ed.socketPos(g.fixed.node, g.fixed.dir, g.fixed.name) ?? at; + const overPos = over && !g.reason ? ed.socketPos(over.node, over.dir, over.name) ?? at : at; + if (g.fixed.dir === 'out') ed.links?.showTemp(fixedPos, overPos, g.fixed.ty, g.reason !== ''); + else ed.links?.showTemp(overPos, fixedPos, g.fixed.ty, g.reason !== ''); + ed.status.note(g.reason); + return; + } + if (g.kind === 'nodes') { + const dx = at[0] - g.start[0], dy = at[1] - g.start[1]; + if (!g.moved && Math.hypot(dx, dy) * canvas.view.z < DRAG_SLOP) return; + g.moved = true; + for (const id of g.ids) { + const p = g.from.get(id); + if (p) ed.moveTo(id, [Math.round(p[0] + dx), Math.round(p[1] + dy)]); + } + ed.relinkNodes(new Set(g.ids)); + return; + } + const x0 = Math.min(g.start[0], at[0]), y0 = Math.min(g.start[1], at[1]); + const x1 = Math.max(g.start[0], at[0]), y1 = Math.max(g.start[1], at[1]); + if (!g.moved && (x1 - x0) * canvas.view.z < DRAG_SLOP && (y1 - y0) * canvas.view.z < DRAG_SLOP) return; + g.moved = true; + const z = canvas.view.z, v = canvas.view; + const band = canvas.band; + band.hidden = false; + band.style.transform = `translate(${x0 * z + v.x}px, ${y0 * z + v.y}px)`; + band.style.width = `${(x1 - x0) * z}px`; + band.style.height = `${(y1 - y0) * z}px`; + const next = new Set(g.add ? g.base : []); + for (const [id, view] of ed.views) { + if (view.x < x1 && view.x + view.w > x0 && view.y < y1 && view.y + view.h > y0) next.add(id); + } + ed.select(next); + } + + private up(e: PointerEvent, cancel: boolean): void { + const g = this.g, ed = this.ed; + if (!g || e.pointerId !== g.pointer) return; + this.g = null; + if (g.kind === 'link') { + ed.links?.hideTemp(); + if (g.picked) ed.links?.setClass(g.picked, 'is-picked', false); + this.unmark(); + ed.status.note(''); + if (cancel) return; + if (g.over && g.reason) { ed.ws.ctx.toast(g.reason, 'error'); return; } + if (g.over) { + const out = g.fixed.dir === 'out' ? g.fixed : g.over, inp = g.fixed.dir === 'out' ? g.over : g.fixed; + ed.connect([out.node, out.name] as SocketRef, inp.node, inp.name, g.picked); + } else if (g.picked) ed.disconnect(g.picked); + return; + } + if (g.kind === 'nodes') { + if (g.moved && !cancel) ed.finishMove(g.ids); + else if (g.moved) for (const id of g.ids) { const p = g.from.get(id); if (p) ed.moveTo(id, p); } + else if (g.clickSelect !== null) ed.select(new Set([g.clickSelect])); + if (cancel) ed.relinkNodes(new Set(g.ids)); + return; + } + if (ed.canvas) ed.canvas.band.hidden = true; + if (!g.moved && !g.add) ed.select(new Set()); + } +} diff --git a/frontend/src/ui/graph/keys.ts b/frontend/src/ui/graph/keys.ts new file mode 100644 index 00000000..24bacd83 --- /dev/null +++ b/frontend/src/ui/graph/keys.ts @@ -0,0 +1,31 @@ +export type ActionId = + | 'add' | 'links' | 'delete' | 'duplicate' | 'copy' | 'cut' | 'paste' | 'selectAll' | 'frame' | 'zoomIn' | 'zoomOut' | 'zoomReset' + | 'next' | 'enter' | 'nudge' | 'pan' | 'help' | 'close'; + +export interface KeyAction { id: ActionId; keys: string[]; shown: string[]; label: string } + +export const KEY_ACTIONS: readonly KeyAction[] = [ + { id: 'add', keys: ['Tab', 'Shift+A'], shown: ['Tab', 'Shift+A'], label: 'Add a node at the pointer' }, + { id: 'links', keys: ['L'], shown: ['L'], label: 'Connect or disconnect the focused node' }, + { id: 'delete', keys: ['Delete', 'Backspace', 'X'], shown: ['Delete', 'X'], label: 'Delete the selected nodes' }, + { id: 'duplicate', keys: ['Mod+D', 'Shift+D'], shown: ['Mod+D'], label: 'Duplicate the selected nodes' }, + { id: 'copy', keys: ['Mod+C'], shown: ['Mod+C'], label: 'Copy the selected nodes' }, + { id: 'cut', keys: ['Mod+X'], shown: ['Mod+X'], label: 'Cut the selected nodes' }, + { id: 'paste', keys: ['Mod+V'], shown: ['Mod+V'], label: 'Paste nodes, also into another material' }, + { id: 'selectAll', keys: ['Mod+A'], shown: ['Mod+A'], label: 'Select every node' }, + { id: 'frame', keys: ['F', 'Home'], shown: ['F'], label: 'Frame all nodes' }, + { id: 'zoomIn', keys: ['Mod+=', 'Shift+Mod+=', '='], shown: ['Mod++'], label: 'Zoom in' }, + { id: 'zoomOut', keys: ['Mod+-', '-'], shown: ['Mod+-'], label: 'Zoom out' }, + { id: 'zoomReset', keys: ['Mod+0'], shown: ['Mod+0'], label: 'Zoom to 100%' }, + { id: 'next', keys: ['Up', 'Down', 'Left', 'Right'], shown: ['Up', 'Down', 'Left', 'Right'], label: 'Move focus to the nearest node' }, + { id: 'nudge', keys: ['Shift+Up', 'Shift+Down', 'Shift+Left', 'Shift+Right'], shown: ['Shift+Up'], label: 'Move the selected nodes' }, + { id: 'enter', keys: ['Enter'], shown: ['Enter'], label: 'Edit the focused node; Escape returns' }, + { id: 'pan', keys: [], shown: ['Space'], label: 'Hold and drag to pan; middle drag and two-finger scroll pan too' }, + { id: 'help', keys: ['Shift+/', 'H', 'F1'], shown: ['?'], label: 'Show these keys' }, + { id: 'close', keys: ['Escape'], shown: ['Escape'], label: 'Close the node editor' }, +]; + +const BY_COMBO = new Map<string, ActionId>(); +for (const a of KEY_ACTIONS) for (const k of a.keys) BY_COMBO.set(k, a.id); + +export const actionFor = (combo: string): ActionId | undefined => BY_COMBO.get(combo); diff --git a/frontend/src/ui/graph/labels.ts b/frontend/src/ui/graph/labels.ts new file mode 100644 index 00000000..50ade66d --- /dev/null +++ b/frontend/src/ui/graph/labels.ts @@ -0,0 +1,35 @@ +const NAMES: Readonly<Record<string, string>> = { + op: 'Operation', + gradient: 'Shape', + wave: 'Shape', + texture: 'Image', + colour_space: 'Colour space', + flip_y: 'Flip green', + f1: 'Nearest point', + f2: 'Second nearest', + edge: 'Cell edge', + acescg: 'ACEScg', + srgb: 'sRGB', + uv: 'UV', +}; + +export function words(name: string): string { + const own = NAMES[name]; + if (own) return own; + const s = name.replace(/_/g, ' ').replace(/([a-z])(\d)/gi, '$1 $2'); + return s.charAt(0).toUpperCase() + s.slice(1); +} + +export function groupOf(k: { id: string; procedural: boolean }): string { + if (k.procedural) return 'Patterns'; + if (k.id === 'constant' || k.id === 'texture' || k.id === 'mapping') return 'Inputs'; + if (k.id === 'normal_map' || k.id === 'bump') return 'Surface'; + return 'Colour and maths'; +} + +export const TYPE_WORDS: Readonly<Record<string, string>> = { + float: 'number', + colour: 'colour', + vector: 'vector', + normal: 'normal', +}; diff --git a/frontend/src/ui/graph/links.ts b/frontend/src/ui/graph/links.ts new file mode 100644 index 00000000..fdd8f200 --- /dev/null +++ b/frontend/src/ui/graph/links.ts @@ -0,0 +1,68 @@ +import type { SocketType } from './model'; + +const SVG_NS = 'http://www.w3.org/2000/svg'; + +export type Point = [number, number]; + +export function curve(a: Point, b: Point): string { + const dx = Math.max(36, Math.abs(b[0] - a[0]) * 0.5); + const r = (v: number): number => Math.round(v * 10) / 10; + return `M${r(a[0])} ${r(a[1])}C${r(a[0] + dx)} ${r(a[1])} ${r(b[0] - dx)} ${r(b[1])} ${r(b[0])} ${r(b[1])}`; +} + +interface Path { el: SVGPathElement; d: string; ty: string } + +export class LinkLayer { + private readonly paths = new Map<string, Path>(); + private readonly temp: SVGPathElement; + private tempD = ''; + + constructor(private readonly svg: SVGSVGElement) { + this.temp = document.createElementNS(SVG_NS, 'path'); + this.temp.setAttribute('class', 'fsh-graph-link is-temp'); + this.temp.style.visibility = 'hidden'; + svg.appendChild(this.temp); + } + + has(key: string): boolean { return this.paths.has(key); } + keys(): string[] { return [...this.paths.keys()]; } + + set(key: string, a: Point, b: Point, ty: SocketType): void { + const d = curve(a, b); + let p = this.paths.get(key); + if (!p) { + const node = document.createElementNS(SVG_NS, 'path'); + node.setAttribute('class', `fsh-graph-link is-${ty}`); + node.dataset.key = key; + this.svg.insertBefore(node, this.temp); + p = { el: node, d: '', ty }; + this.paths.set(key, p); + } + if (p.ty !== ty) { p.el.classList.replace(`is-${p.ty}`, `is-${ty}`); p.ty = ty; } + if (p.d !== d) { p.d = d; p.el.setAttribute('d', d); } + } + + remove(key: string): void { + const p = this.paths.get(key); + if (!p) return; + p.el.remove(); + this.paths.delete(key); + } + + setClass(key: string, cls: string, on: boolean): void { + const p = this.paths.get(key); + if (p && p.el.classList.contains(cls) !== on) p.el.classList.toggle(cls, on); + } + + showTemp(a: Point, b: Point, ty: SocketType, refused: boolean): void { + const d = curve(a, b); + if (d !== this.tempD) { this.tempD = d; this.temp.setAttribute('d', d); } + const cls = `fsh-graph-link is-temp is-${ty}${refused ? ' is-refused' : ''}`; + if (this.temp.getAttribute('class') !== cls) this.temp.setAttribute('class', cls); + if (this.temp.style.visibility) this.temp.style.visibility = ''; + } + + hideTemp(): void { + if (!this.temp.style.visibility) this.temp.style.visibility = 'hidden'; + } +} diff --git a/frontend/src/ui/graph/menu.ts b/frontend/src/ui/graph/menu.ts new file mode 100644 index 00000000..d0e39269 --- /dev/null +++ b/frontend/src/ui/graph/menu.ts @@ -0,0 +1,119 @@ +import { el, escapeHtml, patchList, q, setAttr, setClass, setHidden, setStyleVar } from '../../shell/dom'; +import { t } from '../../i18n'; + +export interface PickItem { id: string; label: string; group: string; hint?: string } + +export class PickMenu { + readonly root: HTMLElement; + private readonly input: HTMLInputElement; + private readonly list: HTMLElement; + private readonly empty: HTMLElement; + private items: PickItem[] = []; + private shown: PickItem[] = []; + private active = 0; + private pick: ((item: PickItem) => void) | null = null; + private before: HTMLElement | null = null; + + constructor(host: HTMLElement) { + this.root = el(`<div class="fsh-graph-menu" role="dialog" hidden> +<input class="fsh-input fsh-graph-menu-search" type="search" spellcheck="false" autocomplete="off" role="combobox" aria-expanded="true" aria-controls="fsh-graph-menu-list"> +<div class="fsh-graph-menu-list fsh-graph-scroll" id="fsh-graph-menu-list" role="listbox"></div> +<p class="fsh-graph-menu-empty" hidden>${escapeHtml(t('Nothing matches'))}</p> +</div>`); + this.input = q<HTMLInputElement>(this.root, 'input'); + this.list = q(this.root, '.fsh-graph-menu-list'); + this.empty = q(this.root, '.fsh-graph-menu-empty'); + host.appendChild(this.root); + this.input.addEventListener('input', () => { this.active = 0; this.filter(); }); + this.input.addEventListener('keydown', (e) => this.key(e)); + this.list.addEventListener('pointerdown', (e) => e.preventDefault()); + this.list.addEventListener('click', (e) => { + const row = (e.target as HTMLElement).closest<HTMLElement>('[data-index]'); + if (row) this.choose(Number(row.dataset.index)); + }); + this.list.addEventListener('pointermove', (e) => { + const row = (e.target as HTMLElement).closest<HTMLElement>('[data-index]'); + if (row && Number(row.dataset.index) !== this.active) { this.active = Number(row.dataset.index); this.mark(); } + }); + this.input.addEventListener('blur', () => { if (!this.root.hidden) window.setTimeout(() => { if (!this.root.contains(document.activeElement)) this.close(false); }, 0); }); + } + + get open(): boolean { return !this.root.hidden; } + + show(title: string, items: PickItem[], x: number, y: number, pick: (item: PickItem) => void): void { + this.before = document.activeElement instanceof HTMLElement ? document.activeElement : null; + this.items = items; + this.pick = pick; + this.active = 0; + this.input.value = ''; + setAttr(this.input, 'placeholder', title); + setAttr(this.input, 'aria-label', title); + this.filter(); + const w = 260, h = 340; + setStyleVar(this.root, '--fsh-graph-mx', `${Math.round(Math.min(Math.max(4, x), window.innerWidth - w - 4))}px`); + setStyleVar(this.root, '--fsh-graph-my', `${Math.round(Math.min(Math.max(4, y), window.innerHeight - h - 4))}px`); + setHidden(this.root, false); + this.input.focus(); + } + + close(refocus = true): void { + if (this.root.hidden) return; + setHidden(this.root, true); + this.pick = null; + if (refocus && this.before?.isConnected) this.before.focus({ preventScroll: true }); + } + + private filter(): void { + const words = this.input.value.trim().toLowerCase().split(/\s+/).filter(Boolean); + this.shown = this.items.filter((i) => words.every((w) => `${i.label} ${i.group} ${i.hint ?? ''}`.toLowerCase().includes(w))); + const rows: Array<{ key: string; group?: string; item?: PickItem; n: number }> = []; + let group = ''; + this.shown.forEach((i, n) => { + if (i.group !== group) { group = i.group; rows.push({ key: `g:${group}`, group, n: -1 }); } + rows.push({ key: `i:${i.id}`, item: i, n }); + }); + patchList(this.list, rows, { + key: (r) => r.key, + create: (r) => (r.item + ? el(`<div class="fsh-graph-menu-item" role="option"><span>${escapeHtml(r.item.label)}</span>${r.item.hint ? `<span class="fsh-graph-menu-hint">${escapeHtml(r.item.hint)}</span>` : ''}</div>`) + : el(`<div class="fsh-graph-menu-group" role="presentation">${escapeHtml(r.group ?? '')}</div>`)), + update: () => undefined, + }); + for (const row of this.list.children) { + const r = rows.find((x) => x.key === (row as HTMLElement).dataset.key); + if (r?.item) { (row as HTMLElement).dataset.index = String(r.n); row.id = `fsh-graph-opt-${r.n}`; } + } + setHidden(this.empty, this.shown.length > 0); + this.mark(); + } + + private mark(): void { + for (const row of this.list.querySelectorAll<HTMLElement>('[data-index]')) { + const on = Number(row.dataset.index) === this.active; + setClass(row, 'is-active', on); + setAttr(row, 'aria-selected', on ? 'true' : 'false'); + if (on) row.scrollIntoView({ block: 'nearest' }); + } + setAttr(this.input, 'aria-activedescendant', this.shown.length ? `fsh-graph-opt-${this.active}` : null); + } + + private choose(i: number): void { + const item = this.shown[i]; + const fn = this.pick; + if (!item || !fn) return; + this.close(); + fn(item); + } + + private key(e: KeyboardEvent): void { + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + if (this.shown.length) this.active = (this.active + (e.key === 'ArrowDown' ? 1 : this.shown.length - 1)) % this.shown.length; + this.mark(); + } else if (e.key === 'Enter') this.choose(this.active); + else if (e.key === 'Escape') this.close(); + else if (e.key === 'Tab') { e.preventDefault(); this.close(); } + else { e.stopPropagation(); return; } + e.preventDefault(); + e.stopPropagation(); + } +} diff --git a/frontend/src/ui/graph/model.ts b/frontend/src/ui/graph/model.ts new file mode 100644 index 00000000..c83f07f3 --- /dev/null +++ b/frontend/src/ui/graph/model.ts @@ -0,0 +1,238 @@ +export type SocketType = 'float' | 'colour' | 'vector' | 'normal'; +export type Rgb = [number, number, number]; +export type SocketValue = number | Rgb; +export type SocketRef = [number, string]; + +export interface SocketSpec { name: string; ty: SocketType; default: Rgb } +export interface SettingSpec { name: string; kind: string; values: string[] } +export interface KindSpec { + id: string; + label: string; + inputs: SocketSpec[]; + outputs: SocketSpec[]; + settings: SettingSpec[]; + procedural: boolean; +} +export interface MaterialInputSpec { name: string; colour: boolean; graph: boolean } + +export interface Catalogue { + kinds: KindSpec[]; + byId: Map<string, KindSpec>; + inputs: MaterialInputSpec[]; +} + +export interface GNode { + id: number; + kind: string; + settings: Record<string, unknown>; + inputs: Record<string, SocketValue>; + position: [number, number]; + label: string; +} + +export interface GLink { from: SocketRef; to: SocketRef } + +export interface Graph { + nodes: Map<number, GNode>; + links: GLink[]; + outputs: Map<string, SocketRef>; +} + +export const OUTPUT_NODE = 0; +export const MAX_NODES = 256; +export const MAX_STOPS = 16; + +const ENUM_DEFAULTS: Readonly<Record<string, string>> = { filter: 'trilinear' }; +const TYPES: readonly SocketType[] = ['float', 'colour', 'vector', 'normal']; +const RESERVED = new Set(['kind', 'inputs', 'position', 'label']); + +const obj = (v: unknown): Record<string, unknown> | null => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null); +const num = (v: unknown, d = 0): number => (typeof v === 'number' && Number.isFinite(v) ? v : d); + +function rgbOf(v: unknown, d: Rgb = [0, 0, 0]): Rgb { + return Array.isArray(v) && v.length >= 3 ? [num(v[0], d[0]), num(v[1], d[1]), num(v[2], d[2])] : [...d]; +} + +function socketSpec(v: unknown): SocketSpec | null { + const o = obj(v); + if (!o || typeof o.name !== 'string') return null; + const ty = TYPES.includes(o.ty as SocketType) ? o.ty as SocketType : 'float'; + return { name: o.name, ty, default: rgbOf(o.default) }; +} + +export function parseCatalogue(raw: unknown): Catalogue { + const o = obj(raw) ?? {}; + const kinds: KindSpec[] = []; + for (const k of Array.isArray(o.kinds) ? o.kinds : []) { + const ko = obj(k); + if (!ko || typeof ko.id !== 'string') continue; + const list = (v: unknown): SocketSpec[] => (Array.isArray(v) ? v.map(socketSpec).filter((s): s is SocketSpec => s !== null) : []); + const settings: SettingSpec[] = []; + for (const s of Array.isArray(ko.settings) ? ko.settings : []) { + const so = obj(s); + if (!so || typeof so.name !== 'string') continue; + settings.push({ name: so.name, kind: typeof so.kind === 'string' ? so.kind : 'enum', values: Array.isArray(so.values) ? so.values.map(String) : [] }); + } + kinds.push({ id: ko.id, label: typeof ko.label === 'string' ? ko.label : ko.id, inputs: list(ko.inputs), outputs: list(ko.outputs), settings, procedural: ko.procedural === true }); + } + const inputs: MaterialInputSpec[] = []; + for (const i of Array.isArray(o.inputs) ? o.inputs : []) { + const io = obj(i); + if (io && typeof io.name === 'string') inputs.push({ name: io.name, colour: io.colour === true, graph: io.graph !== false }); + } + return { kinds, byId: new Map(kinds.map((k) => [k.id, k])), inputs }; +} + +export function emptyGraph(): Graph { + return { nodes: new Map(), links: [], outputs: new Map() }; +} + +function refOf(v: unknown): SocketRef | null { + return Array.isArray(v) && v.length === 2 && typeof v[1] === 'string' && Number.isFinite(Number(v[0])) ? [Number(v[0]), v[1]] : null; +} + +export function parseGraph(raw: unknown): Graph { + const g = emptyGraph(); + const o = obj(raw); + if (!o) return g; + for (const [key, value] of Object.entries(obj(o.nodes) ?? {})) { + const n = obj(value); + const id = Number(key); + if (!n || !Number.isInteger(id) || id <= 0 || typeof n.kind !== 'string') continue; + const settings: Record<string, unknown> = {}; + for (const [k, v] of Object.entries(n)) if (!RESERVED.has(k)) settings[k] = v; + const inputs: Record<string, SocketValue> = {}; + for (const [k, v] of Object.entries(obj(n.inputs) ?? {})) { + if (typeof v === 'number') inputs[k] = v; + else if (Array.isArray(v)) inputs[k] = rgbOf(v); + } + const p = Array.isArray(n.position) ? n.position : []; + g.nodes.set(id, { id, kind: n.kind, settings, inputs, position: [num(p[0]), num(p[1])], label: typeof n.label === 'string' ? n.label : '' }); + } + for (const l of Array.isArray(o.links) ? o.links : []) { + const lo = obj(l); + const from = refOf(lo?.from), to = refOf(lo?.to); + if (from && to) g.links.push({ from, to }); + } + for (const [k, v] of Object.entries(obj(o.outputs) ?? {})) { + const r = refOf(v); + if (r) g.outputs.set(k, r); + } + return g; +} + +export function nodeJson(n: GNode): Record<string, unknown> { + return { ...n.settings, kind: n.kind, inputs: { ...n.inputs }, position: [Math.round(n.position[0]), Math.round(n.position[1])], label: n.label }; +} + +export function graphJson(g: Graph): Record<string, unknown> { + const nodes: Record<string, unknown> = {}; + for (const id of [...g.nodes.keys()].sort((a, b) => a - b)) nodes[String(id)] = nodeJson(g.nodes.get(id) as GNode); + const links = [...g.links].sort((a, b) => cmpRef(a.to, b.to) || cmpRef(a.from, b.from)).map((l) => ({ from: [...l.from], to: [...l.to] })); + const outputs: Record<string, unknown> = {}; + for (const k of [...g.outputs.keys()].sort()) outputs[k] = [...(g.outputs.get(k) as SocketRef)]; + return { nodes, links, outputs }; +} + +function cmpRef(a: SocketRef, b: SocketRef): number { + return a[0] - b[0] || (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0); +} + +export function stable(v: unknown): string { + if (Array.isArray(v)) return '[' + v.map(stable).join(',') + ']'; + const o = obj(v); + if (o) return '{' + Object.keys(o).sort().map((k) => JSON.stringify(k) + ':' + stable(o[k])).join(',') + '}'; + if (typeof v === 'number') return String(Math.fround(v)); + return JSON.stringify(v ?? null); +} + +export const nodeSig = (n: GNode): string => stable(nodeJson(n)); +export const graphSig = (g: Graph): string => stable(graphJson(g)); + +export function cloneGraph(g: Graph): Graph { + return parseGraph(JSON.parse(JSON.stringify(graphJson(g)))); +} + +export function cloneNode(n: GNode, id = n.id): GNode { + return { id, kind: n.kind, settings: JSON.parse(JSON.stringify(n.settings)) as Record<string, unknown>, inputs: JSON.parse(JSON.stringify(n.inputs)) as Record<string, SocketValue>, position: [n.position[0], n.position[1]], label: n.label }; +} + +export const linkKey = (l: GLink): string => `${l.from[0]}:${l.from[1]}>${l.to[0]}:${l.to[1]}`; +export const outputKey = (input: string, r: SocketRef): string => `${r[0]}:${r[1]}>out:${input}`; + +export function nextId(g: Graph): number { + let max = 0; + for (const id of g.nodes.keys()) max = Math.max(max, id); + return max + 1; +} + +export function converts(from: SocketType, to: SocketType): boolean { + if (from === to) return true; + if ((from === 'normal' && to === 'vector') || (from === 'vector' && to === 'normal')) return true; + return from !== 'normal' && to !== 'normal'; +} + +export function outputType(cat: Catalogue, n: GNode, socket: string): SocketType | null { + if (n.kind === 'constant' && socket === 'value') return Array.isArray(n.settings.value) ? 'colour' : 'float'; + return cat.byId.get(n.kind)?.outputs.find((s) => s.name === socket)?.ty ?? null; +} + +export function inputSpec(cat: Catalogue, n: GNode, socket: string): SocketSpec | null { + return cat.byId.get(n.kind)?.inputs.find((s) => s.name === socket) ?? null; +} + +export function materialInputType(cat: Catalogue, input: string): SocketType { + if (input === 'normal') return 'normal'; + return cat.inputs.find((i) => i.name === input)?.colour ? 'colour' : 'float'; +} + +export function linkInto(g: Graph, node: number, socket: string): GLink | undefined { + return g.links.find((l) => l.to[0] === node && l.to[1] === socket); +} + +export function reaches(g: Graph, from: number, target: number): boolean { + const seen = new Set<number>(); + const stack = [from]; + while (stack.length) { + const id = stack.pop() as number; + if (id === target) return true; + if (seen.has(id)) continue; + seen.add(id); + for (const l of g.links) if (l.from[0] === id) stack.push(l.to[0]); + } + return false; +} + +export function defaultSetting(s: SettingSpec): unknown { + switch (s.kind) { + case 'enum': return ENUM_DEFAULTS[s.name] && s.values.includes(ENUM_DEFAULTS[s.name]) ? ENUM_DEFAULTS[s.name] : s.values[0] ?? ''; + case 'u32': return 0; + case 'bool': return false; + case 'texture': return null; + case 'projection': return { kind: 'uv', set: 0 }; + case 'transform': return { offset: [0, 0], scale: [1, 1], rotation: 0, space: 'object' }; + case 'colour_space': return null; + case 'rgba': return [0.5, 0.5, 0.5, 1]; + case 'stops': return [{ position: 0, colour: [0, 0, 0, 1] }, { position: 1, colour: [1, 1, 1, 1] }]; + case 'value': return 0; + default: return null; + } +} + +export function newNode(spec: KindSpec, id: number, position: [number, number]): GNode { + const settings: Record<string, unknown> = {}; + for (const s of spec.settings) settings[s.name] = defaultSetting(s); + return { id, kind: spec.id, settings, inputs: {}, position, label: '' }; +} + +export function inputValue(spec: SocketSpec, n: GNode): SocketValue { + const v = n.inputs[spec.name]; + if (v !== undefined) return v; + return spec.ty === 'colour' ? [...spec.default] : spec.default[0]; +} + +export function removeNodes(g: Graph, ids: ReadonlySet<number>): void { + for (const id of ids) g.nodes.delete(id); + g.links = g.links.filter((l) => !ids.has(l.from[0]) && !ids.has(l.to[0])); + for (const [k, r] of [...g.outputs]) if (ids.has(r[0])) g.outputs.delete(k); +} diff --git a/frontend/src/ui/graph/ramp.ts b/frontend/src/ui/graph/ramp.ts new file mode 100644 index 00000000..753decec --- /dev/null +++ b/frontend/src/ui/graph/ramp.ts @@ -0,0 +1,218 @@ +import { el, escapeHtml, q, setAttr, setClass, setStyleVar, setValue } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { cssOf, fromHex, hexOf, lerpRgba } from './colour'; +import type { Control, Edit } from './fields'; +import { MAX_STOPS, type Rgb } from './model'; + +export interface Stop { position: number; colour: number[] } + +function stopsOf(v: unknown): Stop[] { + if (!Array.isArray(v)) return []; + return v.map((s) => { + const o = (s && typeof s === 'object' ? s : {}) as Record<string, unknown>; + const c = Array.isArray(o.colour) ? o.colour.map(Number) : [0, 0, 0, 1]; + return { position: Number(o.position) || 0, colour: [c[0] ?? 0, c[1] ?? 0, c[2] ?? 0, c[3] ?? 1] }; + }); +} + +const round = (v: number): number => Math.round(v * 1000) / 1000; +const rgb = (c: number[]): Rgb => [c[0], c[1], c[2]]; + +export function sampleStops(stops: Stop[], at: number): number[] { + if (!stops.length) return [0, 0, 0, 1]; + if (at <= stops[0].position) return [...stops[0].colour]; + for (let i = 1; i < stops.length; i++) { + const a = stops[i - 1], b = stops[i]; + if (at <= b.position) return lerpRgba(a.colour, b.colour, b.position > a.position ? (at - a.position) / (b.position - a.position) : 0); + } + return [...stops[stops.length - 1].colour]; +} + +export class RampControl implements Control { + readonly el: HTMLElement; + private readonly bar: HTMLElement; + private readonly track: HTMLElement; + private readonly colour: HTMLInputElement; + private readonly pos: HTMLInputElement; + private readonly remove: HTMLButtonElement; + private stops: Stop[] = []; + private interpolation = 'linear'; + private active = 0; + private dragging = false; + + constructor(private readonly edit: Edit) { + this.el = el(`<div class="fsh-graph-ramp"> +<div class="fsh-graph-ramp-bar" role="presentation"></div> +<div class="fsh-graph-ramp-track"></div> +<div class="fsh-graph-ramp-row"> +<input class="fsh-graph-swatch" type="color" aria-label="${escapeHtml(t('Stop colour'))}"> +<input class="fsh-input fsh-graph-ramp-pos" type="text" inputmode="decimal" spellcheck="false" data-no-i18n aria-label="${escapeHtml(t('Stop position'))}"> +<button type="button" class="fsh-icon-btn fsh-graph-ramp-del" aria-label="${escapeHtml(t('Delete stop'))}" title="${escapeHtml(t('Delete stop'))}">${icon('trash', 14)}</button> +</div> +</div>`); + this.bar = q(this.el, '.fsh-graph-ramp-bar'); + this.track = q(this.el, '.fsh-graph-ramp-track'); + this.colour = q<HTMLInputElement>(this.el, '.fsh-graph-swatch'); + this.pos = q<HTMLInputElement>(this.el, '.fsh-graph-ramp-pos'); + this.remove = q<HTMLButtonElement>(this.el, '.fsh-graph-ramp-del'); + this.bar.title = t('Click to add a stop'); + this.listen(); + } + + setInterpolation(mode: string): void { + if (this.interpolation === mode) return; + this.interpolation = mode; + this.paint(); + } + + set(v: unknown): void { + if (this.dragging) return; + const next = stopsOf(v); + if (!next.length) return; + this.stops = next; + this.active = Math.min(this.active, next.length - 1); + this.paint(); + } + + private send(live: boolean): void { + this.edit(this.stops.map((s) => ({ position: round(s.position), colour: s.colour.map((c) => Math.round(c * 1e5) / 1e5) })), live); + } + + private sortKeep(): void { + const cur = this.stops[this.active]; + this.stops.sort((a, b) => a.position - b.position); + this.active = this.stops.indexOf(cur); + } + + private paint(): void { + const parts: string[] = []; + for (let i = 0; i < this.stops.length; i++) { + const s = this.stops[i], pct = `${(s.position * 100).toFixed(2)}%`, c = cssOf(rgb(s.colour)); + if (this.interpolation === 'constant' && i > 0) parts.push(`${cssOf(rgb(this.stops[i - 1].colour))} ${pct}`); + parts.push(`${c} ${pct}`); + } + const bg = this.stops.length === 1 ? cssOf(rgb(this.stops[0].colour)) : `linear-gradient(to right, ${parts.join(', ')})`; + if (this.bar.style.background !== bg) this.bar.style.background = bg; + const handles = this.track.children; + while (handles.length < this.stops.length) { + const b = el(`<button type="button" class="fsh-graph-ramp-stop"></button>`); + this.track.appendChild(b); + } + while (handles.length > this.stops.length) (this.track.lastElementChild as Element).remove(); + this.stops.forEach((s, i) => { + const h = handles[i] as HTMLElement; + if (h.dataset.index !== String(i)) h.dataset.index = String(i); + setStyleVar(h, '--fsh-graph-at', `${s.position * 100}%`); + setStyleVar(h, '--fsh-graph-stop', cssOf(rgb(s.colour))); + setClass(h, 'is-active', i === this.active); + setAttr(h, 'aria-label', t('Stop {n} at {pos}', { n: i + 1, pos: s.position.toFixed(3) })); + setAttr(h, 'tabindex', i === this.active ? '0' : '-1'); + }); + const a = this.stops[this.active]; + if (a) { + if (document.activeElement !== this.colour) setValue(this.colour, hexOf(rgb(a.colour))); + setValue(this.pos, a.position.toFixed(3)); + } + this.remove.disabled = this.stops.length <= 1; + } + + private at(clientX: number): number { + const r = this.track.getBoundingClientRect(); + return Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))); + } + + private add(position: number): void { + if (this.stops.length >= MAX_STOPS) return; + const s = { position: round(position), colour: sampleStops(this.stops, position) }; + this.stops.push(s); + this.active = this.stops.length - 1; + this.sortKeep(); + this.paint(); + this.send(false); + } + + private drop(): void { + if (this.stops.length <= 1) return; + this.stops.splice(this.active, 1); + this.active = Math.max(0, this.active - 1); + this.paint(); + this.send(false); + (this.track.children[this.active] as HTMLElement | undefined)?.focus(); + } + + private listen(): void { + this.bar.addEventListener('pointerdown', (e) => { + if (e.button !== 0) return; + e.stopPropagation(); + this.add(this.at(e.clientX)); + }); + let pointer = -1, moved = false; + this.track.addEventListener('pointerdown', (e) => { + const h = (e.target as HTMLElement).closest<HTMLElement>('.fsh-graph-ramp-stop'); + e.stopPropagation(); + if (!h || e.button !== 0) { if (!h && e.button === 0) this.add(this.at(e.clientX)); return; } + this.active = Number(h.dataset.index); + pointer = e.pointerId; + moved = false; + h.focus(); + this.paint(); + try { this.track.setPointerCapture(e.pointerId); } catch { pointer = -1; return; } + this.dragging = true; + }); + this.track.addEventListener('pointermove', (e) => { + if (e.pointerId !== pointer) return; + moved = true; + this.stops[this.active].position = round(this.at(e.clientX)); + this.sortKeep(); + this.paint(); + this.send(true); + }); + const end = (e: PointerEvent): void => { + if (e.pointerId !== pointer) return; + pointer = -1; + this.dragging = false; + if (moved) this.send(false); + }; + this.track.addEventListener('pointerup', end); + this.track.addEventListener('pointercancel', end); + this.track.addEventListener('keydown', (e) => { + const h = (e.target as HTMLElement).closest<HTMLElement>('.fsh-graph-ramp-stop'); + if (!h) return; + const step = e.shiftKey ? 0.1 : 0.01; + if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { + const s = this.stops[this.active]; + s.position = round(Math.min(1, Math.max(0, s.position + (e.key === 'ArrowLeft' ? -step : step)))); + this.sortKeep(); + this.paint(); + this.send(false); + (this.track.children[this.active] as HTMLElement).focus(); + } else if (e.key === 'Delete' || e.key === 'Backspace') this.drop(); + else if (e.key === 'Insert' || e.key === '+') this.add(Math.min(1, this.stops[this.active].position + 0.1)); + else return; + e.preventDefault(); + e.stopPropagation(); + }); + this.colour.addEventListener('input', () => { this.recolour(); this.send(true); }); + this.colour.addEventListener('change', () => { this.recolour(); this.send(false); }); + const setPos = (): void => { + const v = parseFloat(this.pos.value.replace(',', '.')); + if (!Number.isFinite(v)) { this.paint(); return; } + this.stops[this.active].position = round(Math.min(1, Math.max(0, v))); + this.sortKeep(); + this.paint(); + this.send(false); + }; + this.pos.addEventListener('change', setPos); + this.pos.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); setPos(); } e.stopPropagation(); }); + this.remove.addEventListener('click', () => this.drop()); + } + + private recolour(): void { + const s = this.stops[this.active]; + if (!s) return; + const c = fromHex(this.colour.value); + s.colour = [c[0], c[1], c[2], s.colour[3] ?? 1]; + this.paint(); + } +} diff --git a/frontend/src/ui/graph/source.ts b/frontend/src/ui/graph/source.ts new file mode 100644 index 00000000..e963d620 --- /dev/null +++ b/frontend/src/ui/graph/source.ts @@ -0,0 +1,57 @@ +import type { Workspace } from '../context'; +import { emptyGraph, parseCatalogue, parseGraph, type Catalogue, type Graph } from './model'; + +export interface TextureInfo { key: string; path: string; name: string } +export interface MaterialData { graph: Graph; textures: TextureInfo[]; name: string } + +const READ_COMMAND = 'material.get'; + +const obj = (v: unknown): Record<string, unknown> | null => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null); + +export function baseName(path: string): string { + const clean = path.replace(/^fshot:/, ''); + const i = Math.max(clean.lastIndexOf('/'), clean.lastIndexOf('\\')); + return i >= 0 ? clean.slice(i + 1) : clean; +} + +function texturesOf(raw: unknown): TextureInfo[] { + const out: TextureInfo[] = []; + const add = (key: unknown, t: unknown): void => { + const o = obj(t); + const k = key ?? o?.key; + if (!o || k === undefined || k === null || typeof o.path !== 'string') return; + out.push({ key: String(k), path: o.path, name: baseName(o.path) }); + }; + if (Array.isArray(raw)) for (const t of raw) add(obj(t)?.key, t); + else for (const [k, t] of Object.entries(obj(raw) ?? {})) add(k, t); + return out.sort((a, b) => Number(a.key) - Number(b.key)); +} + +export class GraphSource { + private kinds: Promise<Catalogue> | null = null; + + constructor(private readonly ws: Workspace) {} + + catalogue(): Promise<Catalogue> { + if (!this.kinds) { + this.kinds = this.ws.client.dispatch('material.node_kinds', {}).then(parseCatalogue); + this.kinds.catch(() => { this.kinds = null; }); + } + return this.kinds; + } + + async read(material: string): Promise<MaterialData> { + if (!this.ws.client.has(READ_COMMAND)) throw new Error(`The engine has no command ${READ_COMMAND}`); + const o = obj(await this.ws.client.dispatch(READ_COMMAND, { key: material })) ?? {}; + const m = obj(o.material); + if (!m) throw new Error('missing material'); + return { graph: m.graph ? parseGraph(m.graph) : emptyGraph(), textures: texturesOf(o.textures), name: typeof m.name === 'string' ? m.name : '' }; + } + + async preview(material: string, size: number): Promise<string | null> { + if (!this.ws.client.has('material.preview_maps')) return null; + const o = obj(await this.ws.client.dispatch('material.preview_maps', { key: material, size })); + const png = obj(o?.maps)?.base_color; + return typeof png === 'string' ? `data:image/png;base64,${png}` : null; + } +} diff --git a/frontend/src/ui/graph/status.ts b/frontend/src/ui/graph/status.ts new file mode 100644 index 00000000..7f50d02d --- /dev/null +++ b/frontend/src/ui/graph/status.ts @@ -0,0 +1,51 @@ +import { el, q, setClass, setText, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; + +const NOTE_MS = 4000; + +export class StatusLine { + private readonly message: HTMLElement; + private readonly revert: HTMLButtonElement; + private readonly zoom: HTMLElement; + private readonly count: HTMLElement; + private hint = ''; + private err = ''; + private fade: number | undefined; + + constructor(host: HTMLElement, onRevert: () => void) { + host.appendChild(el(`<span class="fsh-graph-msg"></span>`)); + host.appendChild(el(`<button type="button" class="fsh-btn is-sm fsh-graph-revert" hidden></button>`)); + host.appendChild(el(`<span class="fsh-graph-count fsh-tabular" data-no-i18n></span>`)); + host.appendChild(el(`<span class="fsh-graph-zoom fsh-tabular" data-no-i18n></span>`)); + this.message = q(host, '.fsh-graph-msg'); + this.revert = q<HTMLButtonElement>(host, '.fsh-graph-revert'); + this.zoom = q(host, '.fsh-graph-zoom'); + this.count = q(host, '.fsh-graph-count'); + setText(this.revert, t('Revert')); + setTitle(this.revert, t('Go back to the last graph the engine accepted')); + this.revert.addEventListener('click', onRevert); + } + + note(text: string, fade = false): void { + window.clearTimeout(this.fade); + this.hint = text; + this.paint(); + if (fade && text) this.fade = window.setTimeout(() => { if (this.hint === text) this.note(''); }, NOTE_MS); + } + + error(text: string): void { + this.err = text; + this.paint(); + } + + setZoom(z: number): void { setText(this.zoom, `${Math.round(z * 100)}%`); } + setCount(nodes: number, links: number): void { setText(this.count, t('{nodes} nodes, {links} links', { nodes, links })); } + + private paint(): void { + const text = this.err || this.hint; + setText(this.message, text); + setTitle(this.message, text); + setClass(this.message, 'is-error', this.err !== ''); + if (this.revert.hidden !== !this.err) this.revert.hidden = !this.err; + } +} diff --git a/frontend/src/ui/graph/views.ts b/frontend/src/ui/graph/views.ts new file mode 100644 index 00000000..90fa72b8 --- /dev/null +++ b/frontend/src/ui/graph/views.ts @@ -0,0 +1,309 @@ +import { el, escapeHtml, q, setAttr, setClass, setText, setTitle, swapMedia } from '../../shell/dom'; +import { t } from '../../i18n'; +import { boolControl, colourControl, numberControl, selectControl, stepFor, type Control, type Edit } from './fields'; +import { TYPE_WORDS, words } from './labels'; +import { inputValue, materialInputType, OUTPUT_NODE, type Catalogue, type GNode, type SettingSpec, type SocketType, type SocketValue } from './model'; +import { RampControl } from './ramp'; +import type { TextureInfo } from './source'; + +export type Dir = 'in' | 'out'; + +export interface Sock { + el: HTMLElement; + row: HTMLElement; + dir: Dir; + name: string; + ty: SocketType; + label: string; + dy: number; +} + +export interface NodeHost { + cat: Catalogue; + textures(): TextureInfo[]; + editInput(node: number, socket: string, value: SocketValue, live: boolean): void; + editSetting(node: number, name: string, value: unknown, live: boolean): void; + addImage(node: number): void; +} + +export const NODE_W = 208; +export const OUTPUT_W = 196; +const ADD_IMAGE = '__add'; +const PROJECTIONS = ['uv', 'box', 'planar', 'cylindrical', 'spherical'] as const; +const SPACES = ['', 'srgb', 'linear', 'acescg', 'data'] as const; + +export function shapeOf(n: GNode): string { + return n.kind === 'constant' ? `constant:${Array.isArray(n.settings.value) ? 'colour' : 'float'}` : n.kind; +} + +function sockHtml(dir: Dir, ty: SocketType, name: string): string { + return `<button type="button" class="fsh-graph-sock is-${dir} is-${ty}" tabindex="-1" data-dir="${dir}" data-sock="${escapeHtml(name)}" data-ty="${ty}"></button>`; +} + +abstract class BaseView { + readonly el: HTMLElement; + readonly sockets = new Map<string, Sock>(); + x = Number.NaN; + y = Number.NaN; + w = NODE_W; + h = 0; + protected readonly body: HTMLElement; + private readonly head: HTMLElement; + + constructor(readonly id: number, title: string, extra: string) { + this.el = el(`<div class="fsh-graph-node ${extra}" role="group" tabindex="-1" aria-selected="false" data-node="${id}"><header class="fsh-graph-node-head"><span class="fsh-graph-node-title"></span><span class="fsh-graph-node-badge" hidden>!</span></header><div class="fsh-graph-node-body"></div></div>`); + this.head = q(this.el, '.fsh-graph-node-head'); + this.body = q(this.el, '.fsh-graph-node-body'); + setText(q(this.el, '.fsh-graph-node-title'), title); + } + + place(x: number, y: number): boolean { + if (x === this.x && y === this.y) return false; + this.x = x; + this.y = y; + this.el.style.transform = `translate(${x}px, ${y}px)`; + return true; + } + + measure(): void { + this.w = this.el.offsetWidth || this.w; + this.h = this.el.offsetHeight; + for (const s of this.sockets.values()) s.dy = s.row.offsetTop + s.row.offsetHeight / 2; + } + + socketAt(dir: Dir, name: string): [number, number] | null { + const s = this.sockets.get(`${dir}:${name}`); + return s && Number.isFinite(this.x) ? [this.x + (dir === 'out' ? this.w : 0), this.y + s.dy] : null; + } + + setSelected(on: boolean): void { + setClass(this.el, 'is-selected', on); + setAttr(this.el, 'aria-selected', on ? 'true' : 'false'); + } + + setError(message: string | null): void { + setClass(this.el, 'is-error', message !== null); + const badge = q(this.head, '.fsh-graph-node-badge'); + if (badge.hidden !== (message === null)) badge.hidden = message === null; + setTitle(badge, message ?? ''); + } + + setLinked(name: string, on: boolean, to: string): void { + const s = this.sockets.get(`in:${name}`); + if (!s) return; + setClass(s.row, 'is-linked', on); + setAttr(s.el, 'aria-label', on ? t('{socket} input, linked from {from}', { socket: s.label, from: to }) : t('{socket} input, {type}', { socket: s.label, type: t(TYPE_WORDS[s.ty]) })); + } + + protected addSocketRow(dir: Dir, name: string, ty: SocketType, label: string, control: Control | null): HTMLElement { + const row = el(`<div class="fsh-graph-row is-${dir}">${sockHtml(dir, ty, name)}<span class="fsh-graph-row-label"></span></div>`); + setText(q(row, '.fsh-graph-row-label'), label); + if (control) { row.classList.add('has-field'); row.appendChild(control.el); } + const sockEl = q(row, '.fsh-graph-sock'); + sockEl.setAttribute('aria-label', dir === 'out' + ? t('{socket} output, {type}', { socket: label, type: t(TYPE_WORDS[ty]) }) + : t('{socket} input, {type}', { socket: label, type: t(TYPE_WORDS[ty]) })); + this.body.appendChild(row); + this.sockets.set(`${dir}:${name}`, { el: sockEl, row, dir, name, ty, label, dy: 0 }); + return row; + } +} + +export class NodeView extends BaseView { + readonly kind: string; + readonly shape: string; + private readonly inputs = new Map<string, Control>(); + private readonly settings = new Map<string, Control>(); + private readonly rgba = new Map<string, number[]>(); + private ramp: RampControl | null = null; + private texture: HTMLSelectElement | null = null; + private texturesSig: string | null = null; + + constructor(private readonly host: NodeHost, node: GNode) { + const spec = host.cat.byId.get(node.kind); + super(node.id, t(spec?.label ?? words(node.kind)), `is-kind-${node.kind}${spec?.procedural ? ' is-pattern' : ''}`); + this.kind = node.kind; + this.shape = shapeOf(node); + this.el.setAttribute('aria-label', t('{kind} node {id}', { kind: t(spec?.label ?? words(node.kind)), id: node.id })); + const outputs = node.kind === 'constant' ? [{ name: 'value', ty: (Array.isArray(node.settings.value) ? 'colour' : 'float') as SocketType }] : (spec?.outputs ?? []); + for (const o of outputs) this.addSocketRow('out', o.name, o.ty, t(words(o.name)), null); + for (const s of spec?.settings ?? []) this.addSetting(node, s); + for (const i of spec?.inputs ?? []) { + const id = node.id, name = i.name; + const edit: Edit = (v, live) => host.editInput(id, name, v as SocketValue, live); + let control: Control | null = null; + if (i.ty === 'float') control = numberControl(words(name), { step: stepFor(i.default[0]) }, edit); + else if (i.ty === 'colour') control = colourControl(words(name), edit); + this.addSocketRow('in', name, i.ty, t(words(name)), control); + if (control) this.inputs.set(name, control); + } + this.update(node); + } + + update(node: GNode): void { + const spec = this.host.cat.byId.get(node.kind); + for (const i of spec?.inputs ?? []) this.inputs.get(i.name)?.set(inputValue(i, node)); + for (const [name, c] of this.settings) c.set(node.settings[name]); + if (this.ramp) this.ramp.setInterpolation(String(node.settings.interpolation ?? 'linear')); + this.refreshTextures(); + const tex = this.texture; + if (tex) { + const v = node.settings.texture; + const want = v === null || v === undefined ? '' : String(v); + if (tex.value !== want) tex.value = want; + } + } + + refreshTextures(): void { + const tex = this.texture; + if (!tex) return; + const list = this.host.textures(); + const sig = list.map((x) => `${x.key}=${x.name}`).join('|'); + if (sig === this.texturesSig) return; + this.texturesSig = sig; + const keep = tex.value; + const want: Array<[string, string]> = [['', t('None')], ...list.map((x): [string, string] => [x.key, x.name]), [ADD_IMAGE, t('Add image...')]]; + const have = new Map<string, HTMLOptionElement>(); + for (const o of Array.from(tex.options)) have.set(o.value, o); + want.forEach(([value, label], i) => { + let o = have.get(value); + if (!o) { o = document.createElement('option'); o.value = value; } + if (o.textContent !== label) o.textContent = label; + if (value !== '' && value !== ADD_IMAGE) o.setAttribute('data-no-i18n', ''); + if (tex.options[i] !== o) tex.insertBefore(o, tex.options[i] ?? null); + have.delete(value); + }); + for (const o of have.values()) o.remove(); + tex.value = keep; + } + + private addRow(control: Control): void { + const row = el('<div class="fsh-graph-row is-setting"></div>'); + row.appendChild(control.el); + this.body.appendChild(row); + } + + private addSetting(node: GNode, s: SettingSpec): void { + const id = node.id, name = s.name; + const edit: Edit = (v, live) => this.host.editSetting(id, name, v, live); + let c: Control | null = null; + switch (s.kind) { + case 'enum': c = selectControl(words(name), s.values.map((v) => [v, words(v)] as const), edit); break; + case 'u32': c = numberControl(words(name), { step: 1, min: 0, integer: true }, edit); break; + case 'bool': c = boolControl(words(name), edit); break; + case 'colour_space': { + const sel = selectControl(words(name), SPACES.map((v) => [v, v ? words(v) : 'Automatic'] as const), (v, live) => edit(v === '' ? null : v, live)); + c = sel; + break; + } + case 'rgba': { + const col = colourControl(words(name), (v, live) => { + const cur = this.currentRgba(name); + const rgb = v as number[]; + edit([rgb[0], rgb[1], rgb[2], cur[3] ?? 1], live); + }); + c = { el: col.el, set: (v) => { if (Array.isArray(v)) { this.rgba.set(name, v.map(Number)); col.set(v); } } }; + break; + } + case 'projection': { + const sel = selectControl(words(name), PROJECTIONS.map((v) => [v, words(v)] as const), (v, live) => edit(v === 'box' ? { kind: 'box', blend: 0.5 } : v === 'uv' ? { kind: 'uv', set: 0 } : { kind: v }, live)); + c = { el: sel.el, set: (v) => sel.set((v && typeof v === 'object' ? (v as Record<string, unknown>).kind : 'uv') ?? 'uv') }; + break; + } + case 'transform': this.addTransform(id, name); return; + case 'texture': this.addTexture(id); return; + case 'stops': { + this.ramp = new RampControl(edit); + const row = el('<div class="fsh-graph-row is-ramp"></div>'); + row.appendChild(this.ramp.el); + this.body.appendChild(row); + this.settings.set(name, this.ramp); + return; + } + case 'value': this.addConstant(node); return; + default: return; + } + if (c) { this.addRow(c); this.settings.set(name, c); } + } + + private currentRgba(name: string): number[] { return this.rgba.get(name) ?? [0.5, 0.5, 0.5, 1]; } + + private addTransform(id: number, name: string): void { + let cur: Record<string, unknown> = {}; + const pair = (v: unknown, i: number, d: number): number => (Array.isArray(v) && typeof v[i] === 'number' ? v[i] as number : d); + const send = (patch: Record<string, unknown>, live: boolean): void => { cur = { ...cur, ...patch }; this.host.editSetting(id, name, cur, live); }; + const parts: Array<[string, (v: number) => Record<string, unknown>, (o: Record<string, unknown>) => number, number]> = [ + ['Scale X', (v) => ({ scale: [v, pair(cur.scale, 1, 1)] }), (o) => pair(o.scale, 0, 1), 0.01], + ['Scale Y', (v) => ({ scale: [pair(cur.scale, 0, 1), v] }), (o) => pair(o.scale, 1, 1), 0.01], + ['Rotation', (v) => ({ rotation: (v * Math.PI) / 180 }), (o) => Math.round(((Number(o.rotation) || 0) * 180) / Math.PI * 100) / 100, 1], + ['Offset X', (v) => ({ offset: [v, pair(cur.offset, 1, 0)] }), (o) => pair(o.offset, 0, 0), 0.01], + ['Offset Y', (v) => ({ offset: [pair(cur.offset, 0, 0), v] }), (o) => pair(o.offset, 1, 0), 0.01], + ]; + const controls = parts.map(([label, patch, , step]) => { + const c = numberControl(label, { step }, (v, live) => send(patch(v as number), live)); + this.addRow(c); + return c; + }); + this.settings.set(name, { + el: this.body, + set: (v) => { + cur = v && typeof v === 'object' ? { ...(v as Record<string, unknown>) } : {}; + parts.forEach(([, , read], i) => controls[i].set(read(cur))); + }, + }); + } + + private addTexture(id: number): void { + const row = el(`<div class="fsh-graph-row is-setting"><label class="fsh-graph-field is-select"><span class="fsh-graph-field-label">${escapeHtml(t(words('texture')))}</span><select class="fsh-input fsh-graph-select" aria-label="${escapeHtml(t(words('texture')))}"></select></label></div>`); + const sel = q<HTMLSelectElement>(row, 'select'); + this.texture = sel; + let last = ''; + sel.addEventListener('focus', () => { last = sel.value; }); + sel.addEventListener('change', () => { + if (sel.value === ADD_IMAGE) { sel.value = last; this.host.addImage(id); return; } + last = sel.value; + this.host.editSetting(id, 'texture', sel.value === '' ? null : Number(sel.value), false); + }); + this.body.appendChild(row); + this.refreshTextures(); + } + + private addConstant(node: GNode): void { + const id = node.id; + const colour = Array.isArray(node.settings.value); + const type = selectControl('Type', [['float', 'Number'], ['colour', 'Colour']], (v) => { + this.host.editSetting(id, 'value', v === 'colour' ? [0.5, 0.5, 0.5] : 0.5, false); + }); + type.set(colour ? 'colour' : 'float'); + this.addRow(type); + const edit: Edit = (v, live) => this.host.editSetting(id, 'value', v, live); + const c = colour ? colourControl(words('value'), edit) : numberControl(words('value'), { step: 0.01 }, edit); + this.addRow(c); + this.settings.set('value', c); + } +} + +export class OutputView extends BaseView { + private readonly swatch: HTMLImageElement; + private readonly box: HTMLElement; + + constructor(cat: Catalogue) { + super(OUTPUT_NODE, t('Material output'), 'is-output'); + this.w = OUTPUT_W; + this.el.setAttribute('aria-label', t('Material output')); + this.box = el(`<div class="fsh-graph-preview is-empty"><img alt="" decoding="async" draggable="false"></div>`); + this.swatch = q<HTMLImageElement>(this.box, 'img'); + this.swatch.alt = t('Material preview'); + this.body.appendChild(this.box); + for (const i of cat.inputs) { + if (!i.graph) continue; + this.addSocketRow('in', i.name, materialInputType(cat, i.name), t(words(i.name)), null); + } + } + + async setPreview(src: string | null): Promise<void> { + if (!src) return; + try { await swapMedia(this.swatch, src); } catch { return; } + setClass(this.box, 'is-empty', false); + } +} diff --git a/frontend/src/ui/graph/window.ts b/frontend/src/ui/graph/window.ts new file mode 100644 index 00000000..06682479 --- /dev/null +++ b/frontend/src/ui/graph/window.ts @@ -0,0 +1,155 @@ +import { el, q, setText } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; + +export interface Box { x: number; y: number; w: number; h: number } + +const STORE = 'formshot.graph.window'; +const MIN_W = 520; +const MIN_H = 360; +const EDGES = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'] as const; + +function stored(): Box | null { + try { + const v = JSON.parse(sessionStorage.getItem(STORE) ?? 'null') as Partial<Box> | null; + if (v && [v.x, v.y, v.w, v.h].every((n) => typeof n === 'number' && Number.isFinite(n))) return v as Box; + } catch { return null; } + return null; +} + +export class EditorWindow { + readonly root: HTMLElement; + readonly body: HTMLElement; + readonly tools: HTMLElement; + readonly status: HTMLElement; + private readonly title: HTMLElement; + private box: Box; + private before: Element | null = null; + onClose: (() => void) | null = null; + + constructor(host: HTMLElement) { + this.root = el(`<section class="fsh-graph-win" role="dialog" aria-modal="false" aria-labelledby="fsh-graph-title" hidden> +<header class="fsh-graph-head"> +<span class="fsh-graph-grip" aria-hidden="true"></span> +<h2 class="fsh-graph-title" id="fsh-graph-title"></h2> +<div class="fsh-graph-tools"></div> +<button type="button" class="fsh-icon-btn fsh-graph-close" aria-label="${t('Close')}" title="${t('Close')} (Esc)">${icon('close', 16)}</button> +</header> +<div class="fsh-graph-body"></div> +<footer class="fsh-graph-status" aria-live="polite"></footer> +${EDGES.map((e) => `<span class="fsh-graph-edge is-${e}" data-edge="${e}" aria-hidden="true"></span>`).join('')} +</section>`); + this.title = q(this.root, '.fsh-graph-title'); + this.body = q(this.root, '.fsh-graph-body'); + this.tools = q(this.root, '.fsh-graph-tools'); + this.status = q(this.root, '.fsh-graph-status'); + this.box = this.clamp(stored() ?? this.initial()); + this.place(); + host.appendChild(this.root); + q(this.root, '.fsh-graph-close').addEventListener('click', () => this.close()); + this.listen(); + window.addEventListener('resize', () => { if (!this.root.hidden) { this.box = this.clamp(this.box); this.place(); } }); + } + + get open(): boolean { return !this.root.hidden; } + get rect(): Box { return { ...this.box }; } + + setTitle(text: string): void { setText(this.title, text); } + + show(): void { + if (!this.root.hidden) return; + this.before = document.activeElement; + this.box = this.clamp(this.box); + this.place(); + this.root.hidden = false; + } + + close(): void { + if (this.root.hidden) return; + this.root.hidden = true; + this.onClose?.(); + if (this.before instanceof HTMLElement && this.before.isConnected) this.before.focus(); + } + + private initial(): Box { + const w = Math.max(MIN_W, Math.round(window.innerWidth * 0.72)); + const h = Math.max(MIN_H, Math.round(window.innerHeight * 0.7)); + return { x: Math.round((window.innerWidth - w) / 2), y: Math.round((window.innerHeight - h) / 2), w, h }; + } + + private clamp(b: Box): Box { + const vw = window.innerWidth, vh = window.innerHeight; + const w = Math.min(Math.max(MIN_W, b.w), Math.max(MIN_W, vw)); + const h = Math.min(Math.max(MIN_H, b.h), Math.max(MIN_H, vh)); + const x = Math.min(Math.max(b.x, 40 - w), vw - 40); + const y = Math.min(Math.max(b.y, 0), vh - 36); + return { x: Math.round(x), y: Math.round(y), w: Math.round(w), h: Math.round(h) }; + } + + private place(): void { + const s = this.root.style; + const tr = `translate(${this.box.x}px, ${this.box.y}px)`; + if (s.transform !== tr) s.transform = tr; + if (s.width !== `${this.box.w}px`) s.width = `${this.box.w}px`; + if (s.height !== `${this.box.h}px`) s.height = `${this.box.h}px`; + } + + private save(): void { + try { sessionStorage.setItem(STORE, JSON.stringify(this.box)); } catch { return; } + } + + private listen(): void { + const head = q(this.root, '.fsh-graph-head'); + let mode: string | null = null; + let start = { x: 0, y: 0 }; + let from: Box = this.box; + let pointer = -1; + const down = (e: PointerEvent, m: string, target: HTMLElement): void => { + if (e.button !== 0) return; + mode = m; + pointer = e.pointerId; + start = { x: e.clientX, y: e.clientY }; + from = { ...this.box }; + target.setPointerCapture(e.pointerId); + e.preventDefault(); + }; + head.addEventListener('pointerdown', (e) => { + if ((e.target as HTMLElement).closest('button, input, select')) return; + down(e, 'move', head); + }); + for (const edge of this.root.querySelectorAll<HTMLElement>('.fsh-graph-edge')) { + edge.addEventListener('pointerdown', (e) => down(e, edge.dataset.edge ?? 'se', edge)); + } + const move = (e: PointerEvent): void => { + if (e.pointerId !== pointer || !mode) return; + const dx = e.clientX - start.x, dy = e.clientY - start.y; + const b = { ...from }; + if (mode === 'move') { b.x += dx; b.y += dy; } + else { + if (mode.includes('e')) b.w = Math.max(MIN_W, from.w + dx); + if (mode.includes('s')) b.h = Math.max(MIN_H, from.h + dy); + if (mode.includes('w')) { b.w = Math.max(MIN_W, from.w - dx); b.x = from.x + from.w - b.w; } + if (mode.includes('n')) { b.h = Math.max(MIN_H, from.h - dy); b.y = from.y + from.h - b.h; } + } + this.box = this.clamp(b); + this.place(); + }; + const up = (e: PointerEvent): void => { + if (e.pointerId !== pointer) return; + pointer = -1; + mode = null; + this.save(); + }; + this.root.addEventListener('pointermove', move); + this.root.addEventListener('pointerup', up); + this.root.addEventListener('pointercancel', up); + head.addEventListener('dblclick', (e) => { + if ((e.target as HTMLElement).closest('button')) return; + const vw = window.innerWidth, vh = window.innerHeight; + const full = this.box.w >= vw - 16 && this.box.h >= vh - 16; + this.box = this.clamp(full ? this.initial() : { x: 8, y: 8, w: vw - 16, h: vh - 16 }); + this.place(); + this.save(); + }); + } +} diff --git a/frontend/src/ui/handoff/browse.ts b/frontend/src/ui/handoff/browse.ts new file mode 100644 index 00000000..2c308f63 --- /dev/null +++ b/frontend/src/ui/handoff/browse.ts @@ -0,0 +1,95 @@ +import { Dialog } from '../../shell/dialog'; +import { el, patchList, q, setDisabled, setHidden, setText, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; +import { ago, appName, offerLine } from './describe'; +import { service, type Offer, type OpenMode, type OpenResult } from './service'; + +export interface BrowseHost { + opened: (offer: { title: string; app_name: string }, mode: OpenMode, result: OpenResult) => void; +} + +function row(): HTMLElement { + return el(`<li class="fsh-handoff-item"><button type="button" class="fsh-handoff-pick"> + <span class="fsh-handoff-item-app" data-no-i18n></span> + <span class="fsh-handoff-item-title" data-no-i18n></span> + <span class="fsh-handoff-item-line"></span> + <span class="fsh-handoff-item-when fsh-tabular"></span> +</button></li>`); +} + +export function browse(host: BrowseHost): void { + const d = new Dialog('Open a Hand-off', 'wide'); + const body = el(`<div class="fsh-handoff-browse"> + <p class="fsh-note">What FormSculpt and FormFabric put in the GoF folder and what FormSurface exported. Opening one here needs no prompt, because you chose it.</p> + <ul class="fsh-handoff-list" aria-label="Hand-offs"></ul> + <p class="fsh-handoff-empty fsh-note" hidden>Nothing from the Form apps is waiting in their hand-off folders.</p> + <div class="fsh-handoff-sources fsh-note fsh-selectable" data-no-i18n></div> + <label class="fsh-handoff-field"><span>Or a path to a file or folder</span><input class="fsh-input fsh-handoff-path-input" type="text" spellcheck="false" placeholder="/path/to/export"></label> + <fieldset class="fsh-handoff-mode"> + <legend class="fsh-handoff-legend">Open it</legend> + <label class="fsh-handoff-choice"><input type="radio" name="fsh-handoff-browse-mode" value="add" checked><span>Add to this document</span></label> + <label class="fsh-handoff-choice"><input type="radio" name="fsh-handoff-browse-mode" value="new"><span>As a new document</span></label> + </fieldset> + <p class="fsh-handoff-error" role="status" hidden></p> +</div>`); + d.body.appendChild(body); + const list = q(body, '.fsh-handoff-list'); + const empty = q(body, '.fsh-handoff-empty'); + const error = q(body, '.fsh-handoff-error'); + const input = q<HTMLInputElement>(body, '.fsh-handoff-path-input'); + let chosen: Offer | null = null; + let busy = false; + const mode = (): OpenMode => (body.querySelector<HTMLInputElement>('input[name="fsh-handoff-browse-mode"]:checked')?.value as OpenMode) || 'add'; + const fail = (text: string): void => { setText(error, text); setHidden(error, !text); }; + const mark = (): void => { + for (const li of list.querySelectorAll<HTMLElement>('.fsh-handoff-item')) li.classList.toggle('is-chosen', li.dataset.key === chosen?.key); + }; + const go = async (): Promise<void> => { + if (busy) return; + const path = input.value.trim() || chosen?.path || ''; + if (!path) { fail(t('Choose a hand-off or give a path')); return; } + const item = input.value.trim() ? null : chosen?.item ?? null; + busy = true; + setDisabled(open, true); + fail(''); + try { + const m = mode(); + const result = await service.open(path, item, m); + host.opened({ title: chosen && !input.value.trim() ? chosen.title : path.split('/').pop() ?? path, app_name: chosen && !input.value.trim() ? appName(chosen) : '' }, m, result); + d.close(); + } catch (err) { + fail(err instanceof Error ? err.message : String(err)); + } finally { + busy = false; + setDisabled(open, false); + } + }; + d.action('Cancel', () => d.close()); + const open = d.action('Open', go, 'primary'); + input.addEventListener('input', () => { if (input.value.trim()) { chosen = null; mark(); } }); + input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); void go(); } }); + d.open(); + void service.available().then((reply) => { + patchList(list, reply.items, { + key: (o) => o.key, + create: (o) => { + const li = row(); + q(li, 'button').addEventListener('click', () => { chosen = reply.items.find((x) => x.key === li.dataset.key) ?? o; input.value = ''; mark(); }); + q(li, 'button').addEventListener('dblclick', () => void go()); + return li; + }, + update: () => undefined, + }); + for (const li of list.querySelectorAll<HTMLElement>('.fsh-handoff-item')) { + const o = reply.items.find((x) => x.key === li.dataset.key); + if (!o) continue; + setText(q(li, '.fsh-handoff-item-app'), appName(o)); + setText(q(li, '.fsh-handoff-item-title'), o.title); + setText(q(li, '.fsh-handoff-item-line'), offerLine(o)); + setText(q(li, '.fsh-handoff-item-when'), ago(o.changed * 1000)); + setTitle(q(li, 'button'), o.item ? `${o.path}/${o.item}` : o.path); + } + setHidden(empty, reply.items.length > 0); + setText(q(body, '.fsh-handoff-sources'), reply.sources.map((s) => `${t(s.label)}: ${s.folder}${s.found ? '' : ` (${t('not found')})`}`).join('\n')); + }, (err: unknown) => fail(err instanceof Error ? err.message : String(err))); +} diff --git a/frontend/src/ui/handoff/describe.ts b/frontend/src/ui/handoff/describe.ts new file mode 100644 index 00000000..7b9043ab --- /dev/null +++ b/frontend/src/ui/handoff/describe.ts @@ -0,0 +1,54 @@ +import { t } from '../../i18n'; +import type { Inspection, Offer } from './service'; + +const ROLES: Record<string, string> = { + base_colour: 'Base colour', + roughness: 'Roughness', + metalness: 'Metalness', + normal: 'Normal', + bump: 'Height', + opacity: 'Opacity', + emission: 'Emission', + occlusion_roughness_metalness: 'Occlusion, roughness and metalness', + other: 'Other maps', +}; + +export function appName(o: { app_name?: string | null; app?: string | null }): string { + return o.app_name || o.app || t('another app'); +} + +export function kindText(i: Inspection): string { + if (i.kind === 'map_folder') return i.materials_only ? t('Maps by role, without a mesh') : t('A mesh with maps by role'); + if (i.kind === 'gof_folder') return t('An object from the GoF folder'); + return t('A model file'); +} + +export function offerLine(o: Offer): string { + if (o.source === 'formsurface') return t('{count} maps from FormSurface', { count: o.maps ?? 0 }); + if (typeof o.triangles === 'number') return t('{format} file, {count} triangles', { format: o.format.toUpperCase(), count: o.triangles.toLocaleString() }); + return t('{format} file', { format: o.format.toUpperCase() }); +} + +export function contentsText(i: Inspection): string { + const c = i.contents; + if (!c) return t('Not read yet'); + if (c.error) return c.error; + if (i.materials_only) return t('{count} materials', { count: c.materials.length }); + return t('{meshes} meshes, {triangles} triangles, {materials} materials', { + meshes: c.meshes, triangles: c.triangles.toLocaleString(), materials: c.materials.length, + }); +} + +export function mapsText(i: Inspection): string { + if (!i.maps.length) return t('None'); + const roles = i.roles.map((r) => t(ROLES[r] ?? 'Other maps')); + return t('{count} maps: {roles}', { count: i.maps.length, roles: roles.join(', ') }); +} + +export function ago(ms: number): string { + const s = Math.max(0, Math.round((Date.now() - ms) / 1000)); + if (s < 60) return t('just now'); + if (s < 3600) return t('{n} min ago', { n: Math.round(s / 60) }); + if (s < 86400) return t('{n} h ago', { n: Math.round(s / 3600) }); + return t('{n} days ago', { n: Math.round(s / 86400) }); +} diff --git a/frontend/src/ui/handoff/handoff.css b/frontend/src/ui/handoff/handoff.css new file mode 100644 index 00000000..7037923d --- /dev/null +++ b/frontend/src/ui/handoff/handoff.css @@ -0,0 +1,29 @@ +.fsh-handoff-count { min-width: 8ch; color: var(--text-muted); font-size: var(--fs-12); text-align: right; } +.fsh-handoff-lede { display: -webkit-box; min-height: calc(var(--fs-13) * var(--lh) * 2); margin: 0 0 var(--space-3); overflow: hidden; color: var(--text-primary); font-size: var(--fs-13); line-height: var(--lh); -webkit-box-orient: vertical; -webkit-line-clamp: 2; } +.fsh-handoff-facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: var(--space-1) var(--space-3); margin: 0 0 var(--space-3); font-size: var(--fs-12); } +.fsh-handoff-facts dt { color: var(--text-muted); } +.fsh-handoff-facts dd { min-height: calc(var(--fs-12) * 1.5); margin: 0; overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-handoff-facts dd.fsh-handoff-maps { display: -webkit-box; min-height: calc(var(--fs-12) * 3); white-space: normal; -webkit-box-orient: vertical; -webkit-line-clamp: 2; } +.fsh-handoff-path { font-family: var(--font-mono); font-size: var(--fs-11); } +.fsh-handoff-mode { display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-4); margin: 0 0 var(--space-3); padding: var(--space-2) var(--space-3); border: 1px solid var(--line-1); border-radius: var(--radius-md); } +.fsh-handoff-legend { padding: 0 var(--space-1); color: var(--text-muted); font-size: var(--fs-11); } +.fsh-handoff-choice { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--text-primary); font-size: var(--fs-12); cursor: pointer; } +.fsh-handoff-choice input { accent-color: var(--accent); } +.fsh-handoff-note { margin: 0; } +.fsh-handoff-error { margin: var(--space-2) 0 0; color: var(--danger-text); font-size: var(--fs-12); } +.fsh-handoff-browse { display: grid; gap: var(--space-3); } +.fsh-handoff-browse > .fsh-note { margin: 0; } +.fsh-handoff-list { display: grid; gap: var(--space-1); max-height: 280px; min-height: 120px; margin: 0; padding: var(--space-1); overflow-y: auto; list-style: none; border: 1px solid var(--line-1); border-radius: var(--radius-md); background: var(--surface-field); } +.fsh-handoff-pick { display: grid; grid-template-columns: 12ch minmax(0, 1fr) auto; grid-template-rows: auto auto; align-items: center; column-gap: var(--space-3); width: 100%; height: 44px; padding: 0 var(--space-3); border: 1px solid transparent; border-radius: var(--radius); background: transparent; color: var(--text-primary); text-align: left; cursor: pointer; } +.fsh-handoff-pick:hover { background: var(--bg-hover); } +.fsh-handoff-item.is-chosen .fsh-handoff-pick { border-color: var(--accent-line); background: var(--accent-tint); } +.fsh-handoff-item-app { grid-row: 1 / 3; color: var(--text-muted); font-size: var(--fs-11); } +.fsh-handoff-item-title { overflow: hidden; font-size: var(--fs-13); text-overflow: ellipsis; white-space: nowrap; } +.fsh-handoff-item-line { grid-column: 2; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-handoff-item-when { grid-column: 3; grid-row: 1 / 3; min-width: 10ch; color: var(--text-faint); font-size: var(--fs-11); text-align: right; } +.fsh-handoff-sources { margin: 0; font-family: var(--font-mono); font-size: var(--fs-11); white-space: pre-wrap; word-break: break-all; } +.fsh-handoff-field { display: grid; gap: var(--space-1); color: var(--text-muted); font-size: var(--fs-11); } +.fsh-handoff-settings { display: grid; gap: var(--space-3); } +.fsh-handoff-settings > .fsh-note { margin: 0; } +.fsh-handoff-apps { display: grid; gap: var(--space-2); } +.fsh-handoff-app { display: grid; grid-template-columns: minmax(0, 1fr) 16ch; align-items: center; gap: var(--space-3); min-height: var(--ctl); color: var(--text-primary); font-size: var(--fs-13); } diff --git a/frontend/src/ui/handoff/index.ts b/frontend/src/ui/handoff/index.ts new file mode 100644 index 00000000..f6166dc4 --- /dev/null +++ b/frontend/src/ui/handoff/index.ts @@ -0,0 +1,48 @@ +import './handoff.css'; +import type { ModuleContext } from '../../shell/app-shell'; +import { browse } from './browse'; +import { appName } from './describe'; +import { Prompt } from './prompt'; +import { service, type Offer } from './service'; +import { settingsPage } from './settings'; + +const SETTINGS_PAGE = 'handoff'; + +export function mount(ctx: ModuleContext): void { + const said = (offer: object, mode: string): string => { + const o = offer as { title?: unknown; app?: unknown; app_name?: unknown }; + const vars = { title: String(o.title ?? ''), app: appName({ app: String(o.app ?? ''), app_name: String(o.app_name ?? '') }) }; + return mode === 'new' ? ctx.t('Opened {title} from {app} as a new document', vars) : ctx.t('Added {title} from {app}', vars); + }; + const prompt = new Prompt({ + opened: (offer, mode) => ctx.toast(said(offer, mode)), + failed: (message) => ctx.toast(message, 'error'), + }); + const sync = async (): Promise<void> => { + try { + const reply = await service.offers(); + prompt.set(reply.offers); + } catch { + return; + } + }; + ctx.events.on('handoff.offered', (e) => { if (e.offer && typeof e.offer === 'object') prompt.add(e.offer as Offer); }); + ctx.events.on('handoff.withdrawn', (e) => prompt.withdraw(String(e.id ?? ''))); + ctx.events.on('handoff.opened', (e) => { if (e.auto === true) ctx.toast(said(e, String(e.mode ?? 'add'))); }); + ctx.events.on('hello', () => void sync()); + ctx.events.on('resync', () => void sync()); + ctx.onReady(() => void sync()); + + ctx.registry.registerCommand({ + id: 'handoff.browse', label: 'Open a Hand-off...', group: 'File', icon: 'import', + description: 'Open what FormSculpt, FormFabric, FormSurface or FormCAD handed over', + run: () => browse({ opened: (o, mode) => ctx.toast(said(o, mode)) }), + }); + ctx.registry.registerCommand({ id: 'handoff.settings', label: 'Hand-off Settings', group: 'File', palette: false, run: () => ctx.registry.runCommand('app.settings', { page: SETTINGS_PAGE }) }); + ctx.registry.registerMenu({ id: 'file', items: [{ command: 'handoff.browse', section: 3 }] }); + ctx.registry.registerSettingsPage({ + id: SETTINGS_PAGE, title: 'Hand-offs', icon: 'import', order: 60, group: 'Files', + keywords: ['FormSculpt', 'FormSurface', 'FormFabric', 'FormCAD', 'GoF', 'hand-off', 'send to'], + mount: settingsPage, + }); +} diff --git a/frontend/src/ui/handoff/prompt.ts b/frontend/src/ui/handoff/prompt.ts new file mode 100644 index 00000000..be207909 --- /dev/null +++ b/frontend/src/ui/handoff/prompt.ts @@ -0,0 +1,168 @@ +import { el, q, setDisabled, setHidden, setText, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; +import { appName, contentsText, kindText, mapsText, offerLine } from './describe'; +import { service, type Answer, type Inspection, type Offer, type OpenMode } from './service'; + +export interface PromptHost { + opened: (offer: Offer, mode: OpenMode) => void; + failed: (message: string) => void; +} + +export class Prompt { + private readonly root: HTMLElement; + private readonly queue: Offer[] = []; + private readonly details = new Map<string, Inspection | string>(); + private readonly loading = new Set<string>(); + private readonly before: { el: Element | null } = { el: null }; + private busy = false; + + constructor(private readonly host: PromptHost) { + this.root = el(`<div class="fsh-scrim fsh-handoff-scrim" hidden> + <div class="fsh-dialog fsh-handoff" role="alertdialog" aria-modal="true" aria-labelledby="fsh-handoff-title" aria-describedby="fsh-handoff-lede"> + <header class="fsh-dialog-head"><h2 class="fsh-dialog-title" id="fsh-handoff-title">A Form app is handing something over</h2><span class="fsh-handoff-count fsh-tabular" data-no-i18n></span></header> + <div class="fsh-dialog-body"> + <p class="fsh-handoff-lede" id="fsh-handoff-lede"></p> + <dl class="fsh-handoff-facts"> + <dt>Sent as</dt><dd class="fsh-handoff-kind"></dd> + <dt>Contents</dt><dd class="fsh-handoff-contents"></dd> + <dt>Maps</dt><dd class="fsh-handoff-maps"></dd> + <dt>From</dt><dd class="fsh-handoff-path fsh-selectable" data-no-i18n></dd> + </dl> + <fieldset class="fsh-handoff-mode"> + <legend class="fsh-handoff-legend">Open it</legend> + <label class="fsh-handoff-choice"><input type="radio" name="fsh-handoff-mode" value="add" checked><span>Add to this document</span></label> + <label class="fsh-handoff-choice"><input type="radio" name="fsh-handoff-mode" value="new"><span>As a new document</span></label> + </fieldset> + <p class="fsh-note fsh-handoff-note">Nothing is opened until you choose. Textures stay where the app wrote them and are referenced by role.</p> + <p class="fsh-handoff-error" role="status" hidden></p> + </div> + <footer class="fsh-dialog-foot"> + <button type="button" class="fsh-btn fsh-handoff-btn" data-answer="deny">Decline</button> + <button type="button" class="fsh-btn fsh-handoff-btn" data-answer="once">Open once</button> + <button type="button" class="fsh-btn is-primary fsh-handoff-btn fsh-handoff-always" data-answer="always"></button> + </footer> + </div> +</div>`); + for (const b of this.root.querySelectorAll<HTMLButtonElement>('.fsh-handoff-btn')) { + b.addEventListener('click', () => void this.answer(b.dataset.answer as Answer)); + } + this.root.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { e.stopPropagation(); void this.answer('deny'); } + }); + (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); + } + + get waiting(): number { return this.queue.length; } + + set(offers: Offer[]): void { + const ids = new Set(offers.map((o) => o.id)); + for (let i = this.queue.length - 1; i >= 0; i--) if (!ids.has(this.queue[i].id)) this.queue.splice(i, 1); + for (const o of offers) if (!this.queue.some((x) => x.id === o.id)) this.queue.push(o); + this.render(); + } + + add(offer: Offer): void { + const at = this.queue.findIndex((o) => o.id === offer.id || o.key === offer.key); + if (at >= 0) this.queue.splice(at, 1, offer); + else this.queue.push(offer); + this.render(); + } + + withdraw(id: string): void { + const at = this.queue.findIndex((o) => o.id === id); + if (at < 0) return; + this.queue.splice(at, 1); + this.details.delete(id); + this.render(); + } + + private mode(): OpenMode { + return (this.root.querySelector<HTMLInputElement>('input[name="fsh-handoff-mode"]:checked')?.value as OpenMode) || 'add'; + } + + private render(): void { + const offer = this.queue[0]; + const wasHidden = this.root.hidden; + if (!offer) { + setHidden(this.root, true); + if (!wasHidden && this.before.el instanceof HTMLElement) this.before.el.focus(); + return; + } + const app = appName(offer); + setText(q(this.root, '.fsh-handoff-count'), this.queue.length > 1 ? t('1 of {count}', { count: this.queue.length }) : ''); + setText(q(this.root, '.fsh-handoff-lede'), t('{app} is handing over {title}: {what}.', { app, title: offer.title, what: offerLine(offer) })); + setText(q(this.root, '.fsh-handoff-always'), t('Always allow {app}', { app })); + setHidden(q(this.root, '.fsh-handoff-always'), !offer.app); + const path = offer.item ? `${offer.path}/${offer.item}` : offer.path; + setText(q(this.root, '.fsh-handoff-path'), path); + setTitle(q(this.root, '.fsh-handoff-path'), path); + this.showDetails(offer); + this.error(offer.error ?? ''); + if (wasHidden) { + this.before.el = document.activeElement; + setHidden(this.root, false); + q<HTMLButtonElement>(this.root, '.fsh-handoff-btn[data-answer="once"]').focus(); + } + void this.load(offer); + } + + private showDetails(offer: Offer): void { + const d = this.details.get(offer.id); + const kind = q(this.root, '.fsh-handoff-kind'); + const contents = q(this.root, '.fsh-handoff-contents'); + const maps = q(this.root, '.fsh-handoff-maps'); + if (d === undefined) { + for (const n of [kind, contents, maps]) setText(n, t('Reading...')); + } else if (typeof d === 'string') { + setText(kind, t('Could not be read')); + setText(contents, d); + setText(maps, ''); + } else { + setText(kind, kindText(d)); + setText(contents, contentsText(d)); + setText(maps, mapsText(d)); + } + } + + private async load(offer: Offer): Promise<void> { + if (this.details.has(offer.id) || this.loading.has(offer.id)) return; + this.loading.add(offer.id); + let found: Inspection | string; + try { + found = await service.inspect(offer.path, offer.item); + } catch (err) { + found = err instanceof Error ? err.message : String(err); + } + this.loading.delete(offer.id); + this.details.set(offer.id, found); + if (this.queue[0]?.id === offer.id) this.showDetails(offer); + } + + private error(text: string): void { + const n = q(this.root, '.fsh-handoff-error'); + setText(n, text); + setHidden(n, !text); + } + + private async answer(answer: Answer): Promise<void> { + const offer = this.queue[0]; + if (!offer || this.busy) return; + this.busy = true; + const buttons = [...this.root.querySelectorAll<HTMLButtonElement>('.fsh-handoff-btn')]; + for (const b of buttons) setDisabled(b, true); + const mode = this.mode(); + try { + await service.answer(offer.id, answer, mode); + this.withdraw(offer.id); + if (answer !== 'deny') this.host.opened(offer, mode); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + this.error(message); + if (/no longer waiting/.test(message)) this.withdraw(offer.id); + else this.host.failed(message); + } finally { + this.busy = false; + for (const b of buttons) setDisabled(b, false); + } + } +} diff --git a/frontend/src/ui/handoff/service.ts b/frontend/src/ui/handoff/service.ts new file mode 100644 index 00000000..d0d2461b --- /dev/null +++ b/frontend/src/ui/handoff/service.ts @@ -0,0 +1,67 @@ +import { api } from '../../shell/api'; + +export type AppChoice = 'ask' | 'allowed' | 'blocked'; +export type Answer = 'deny' | 'once' | 'always'; +export type OpenMode = 'add' | 'new'; + +export interface Offer { + id: string; + key: string; + source: 'gof' | 'formsurface'; + path: string; + item: string | null; + file: string; + app: string | null; + app_name: string; + title: string; + format: string; + target: string; + triangles?: number; + maps?: number; + mesh?: boolean; + changed: number; + arrived: number; + error?: string; +} + +export interface Source { id: string; label: string; apps: string[]; folder: string; found: boolean } + +export interface OffersReply { + offers: Offer[]; + apps: Record<string, AppChoice>; + names: Record<string, string>; + sources: Source[]; +} + +export interface MapInfo { file: string; map: string; source: string; role: string; colour_space: string; texture_set: string; udim: number | null } + +export interface Inspection { + path: string; + kind: 'model' | 'map_folder' | 'gof_folder'; + app: string | null; + app_name: string | null; + writer: string | null; + title: string; + model: string | null; + format: string | null; + design_unit: string | null; + materials_only: boolean; + template: string | null; + texture_sets: string[]; + maps: MapInfo[]; + roles: string[]; + warnings: string[]; + contents?: { meshes: number; triangles: number; nodes: number; materials: string[]; textures: number; unit: string | null; warnings: string[]; error?: string }; +} + +export interface OpenResult { title?: string; app_name?: string; created?: unknown[] } + +export const service = { + offers: () => api.get<OffersReply>('/api/handoff/offers'), + answer: (id: string, answer: Answer, mode: OpenMode) => api.post<{ ok: boolean; result?: OpenResult }>(`/api/handoff/offers/${encodeURIComponent(id)}`, { answer, as: mode }, { timeoutMs: 600_000 }), + apps: () => api.get<{ apps: Record<string, AppChoice>; names: Record<string, string> }>('/api/handoff/apps'), + setApp: (app: string, choice: AppChoice) => api.post<{ apps: Record<string, AppChoice> }>('/api/handoff/apps', { app, choice }), + available: () => api.get<{ items: Offer[]; sources: Source[] }>('/api/handoff/available'), + inspect: (path: string, item: string | null) => api.post<Inspection>('/api/handoff/inspect', item ? { path, item } : { path }, { timeoutMs: 120_000 }), + open: (path: string, item: string | null, mode: OpenMode) => api.post<OpenResult>('/api/handoff/open', item ? { path, item, as: mode } : { path, as: mode }, { timeoutMs: 600_000 }), +}; diff --git a/frontend/src/ui/handoff/settings.ts b/frontend/src/ui/handoff/settings.ts new file mode 100644 index 00000000..d8e4cf47 --- /dev/null +++ b/frontend/src/ui/handoff/settings.ts @@ -0,0 +1,44 @@ +import { el, q, setHidden, setText, setValue } from '../../shell/dom'; +import { t } from '../../i18n'; +import { service, type AppChoice } from './service'; + +const APPS: [string, string][] = [['formsculpt', 'FormSculpt'], ['formfabric', 'FormFabric'], ['formsurface', 'FormSurface'], ['formcad', 'FormCAD']]; + +export function settingsPage(host: HTMLElement): void { + const root = el(`<div class="fsh-handoff-settings"> + <p class="fsh-note">FormShot watches the GoF folder and FormSurface's exports while this window is open. When a Form app hands something over, FormShot asks here before opening it.</p> + <div class="fsh-handoff-apps"></div> + <div class="fsh-handoff-sources fsh-note fsh-selectable" data-no-i18n></div> + <p class="fsh-handoff-error" role="status" hidden>The FormShot service is not reachable, so these choices cannot be read or changed now.</p> +</div>`); + const apps = q(root, '.fsh-handoff-apps'); + const error = q(root, '.fsh-handoff-error'); + const selects = new Map<string, HTMLSelectElement>(); + for (const [id, name] of APPS) { + const r = el(`<label class="fsh-handoff-app"><span class="fsh-handoff-app-name" data-no-i18n></span><select class="fsh-input fsh-handoff-app-choice"> + <option value="ask">Ask each time</option> + <option value="allowed">Always allow</option> + <option value="blocked">Block</option> +</select></label>`); + setText(q(r, '.fsh-handoff-app-name'), name); + const s = q<HTMLSelectElement>(r, 'select'); + s.setAttribute('aria-label', t('Hand-offs from {app}', { app: name })); + s.addEventListener('change', () => { + void service.setApp(id, s.value as AppChoice).then(() => setHidden(error, true), () => { setHidden(error, false); void read(); }); + }); + selects.set(id, s); + apps.appendChild(r); + } + const read = async (): Promise<void> => { + try { + const reply = await service.offers(); + for (const [id, s] of selects) setValue(s, reply.apps[id] ?? 'ask'); + setText(q(root, '.fsh-handoff-sources'), reply.sources.map((x) => `${t(x.label)}: ${x.folder}${x.found ? '' : ` (${t('not found')})`}`).join('\n')); + setHidden(error, true); + } catch { + setHidden(error, false); + } + }; + host.appendChild(root); + void read(); +} diff --git a/frontend/src/ui/import/desktop.ts b/frontend/src/ui/import/desktop.ts new file mode 100644 index 00000000..f9a4c7a2 --- /dev/null +++ b/frontend/src/ui/import/desktop.ts @@ -0,0 +1,74 @@ +import { api } from '../../shell/api'; +import { inTauri } from '../../shell/dom'; +import { t } from '../../i18n'; +import { isModel, MODEL_EXTS } from './formats'; + +export type NativeDrop = + | { type: 'enter'; paths: string[] } + | { type: 'over'; x: number; y: number } + | { type: 'drop'; paths: string[]; x: number; y: number } + | { type: 'leave' }; + +export const desktop = (): boolean => inTauri(); + +const OPEN_EVENT = 'formshot://open-paths'; + +export async function listenOpens(fn: (paths: string[]) => void): Promise<() => void> { + if (!desktop()) return () => undefined; + const strings = (raw: unknown): string[] => (Array.isArray(raw) ? raw.filter((p): p is string => typeof p === 'string' && p !== '') : []); + try { + const { listen } = await import('@tauri-apps/api/event'); + const { invoke } = await import('@tauri-apps/api/core'); + const off = await listen<unknown>(OPEN_EVENT, (e) => { + const paths = strings(e.payload); + if (paths.length) fn(paths); + }); + const waiting = strings(await invoke<unknown>('take_pending_opens')); + if (waiting.length) fn(waiting); + return off; + } catch { + return () => undefined; + } +} + +export async function pickPaths(): Promise<string[] | null> { + if (!desktop()) return null; + try { + const { invoke } = await import('@tauri-apps/api/core'); + const picked = await invoke<string | string[] | null>('plugin:dialog|open', { + options: { multiple: true, directory: false, title: t('Import Model'), filters: [{ name: t('3D models'), extensions: [...MODEL_EXTS] }] }, + }); + if (picked === null) return []; + return Array.isArray(picked) ? picked : [picked]; + } catch { + return null; + } +} + +export async function expandPaths(paths: readonly string[]): Promise<string[]> { + try { + const out = await api.post<{ files?: Array<{ path?: unknown }> }>('/api/imports/scan', { paths }); + const found = (out.files ?? []).map((f) => f.path).filter((p): p is string => typeof p === 'string'); + if (found.length || !paths.some(isModel)) return found; + } catch { + return paths.filter(isModel); + } + return paths.filter(isModel); +} + +export async function listenNativeDrop(fn: (e: NativeDrop) => void): Promise<() => void> { + if (!desktop()) return () => undefined; + try { + const { getCurrentWebview } = await import('@tauri-apps/api/webview'); + const ratio = (): number => window.devicePixelRatio || 1; + return await getCurrentWebview().onDragDropEvent((event) => { + const p = event.payload; + if (p.type === 'enter') fn({ type: 'enter', paths: p.paths }); + else if (p.type === 'over') fn({ type: 'over', x: p.position.x / ratio(), y: p.position.y / ratio() }); + else if (p.type === 'drop') fn({ type: 'drop', paths: p.paths, x: p.position.x / ratio(), y: p.position.y / ratio() }); + else fn({ type: 'leave' }); + }); + } catch { + return () => undefined; + } +} diff --git a/frontend/src/ui/import/drop.ts b/frontend/src/ui/import/drop.ts new file mode 100644 index 00000000..53dae5dc --- /dev/null +++ b/frontend/src/ui/import/drop.ts @@ -0,0 +1,99 @@ +import { el, q, setClass, setStyleVar } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { desktop, listenNativeDrop } from './desktop'; +import { FORMAT_LABELS } from './formats'; +import { droppedFiles, type LocalFile } from './upload'; + +export interface DropTarget { + files(items: LocalFile[]): void; + paths(paths: string[]): void; + onHome(paths: string[]): void; +} + +const DOM_DROP_WINDOW_MS = 600; +const NATIVE_SETTLE_MS = 300; + +const homeOpen = (): boolean => { const h = document.getElementById('fsh-home'); return !!h && !h.hidden; }; +const dialogOpen = (): boolean => document.querySelector('#overlay-root .fsh-scrim:not([hidden])') !== null; +const carriesFiles = (e: DragEvent): boolean => Array.from(e.dataTransfer?.types ?? []).includes('Files'); + +export function mountDropZone(overlayRoot: HTMLElement, viewport: HTMLElement, target: DropTarget): void { + const chips = FORMAT_LABELS.map((f) => `<span class="fsh-imp-drop-chip">${f}</span>`).join(''); + const root = el(`<div class="fsh-imp-drop" hidden aria-hidden="true"> +<div class="fsh-imp-drop-frame"></div> +<div class="fsh-imp-drop-card"><span class="fsh-imp-drop-icon">${icon('import', 26)}</span> +<p class="fsh-imp-drop-title">${t('Drop to import into the scene')}</p> +<p class="fsh-imp-drop-chips" translate="no">${chips}</p> +<p class="fsh-imp-drop-hint">${t('Several files import one after another. Buffers, materials and textures beside a model go with it.')}</p> +</div></div>`); + overlayRoot.appendChild(root); + const frame = q(root, '.fsh-imp-drop-frame'); + + const place = (): void => { + const r = viewport.getBoundingClientRect(); + setStyleVar(frame, '--fsh-imp-drop-x', `${Math.round(r.left)}px`); + setStyleVar(frame, '--fsh-imp-drop-y', `${Math.round(r.top)}px`); + setStyleVar(frame, '--fsh-imp-drop-w', `${Math.round(r.width)}px`); + setStyleVar(frame, '--fsh-imp-drop-h', `${Math.round(r.height)}px`); + }; + const over = (x: number, y: number): void => { + const r = viewport.getBoundingClientRect(); + setClass(root, 'is-viewport', x >= r.left && x <= r.right && y >= r.top && y <= r.bottom); + }; + const show = (): void => { + if (!root.hidden) return; + place(); + root.hidden = false; + }; + const hide = (): void => { + if (root.hidden) return; + root.hidden = true; + setClass(root, 'is-viewport', false); + }; + + let depth = 0; + let lastDomDrop = 0; + const wanted = (e: DragEvent): boolean => carriesFiles(e) && !homeOpen() && !dialogOpen(); + + window.addEventListener('drop', (e) => { if (carriesFiles(e)) lastDomDrop = performance.now(); }, true); + window.addEventListener('dragenter', (e) => { + if (!wanted(e) || desktop()) return; + depth++; + show(); + }); + window.addEventListener('dragover', (e) => { + if (!wanted(e) || desktop()) return; + e.preventDefault(); + if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'; + show(); + over(e.clientX, e.clientY); + }); + window.addEventListener('dragleave', (e) => { + if (desktop() || root.hidden) return; + depth = Math.max(0, depth - 1); + if (depth === 0 || e.relatedTarget === null) { depth = 0; hide(); } + }); + window.addEventListener('drop', (e) => { + depth = 0; + hide(); + if (desktop() || e.defaultPrevented || !wanted(e) || !e.dataTransfer) return; + e.preventDefault(); + void droppedFiles(e.dataTransfer).then((items) => target.files(items)); + }); + window.addEventListener('blur', () => { depth = 0; hide(); }); + + void listenNativeDrop((d) => { + if (d.type === 'leave') { hide(); return; } + if (d.type === 'enter') { if (!homeOpen() && !dialogOpen()) show(); return; } + if (d.type === 'over') { if (!root.hidden) over(d.x, d.y); return; } + hide(); + if (dialogOpen() || !d.paths.length) return; + if (!homeOpen()) { target.paths(d.paths); return; } + const at = performance.now(); + window.setTimeout(() => { + if (Math.abs(lastDomDrop - at) < DOM_DROP_WINDOW_MS) return; + target.onHome(d.paths); + }, NATIVE_SETTLE_MS); + }); +} diff --git a/frontend/src/ui/import/engine.ts b/frontend/src/ui/import/engine.ts new file mode 100644 index 00000000..af0e9f24 --- /dev/null +++ b/frontend/src/ui/import/engine.ts @@ -0,0 +1,213 @@ +import { api, ApiError } from '../../shell/api'; +import { t } from '../../i18n'; + +export const COMMANDS = { + probe: 'import.probe', + start: 'import.start', + status: 'import.status', + cancel: 'import.cancel', + direct: 'file.import', + reimport: 'file.reimport', + summary: 'scene.summary', +} as const; + +export type Units = 'auto' | 'mm' | 'cm' | 'm' | 'in' | 'ft'; +export type UpAxis = 'auto' | 'y' | 'z'; +export type CadQuality = 'draft' | 'medium' | 'high' | 'ultra'; +export const UNITS: readonly Units[] = ['auto', 'mm', 'cm', 'm', 'in', 'ft']; +export const CAD_QUALITIES: readonly CadQuality[] = ['draft', 'medium', 'high', 'ultra']; + +export interface ImportOptions { + units: Units; + up_axis: UpAxis; + stand_on_floor: boolean; + center: boolean; + frame: boolean; + merge: boolean; + cad_quality?: CadQuality; +} + +export interface Probe { + format: string; + unitsDeclared: string; + unitsGuess: string; + unitGuessed: boolean; + upAxis: string; + size: [number, number, number] | null; + triangles: number | null; + meshes: number | null; + nodes: number | null; + materials: number | null; + warnings: string[]; +} + +export type JobState = 'running' | 'done' | 'failed' | 'cancelled'; + +export interface Progress { stage: string; fraction: number | null } + +export interface Outcome { state: 'done' | 'failed' | 'cancelled'; result: unknown; error: string } + +const POLL_MS = 200; +const POLL_FAILURES = 5; + +type Obj = Record<string, unknown>; +const obj = (v: unknown): Obj => (v && typeof v === 'object' && !Array.isArray(v) ? v as Obj : {}); +const str = (v: unknown): string => (typeof v === 'string' ? v : ''); +const count = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : Array.isArray(v) ? v.length : null); + +function vec(v: unknown): [number, number, number] | null { + if (!Array.isArray(v) || v.length < 3) return null; + const n = v.slice(0, 3).map(Number); + return n.every(Number.isFinite) ? [n[0], n[1], n[2]] : null; +} + +export function parseProbe(raw: unknown): Probe { + const o = obj(raw); + const b = obj(o.bounds); + const lo = vec(b.min), hi = vec(b.max); + const warnings = Array.isArray(o.warnings) ? o.warnings.map((w) => (typeof w === 'string' ? w : str(obj(w).message))).filter(Boolean) : []; + return { + format: str(o.format), + unitsDeclared: str(o.units_declared), + unitsGuess: str(o.units_guess), + unitGuessed: o.unit_guessed === true, + upAxis: str(o.up_axis), + size: lo && hi ? [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]] : null, + triangles: count(o.triangles), + meshes: count(o.meshes), + nodes: count(o.nodes), + materials: count(o.materials), + warnings, + }; +} + +export function errorText(err: unknown): string { + if (err instanceof ApiError || err instanceof Error) return err.message; + return String(err); +} + +class Catalogue { + state: 'unknown' | 'ready' | 'down' = 'unknown'; + reason = ''; + private names = new Set<string>(); + private loading: Promise<void> | null = null; + private readonly fns = new Set<() => void>(); + + onChange(fn: () => void): () => void { this.fns.add(fn); return () => { this.fns.delete(fn); }; } + has(name: string): boolean { return this.names.has(name); } + + load(): Promise<void> { + if (this.loading) return this.loading; + this.loading = api.catalogue({ timeoutMs: 8000 }).then((cat) => { + this.names = new Set(cat.commands.map((c) => c.name).filter((n) => typeof n === 'string')); + this.state = 'ready'; + this.reason = ''; + }).catch((err: unknown) => { + this.state = 'down'; + this.reason = errorText(err); + }).finally(() => { + this.loading = null; + for (const fn of this.fns) fn(); + }); + return this.loading; + } + + why(name: string): string { + if (this.state === 'unknown') return t('Waiting for the engine'); + if (this.state === 'down') return this.reason || t('The engine is not available'); + if (!this.has(name)) return t('The engine has no command {name} yet', { name }); + return ''; + } + + canImport(): boolean { return this.state === 'ready' && (this.has(COMMANDS.start) || this.has(COMMANDS.direct)); } + importReason(): string { return this.has(COMMANDS.start) ? '' : this.why(COMMANDS.direct); } +} + +export const catalogue = new Catalogue(); + +export async function probe(path: string): Promise<Probe> { + return parseProbe(await api.dispatch(COMMANDS.probe, { path }, { timeoutMs: 120000 })); +} + +function args(path: string, o: ImportOptions): Obj { + const out: Obj = { path, units: o.units, up_axis: o.up_axis, stand_on_floor: o.stand_on_floor, center: o.center, frame: o.frame, merge: o.merge }; + if (o.cad_quality) out.cad_quality = o.cad_quality; + return out; +} + +const sleep = (ms: number): Promise<void> => new Promise((r) => window.setTimeout(r, ms)); + +export class ImportJob { + private job: unknown = null; + private cancelAsked = false; + readonly cancellable: boolean; + + constructor(private readonly path: string, private readonly options: ImportOptions, private readonly onProgress: (p: Progress) => void) { + this.cancellable = catalogue.has(COMMANDS.start) && catalogue.has(COMMANDS.cancel); + } + + async run(): Promise<Outcome> { + if (!catalogue.has(COMMANDS.start)) return this.direct(); + let started: Obj; + try { + started = obj(await api.dispatch(COMMANDS.start, args(this.path, this.options))); + } catch (err) { + return { state: 'failed', result: null, error: errorText(err) }; + } + this.job = started.job ?? null; + if (this.job === null) return { state: 'failed', result: null, error: t('The engine did not start an import job') }; + if (this.cancelAsked) void this.sendCancel(); + let failures = 0; + for (;;) { + await sleep(POLL_MS); + let s: Obj; + try { + s = obj(await api.dispatch(COMMANDS.status, { job: this.job }, { timeoutMs: 15000 })); + failures = 0; + } catch (err) { + if (++failures >= POLL_FAILURES) return { state: 'failed', result: null, error: errorText(err) }; + continue; + } + const state = str(s.state) as JobState; + const fraction = typeof s.fraction === 'number' && Number.isFinite(s.fraction) ? Math.min(1, Math.max(0, s.fraction)) : null; + this.onProgress({ stage: str(s.stage), fraction }); + if (state === 'done') return { state, result: s.result ?? null, error: '' }; + if (state === 'cancelled') return { state, result: null, error: '' }; + if (state === 'failed') return { state, result: null, error: str(s.error) || str(obj(s.error).message) || t('The import failed') }; + } + } + + cancel(): void { + if (!this.cancellable || this.cancelAsked) return; + this.cancelAsked = true; + if (this.job !== null) void this.sendCancel(); + } + + private async sendCancel(): Promise<void> { + try { await api.dispatch(COMMANDS.cancel, { job: this.job }); } catch { return; } + } + + private async direct(): Promise<Outcome> { + this.onProgress({ stage: 'importing', fraction: null }); + try { + const result = await api.dispatch(COMMANDS.direct, args(this.path, this.options), { timeoutMs: 600000 }); + return { state: 'done', result, error: '' }; + } catch (err) { + return { state: 'failed', result: null, error: errorText(err) }; + } + } +} + +export interface ResultCounts { parts: number | null; triangles: number | null; warnings: string[] } + +export function resultCounts(raw: unknown): ResultCounts { + const o = obj(raw); + const report = obj(o.report); + const pick = (...vals: unknown[]): number | null => { for (const v of vals) { const n = count(v); if (n !== null) return n; } return null; }; + const w = Array.isArray(report.warnings) ? report.warnings : Array.isArray(o.warnings) ? o.warnings : []; + return { + parts: pick(o.parts, o.meshes, o.created, report.meshes), + triangles: pick(o.triangles, report.triangles), + warnings: w.map((x) => (typeof x === 'string' ? x : str(obj(x).message))).filter(Boolean), + }; +} diff --git a/frontend/src/ui/import/formats.ts b/frontend/src/ui/import/formats.ts new file mode 100644 index 00000000..fd4bf13f --- /dev/null +++ b/frontend/src/ui/import/formats.ts @@ -0,0 +1,29 @@ +export const MODEL_EXTS = ['glb', 'gltf', 'obj', 'stl', 'ply', '3mf', 'fbx', 'step', 'stp', 'iges', 'igs'] as const; +export const CAD_EXTS: readonly string[] = ['step', 'stp', 'iges', 'igs']; +export const SIBLING_EXTS: readonly string[] = ['bin', 'mtl', 'png', 'jpg', 'jpeg', 'webp', 'ktx2', 'tga', 'bmp', 'tif', 'tiff', 'exr', 'hdr', 'dds', 'gif']; +export const FORMAT_LABELS: readonly string[] = ['GLB', 'glTF', 'OBJ', 'STL', 'PLY', '3MF', 'FBX', 'STEP', 'IGES']; + +export const extOf = (name: string): string => (/\.([a-z0-9]+)$/i.exec(name)?.[1] ?? '').toLowerCase(); +export const baseName = (p: string): string => p.split(/[\\/]/).pop() ?? p; +export const stemOf = (name: string): string => baseName(name).replace(/\.[^.]+$/, ''); +export const isModel = (name: string): boolean => (MODEL_EXTS as readonly string[]).includes(extOf(name)); +export const isCad = (name: string): boolean => CAD_EXTS.includes(extOf(name)); +export const isSibling = (name: string): boolean => SIBLING_EXTS.includes(extOf(name)); +export const acceptList = (): string => [...MODEL_EXTS, ...SIBLING_EXTS].map((x) => `.${x}`).join(','); + +export function formatName(name: string): string { + const ext = extOf(name); + if (ext === 'glb') return 'GLB'; + if (ext === 'gltf') return 'glTF'; + if (ext === 'stp' || ext === 'step') return 'STEP'; + if (ext === 'igs' || ext === 'iges') return 'IGES'; + return ext.toUpperCase(); +} + +export function bytesText(n: number): string { + if (!Number.isFinite(n) || n <= 0) return ''; + const units = ['B', 'KB', 'MB', 'GB']; + let v = n, i = 0; + while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; } + return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`; +} diff --git a/frontend/src/ui/import/import.css b/frontend/src/ui/import/import.css new file mode 100644 index 00000000..2926bff7 --- /dev/null +++ b/frontend/src/ui/import/import.css @@ -0,0 +1,59 @@ +.fsh-imp { display: grid; gap: var(--space-3); color: var(--text-primary); font-size: var(--fs-12); } + +.fsh-imp-file { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--space-2); height: 40px; padding: 0 var(--space-3); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-1); } +.fsh-imp-file-icon { display: inline-flex; color: var(--text-secondary); } +.fsh-imp-file-text { display: grid; min-width: 0; line-height: var(--lh-tight); } +.fsh-imp-name { overflow: hidden; font-size: var(--fs-13); font-weight: var(--fw-medium); text-overflow: ellipsis; white-space: nowrap; } +.fsh-imp-meta { overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-imp-count { min-width: 7ch; color: var(--text-muted); font-size: var(--fs-11); text-align: right; } + +.fsh-imp-cols { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr); gap: var(--space-4); } +.fsh-imp-head { margin: 0 0 var(--space-2); color: var(--text-secondary); font-size: var(--fs-11); font-weight: var(--fw-semibold); letter-spacing: 0.04em; text-transform: uppercase; } + +.fsh-imp-facts { display: grid; gap: 0; margin: 0; } +.fsh-imp-facts > div { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; height: 24px; border-bottom: 1px solid var(--line-1); } +.fsh-imp-facts dt { overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-imp-facts dd { min-width: 10ch; margin: 0; color: var(--text-primary); text-align: right; white-space: nowrap; } + +.fsh-imp-notes { height: 84px; margin-top: var(--space-2); overflow-y: auto; overscroll-behavior: contain; color: var(--text-muted); font-size: var(--fs-11); line-height: var(--lh); } +.fsh-imp-notes-text { margin: 0; } +.fsh-imp-warnings { margin: 0; padding-left: var(--space-4); color: var(--warn); } +.fsh-imp-warnings:empty { display: none; } + +.fsh-imp-options { display: grid; align-content: start; gap: var(--space-1); } +.fsh-imp-row { display: grid; grid-template-columns: minmax(0, 1fr) 168px; align-items: center; gap: var(--space-2); height: var(--ctl-lg); color: var(--text-secondary); } +.fsh-imp-row > select { width: 100%; } +.fsh-imp-check { display: flex; align-items: center; gap: var(--space-2); height: var(--ctl-md); color: var(--text-primary); cursor: pointer; } +.fsh-imp-check input { margin: 0; accent-color: var(--accent-color); } +.fsh-imp-cad.is-off { visibility: hidden; } + +.fsh-imp-unit-note { display: grid; grid-template-columns: 14px minmax(0, 1fr); gap: var(--space-1); height: 32px; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); line-height: var(--lh-tight); } +.fsh-imp-unit-icon { visibility: hidden; color: var(--warn); } +.fsh-imp-unit-note.is-warn { color: var(--warn); } +.fsh-imp-unit-note.is-warn .fsh-imp-unit-icon { visibility: visible; } + +.fsh-imp-progress { display: grid; grid-template-columns: 22ch minmax(0, 1fr) 5ch; align-items: center; gap: var(--space-3); height: 24px; visibility: hidden; } +.fsh-imp-progress.is-on { visibility: visible; } +.fsh-imp-stage { overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; white-space: nowrap; } +.fsh-imp-bar { position: relative; height: 6px; overflow: hidden; border-radius: var(--radius-pill); background: var(--line-2); } +.fsh-imp-fill { position: absolute; inset: 0; border-radius: inherit; background: var(--accent-color); transform: scaleX(var(--fsh-imp-fraction, 0)); transform-origin: left center; transition: transform var(--dur-fast) linear; } +.fsh-imp-progress.is-indeterminate .fsh-imp-fill { width: 30%; transform: none; animation: fsh-imp-slide calc(var(--dur-slow) * 3) ease-in-out infinite; } +.fsh-imp-pct { color: var(--text-muted); text-align: right; } +@keyframes fsh-imp-slide { from { transform: translateX(-100%); } to { transform: translateX(340%); } } + +.fsh-imp-reason { height: 1.4em; margin: 0; overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } + +.fsh-imp-drop { position: fixed; inset: 0; z-index: var(--z-modal); display: grid; place-items: center; background: var(--bg-scrim); pointer-events: none; } +.fsh-imp-drop[hidden] { display: none; } +.fsh-imp-drop-frame { position: fixed; left: var(--fsh-imp-drop-x, 0); top: var(--fsh-imp-drop-y, 0); width: var(--fsh-imp-drop-w, 0); height: var(--fsh-imp-drop-h, 0); box-sizing: border-box; border: 2px dashed var(--line-3); border-radius: var(--radius-lg); transition: border-color var(--dur-fast), background-color var(--dur-fast); } +.fsh-imp-drop.is-viewport .fsh-imp-drop-frame { border-color: var(--accent-color); background: var(--accent-wash); } +.fsh-imp-drop-card { display: grid; justify-items: center; gap: var(--space-2); width: min(440px, calc(100vw - 48px)); padding: var(--space-6) var(--space-6) var(--space-5); border: 1px solid var(--glass-border); border-radius: var(--radius-2xl); background: var(--glass-bg); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); text-align: center; } +.fsh-imp-drop-icon { display: inline-flex; color: var(--accent-color); } +.fsh-imp-drop-title { margin: 0; color: var(--text-primary); font-size: var(--fs-16); font-weight: var(--fw-semibold); } +.fsh-imp-drop-chips { display: flex; flex-wrap: wrap; justify-content: center; gap: var(--space-1); margin: 0; } +.fsh-imp-drop-chip { padding: 1px var(--space-2); border: 1px solid var(--line-3); border-radius: var(--radius-sm); color: var(--text-secondary); font-family: var(--font-mono); font-size: var(--fs-10); } +.fsh-imp-drop-hint { margin: 0; color: var(--text-muted); font-size: var(--fs-12); line-height: var(--lh); } + +.fsh-imp-dialog .fsh-dialog-foot .fsh-btn { min-width: 104px; } +.fsh-imp-dialog .fsh-dialog-foot .fsh-imp-all { margin-right: auto; order: -1; } +.fsh-imp-dialog .fsh-dialog-foot .fsh-imp-all[data-hidden] { visibility: hidden; } diff --git a/frontend/src/ui/import/index.ts b/frontend/src/ui/import/index.ts new file mode 100644 index 00000000..a8971900 --- /dev/null +++ b/frontend/src/ui/import/index.ts @@ -0,0 +1,223 @@ +import './import.css'; +import type { ModuleContext } from '../../shell/app-shell'; +import { api } from '../../shell/api'; +import type { CommandSpec, MenuEntry } from '../../shell/registry'; +import { t } from '../../i18n'; +import { catalogue, COMMANDS, errorText, resultCounts, type Outcome } from './engine'; +import { acceptList, baseName, extOf, isModel, stemOf } from './formats'; +import { desktop, expandPaths, listenOpens, pickPaths } from './desktop'; +import { confirmDialog } from '../../shell/dialog'; +import { mountDropZone } from './drop'; +import { forgetImports, recentImports, rememberImport } from './recent'; +import { ImportSheet, type Source } from './sheet'; +import { groupFiles, type LocalFile } from './upload'; + +const REFRESH_EVENTS = ['scene.changed', 'document.changed']; + +export interface Importer { + files(items: readonly LocalFile[]): void; + paths(paths: readonly string[]): Promise<void>; + pick(): Promise<void>; +} + +function idsOf(raw: unknown): string[] { + const o = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {}; + const sel = Array.isArray(o.selection) ? o.selection : []; + return sel.map((v) => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : '')).filter(Boolean); +} + +export function mount(ctx: ModuleContext): void { + const { registry, events } = ctx; + const reload = (): void => { void catalogue.load(); }; + events.on('hello', reload); + events.on('resync', reload); + catalogue.onChange(() => registry.refreshState()); + reload(); + + const changed = (): void => { for (const type of REFRESH_EVENTS) events.emit({ type }); }; + + const finished = (name: string, path: string, outcome: Outcome): void => { + if (outcome.state === 'cancelled') { ctx.toast(t('The import of {name} was cancelled.', { name })); return; } + if (outcome.state === 'failed') { ctx.toast(t('Could not import {name}: {reason}', { name, reason: outcome.error }), 'error'); return; } + const c = resultCounts(outcome.result); + let text = t('Imported {name}.', { name }); + if (c.parts !== null && c.parts > 1 && c.triangles !== null) text = t('Imported {name}: {parts} parts, {triangles} triangles.', { name, parts: c.parts, triangles: new Intl.NumberFormat().format(c.triangles) }); + else if (c.parts !== null && c.parts > 1) text = t('Imported {name}: {parts} parts.', { name, parts: c.parts }); + if (c.warnings.length > 1) text = `${text} ${t('{n} warnings; the Scene page lists the parts.', { n: c.warnings.length })}`; + else if (c.warnings.length === 1) text = `${text} ${c.warnings[0]}`; + ctx.toast(text); + changed(); + events.emit({ type: 'ui.import.done', name, path }); + }; + + const open = (sources: Source[]): void => { + if (!sources.length) { + ctx.toast(t('Nothing to import: FormShot imports GLB, glTF, OBJ, STL, PLY, 3MF, FBX, STEP and IGES files.'), 'error'); + return; + } + if (catalogue.state !== 'ready') reload(); + new ImportSheet(sources, { finished }).open(); + }; + + const picker = document.createElement('input'); + picker.type = 'file'; + picker.multiple = true; + picker.accept = acceptList(); + picker.hidden = true; + picker.className = 'fsh-imp-picker'; + ctx.slots.overlayRoot.appendChild(picker); + picker.addEventListener('change', () => { + const files = Array.from(picker.files ?? []); + picker.value = ''; + importer.files(files.map((file) => ({ file, rel: file.name }))); + }); + + const importer: Importer = { + files(items) { + open(groupFiles(items).map((job) => ({ kind: 'browser', job, name: job.main.name }))); + }, + async paths(paths) { + const found = paths.every(isModel) ? [...paths] : await expandPaths(paths); + open(found.map((path) => ({ kind: 'path', path, name: baseName(path) }))); + }, + async pick() { + const chosen = await pickPaths(); + if (chosen === null) { picker.click(); return; } + if (chosen.length) await importer.paths(chosen); + }, + }; + + const run = (args?: Record<string, unknown>): Promise<void> | void => { + const a = args ?? {}; + if (Array.isArray(a.files)) { + const files = a.files.filter((f): f is File => f instanceof File); + importer.files(files.map((file) => ({ file, rel: file.webkitRelativePath || file.name }))); + return; + } + const list = Array.isArray(a.paths) ? a.paths.filter((p): p is string => typeof p === 'string') : typeof a.path === 'string' && a.path ? [a.path] : []; + if (list.length) return importer.paths(list); + return importer.pick(); + }; + + const importSpec: CommandSpec = { + id: 'file.import', label: 'Import Model...', group: 'File', icon: 'import', keys: ['Mod+I'], + description: desktop() ? 'Choose model files and import them into the scene with options.' : 'Send model files to FormShot and import them into the scene with options.', + run, + }; + const existing = registry.getCommand('file.import'); + if (existing) Object.assign(existing, { label: importSpec.label, description: importSpec.description, icon: importSpec.icon, enabled: undefined, run }); + else registry.registerCommand(importSpec); + + registry.registerCommands([ + { id: 'import.files', label: 'Import Files', group: 'File', palette: false, run }, + { + id: 'file.reimport', label: 'Reimport', group: 'File', icon: 'refresh', + description: 'Read the source files of the selected parts (or of every imported part) again, keeping their materials.', + enabled: () => catalogue.has(COMMANDS.reimport), + run: async () => { + let nodes: string[] = []; + try { nodes = idsOf(await api.dispatch(COMMANDS.summary, {})); } catch { nodes = []; } + try { + const out = await api.dispatch(COMMANDS.reimport, nodes.length ? { nodes } : {}, { timeoutMs: 600000 }); + const o = out && typeof out === 'object' ? out as Record<string, unknown> : {}; + const n = (k: string): number => (typeof o[k] === 'number' ? o[k] as number : Array.isArray(o[k]) ? (o[k] as unknown[]).length : 0); + ctx.toast(t('Reimported: updated {matched}, new {added}, hidden {hidden}.', { matched: n('matched'), added: n('added'), hidden: n('hidden') })); + changed(); + } catch (err) { + ctx.toast(t('Could not reimport: {reason}', { reason: errorText(err) }), 'error'); + } + }, + }, + ]); + registry.registerMenu({ id: 'file', items: [{ command: 'file.reimport', section: 2 }] }); + + let recentOff: (() => void) | null = null; + let recentKey = ''; + const syncRecent = (): void => { + const list = recentImports(); + const key = list.map((r) => r.path).join('\n'); + if (key === recentKey && recentOff) return; + recentKey = key; + recentOff?.(); + const items: MenuEntry[] = list.length + ? [...list.map((r) => ({ command: 'import.recent', label: r.name, args: { path: r.path } })), { command: 'import.clearRecent', section: 1 }] + : [{ command: 'import.noRecent' }]; + recentOff = registry.registerMenu({ id: 'file', items: [{ label: 'Recent Imports', section: 2, items }] }); + }; + registry.registerCommands([ + { + id: 'import.recent', label: 'Import Recent File', group: 'File', palette: false, + run: (a) => { if (typeof a?.path === 'string' && a.path) return importer.paths([a.path]); return undefined; }, + }, + { id: 'import.clearRecent', label: 'Clear Recent Imports', group: 'File', palette: false, run: () => { forgetImports(); syncRecent(); } }, + { id: 'import.noRecent', label: 'No Recent Imports', group: 'File', palette: false, enabled: () => false, run: () => undefined }, + ]); + events.on('ui.import.done', (e) => { rememberImport(typeof e.name === 'string' ? e.name : '', typeof e.path === 'string' ? e.path : ''); syncRecent(); }); + syncRecent(); + + mountDropZone(ctx.slots.overlayRoot, ctx.slots.viewport, { + files: (items) => importer.files(items), + paths: (paths) => { void importer.paths(paths); }, + onHome: (paths) => { + void registry.callCommand('file.new', { title: stemOf(paths[0]) }).then(() => importer.paths(paths)).catch((err: unknown) => ctx.toast(errorText(err), 'error')); + }, + }); + + const engineReady = (): Promise<boolean> => new Promise((resolve) => { + if (catalogue.state === 'ready') { resolve(true); return; } + const stop = (ok: boolean): void => { off(); window.clearTimeout(timer); resolve(ok); }; + const off = catalogue.onChange(() => { if (catalogue.state === 'ready') stop(true); }); + const timer = window.setTimeout(() => stop(false), 60000); + }); + + const documentState = async (): Promise<{ hasDocument: boolean; title: string; dirty: boolean }> => { + try { + const out = await registry.callCommand('workspace.state'); + const s = out.result && typeof out.result === 'object' ? out.result as Record<string, unknown> : {}; + return { hasDocument: s.hasDocument === true, title: typeof s.title === 'string' ? s.title : '', dirty: s.dirty === true }; + } catch { + return { hasDocument: false, title: '', dirty: false }; + } + }; + + const openGiven = async (given: readonly string[]): Promise<void> => { + const projects = given.filter((p) => extOf(p) === 'fshot'); + const models = given.filter(isModel); + if (projects.length > 1) ctx.toast(t('FormShot opens one project at a time; {n} other project files were left unopened.', { n: projects.length - 1 })); + if (projects.length) { + const path = projects[0]; + const state = await documentState(); + const sure = !state.hasDocument || !state.dirty || await confirmDialog(t('Discard unsaved changes?'), t('Opening {name} will close the open project and discard its unsaved changes.', { name: baseName(path) })); + if (!sure) return; + try { + await registry.callCommand('workspace.load', { path, title: stemOf(path), saved: true }); + } catch (err) { + ctx.toast(t('Could not open {name}: {reason}', { name: baseName(path), reason: errorText(err) }), 'error'); + return; + } + } + if (!models.length) return; + const state = await documentState(); + if (state.hasDocument) { + if (document.documentElement.classList.contains('fsh-home-open')) events.emit({ type: 'ui.workspace.loaded', title: state.title, path: '' }); + } else { + try { + await registry.callCommand('file.new', { title: stemOf(models[0]) }); + } catch (err) { + ctx.toast(errorText(err), 'error'); + return; + } + } + await importer.paths(models); + }; + + let opening: Promise<void> = Promise.resolve(); + ctx.onReady(() => { + void listenOpens((paths) => { + opening = opening.then(async () => { + if (!await engineReady()) { ctx.toast(t('The engine did not start in time, so the files FormShot was given were not opened.'), 'error'); return; } + await openGiven(paths); + }).catch((err: unknown) => ctx.toast(errorText(err), 'error')); + }); + }); +} diff --git a/frontend/src/ui/import/recent.ts b/frontend/src/ui/import/recent.ts new file mode 100644 index 00000000..3f5754b7 --- /dev/null +++ b/frontend/src/ui/import/recent.ts @@ -0,0 +1,25 @@ +const KEY = 'formshot.import.recent'; +const MAX = 8; + +export interface RecentImport { name: string; path: string; at: number } + +export function recentImports(): RecentImport[] { + try { + const raw = JSON.parse(localStorage.getItem(KEY) ?? '[]') as unknown; + if (!Array.isArray(raw)) return []; + return raw.filter((r): r is RecentImport => !!r && typeof r === 'object' && typeof (r as RecentImport).path === 'string' && typeof (r as RecentImport).name === 'string').slice(0, MAX); + } catch { + return []; + } +} + +function store(list: RecentImport[]): void { + try { localStorage.setItem(KEY, JSON.stringify(list.slice(0, MAX))); } catch { return; } +} + +export function rememberImport(name: string, path: string): void { + if (!path) return; + store([{ name, path, at: Date.now() }, ...recentImports().filter((r) => r.path !== path)]); +} + +export function forgetImports(): void { store([]); } diff --git a/frontend/src/ui/import/sheet.ts b/frontend/src/ui/import/sheet.ts new file mode 100644 index 00000000..540e7073 --- /dev/null +++ b/frontend/src/ui/import/sheet.ts @@ -0,0 +1,374 @@ +import { Dialog } from '../../shell/dialog'; +import { el, q, setAttr, setDisabled, setStyleVar, setText, setValue, setChecked } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { toast } from '../../shell/toast'; +import { runCommand } from '../../shell/registry'; +import { t } from '../../i18n'; +import { + catalogue, COMMANDS, CAD_QUALITIES, errorText, ImportJob, probe, resultCounts, UNITS, + type CadQuality, type ImportOptions, type Outcome, type Probe, type Progress, type Units, type UpAxis, +} from './engine'; +import { bytesText, formatName, isCad } from './formats'; +import { removeUpload, Sending, type BrowserJob } from './upload'; + +export type Source = + | { kind: 'path'; path: string; name: string } + | { kind: 'browser'; job: BrowserJob; name: string }; + +export interface SheetHooks { + finished(name: string, path: string, outcome: Outcome, frame: boolean): void; +} + +const OPTIONS_KEY = 'formshot.import.options'; + +const UNIT_LABELS: Record<Units, string> = { + auto: 'Automatic', mm: 'Millimetres (mm)', cm: 'Centimetres (cm)', m: 'Metres (m)', in: 'Inches (in)', ft: 'Feet (ft)', +}; +const UNIT_WORDS: Record<string, string> = { mm: 'millimetres', cm: 'centimetres', m: 'metres', in: 'inches', ft: 'feet' }; +const QUALITY_LABELS: Record<CadQuality, string> = { draft: 'Draft', medium: 'Medium', high: 'High', ultra: 'Ultra' }; +const STAGES: Record<string, string> = { + uploading: 'Uploading', + reading: 'Reading the file', + parsing: 'Reading the file', + tessellating: 'Tessellating CAD surfaces', + cleaning: 'Cleaning up meshes', + cleanup: 'Cleaning up meshes', + materials: 'Making materials', + placing: 'Placing in the scene', + importing: 'Importing', + done: 'Done', +}; + +interface Kept { up_axis: UpAxis; stand_on_floor: boolean; center: boolean; frame: boolean; merge: boolean; cad_quality: CadQuality } +const DEFAULTS: Kept = { up_axis: 'auto', stand_on_floor: true, center: true, frame: true, merge: false, cad_quality: 'medium' }; + +function kept(): Kept { + try { + const raw = JSON.parse(localStorage.getItem(OPTIONS_KEY) ?? 'null') as Partial<Kept> | null; + return { ...DEFAULTS, ...(raw && typeof raw === 'object' ? raw : {}) }; + } catch { + return { ...DEFAULTS }; + } +} + +function keep(o: Kept): void { + try { localStorage.setItem(OPTIONS_KEY, JSON.stringify(o)); } catch { return; } +} + +const numberText = (n: number | null): string => (n === null ? '' : new Intl.NumberFormat().format(n)); + +function sizeText(p: Probe): string { + if (!p.size) return ''; + const unit = p.unitsDeclared || p.unitsGuess; + const f = (v: number): string => new Intl.NumberFormat(undefined, { maximumSignificantDigits: 4 }).format(v); + return `${p.size.map(f).join(' x ')}${unit ? ` ${unit}` : ''}`; +} + +const isUnit = (v: string): v is Units => (UNITS as readonly string[]).includes(v); + +type Phase = 'preparing' | 'ready' | 'running' | 'finished'; + +export class ImportSheet { + private readonly dialog = new Dialog('Import Model', 'wide'); + private readonly root: HTMLElement; + private readonly units: HTMLSelectElement; + private readonly up: HTMLSelectElement; + private readonly cad: HTMLSelectElement; + private readonly boxes: Record<'stand_on_floor' | 'center' | 'frame' | 'merge', HTMLInputElement>; + private readonly importBtn: HTMLButtonElement; + private readonly allBtn: HTMLButtonElement; + private readonly cancelBtn: HTMLButtonElement; + private index = 0; + private phase: Phase = 'preparing'; + private all = false; + private closed = false; + private unitsTouched = false; + private path = ''; + private uploadId = ''; + private sending: Sending | null = null; + private job: ImportJob | null = null; + private probed: Probe | null = null; + private token = 0; + + constructor(private readonly sources: Source[], private readonly hooks: SheetHooks) { + const d = this.dialog; + d.scrim.querySelector('.fsh-dialog')?.classList.add('fsh-imp-dialog'); + this.root = el(`<div class="fsh-imp"> +<div class="fsh-imp-file"><span class="fsh-imp-file-icon">${icon('file', 18)}</span><span class="fsh-imp-file-text"><span class="fsh-imp-name" data-no-i18n></span><span class="fsh-imp-meta fsh-tabular" data-no-i18n></span></span><span class="fsh-imp-count fsh-tabular"></span></div> +<div class="fsh-imp-cols"> +<section class="fsh-imp-summary" aria-label="${t('In this file')}"> +<h3 class="fsh-imp-head">${t('In this file')}</h3> +<dl class="fsh-imp-facts"> +<div><dt>${t('Format')}</dt><dd data-f="format" data-no-i18n></dd></div> +<div><dt>${t('Triangles')}</dt><dd data-f="triangles" class="fsh-tabular" data-no-i18n></dd></div> +<div><dt>${t('Parts')}</dt><dd data-f="parts" class="fsh-tabular" data-no-i18n></dd></div> +<div><dt>${t('Materials')}</dt><dd data-f="materials" class="fsh-tabular" data-no-i18n></dd></div> +<div><dt>${t('Size')}</dt><dd data-f="size" class="fsh-tabular" data-no-i18n></dd></div> +<div><dt>${t('Up axis in file')}</dt><dd data-f="up" data-no-i18n></dd></div> +</dl> +<div class="fsh-imp-notes" role="status"><p class="fsh-imp-notes-text"></p><ul class="fsh-imp-warnings" data-no-i18n></ul></div> +</section> +<section class="fsh-imp-options" aria-label="${t('Options')}"> +<h3 class="fsh-imp-head">${t('Options')}</h3> +<label class="fsh-imp-row"><span>${t('Units')}</span><select class="fsh-input" data-o="units"></select></label> +<p class="fsh-imp-unit-note"><span class="fsh-imp-unit-icon">${icon('warning', 14)}</span><span class="fsh-imp-unit-text"></span></p> +<label class="fsh-imp-row"><span>${t('Up axis')}</span><select class="fsh-input" data-o="up"><option value="auto">${t('Automatic')}</option><option value="y">${t('Y is up')}</option><option value="z">${t('Z is up')}</option></select></label> +<label class="fsh-imp-check"><input type="checkbox" data-o="stand_on_floor"><span>${t('Stand on the floor')}</span></label> +<label class="fsh-imp-check"><input type="checkbox" data-o="center"><span>${t('Centre on the origin')}</span></label> +<label class="fsh-imp-check"><input type="checkbox" data-o="frame"><span>${t('Frame the view after import')}</span></label> +<label class="fsh-imp-check"><input type="checkbox" data-o="merge"><span>${t('Merge into one group')}</span></label> +<label class="fsh-imp-row fsh-imp-cad"><span>${t('CAD quality')}</span><select class="fsh-input" data-o="cad"></select></label> +</section> +</div> +<div class="fsh-imp-progress" aria-live="polite"><span class="fsh-imp-stage"></span><span class="fsh-imp-bar"><span class="fsh-imp-fill"></span></span><span class="fsh-imp-pct fsh-tabular" data-no-i18n></span></div> +<p class="fsh-imp-reason"></p> +</div>`); + d.body.appendChild(this.root); + this.units = q<HTMLSelectElement>(this.root, '[data-o="units"]'); + this.up = q<HTMLSelectElement>(this.root, '[data-o="up"]'); + this.cad = q<HTMLSelectElement>(this.root, '[data-o="cad"]'); + for (const u of UNITS) this.units.appendChild(el(`<option value="${u}">${t(UNIT_LABELS[u])}</option>`)); + for (const c of CAD_QUALITIES) this.cad.appendChild(el(`<option value="${c}">${t(QUALITY_LABELS[c])}</option>`)); + this.boxes = { + stand_on_floor: q<HTMLInputElement>(this.root, '[data-o="stand_on_floor"]'), + center: q<HTMLInputElement>(this.root, '[data-o="center"]'), + frame: q<HTMLInputElement>(this.root, '[data-o="frame"]'), + merge: q<HTMLInputElement>(this.root, '[data-o="merge"]'), + }; + const k = kept(); + setValue(this.up, k.up_axis); + setValue(this.cad, k.cad_quality); + for (const key of Object.keys(this.boxes) as Array<keyof typeof this.boxes>) setChecked(this.boxes[key], k[key]); + this.units.addEventListener('change', () => { this.unitsTouched = true; this.unitNote(); }); + this.root.addEventListener('keydown', (e) => { + if (e.key !== 'Enter' || e.target instanceof HTMLSelectElement || this.phase !== 'ready') return; + e.preventDefault(); + e.stopPropagation(); + this.start(); + }); + this.cancelBtn = d.action('Cancel', () => this.cancel()); + this.allBtn = d.action('Import All', () => { this.all = true; this.start(); }); + this.importBtn = d.action('Import', () => this.start(), 'primary'); + this.allBtn.classList.add('fsh-imp-all'); + setAttr(this.allBtn, 'data-hidden', sources.length > 1 ? null : 'true'); + d.onClose = () => this.closing(); + catalogue.onChange(() => this.syncButtons()); + } + + open(): void { + this.dialog.open(); + this.show(0); + this.units.focus(); + runCommand('cad.sheet', { select: this.cad, row: q(this.root, '.fsh-imp-cad') }); + } + + private options(): ImportOptions { + const units = isUnit(this.units.value) ? this.units.value : 'auto'; + const up = this.up.value === 'y' || this.up.value === 'z' ? this.up.value : 'auto'; + const custom = this.cad.selectedOptions[0]?.dataset.quality; + const cad = (CAD_QUALITIES as readonly string[]).includes(this.cad.value) ? this.cad.value as CadQuality : 'medium'; + const o: ImportOptions = { + units, up_axis: up, + stand_on_floor: this.boxes.stand_on_floor.checked, center: this.boxes.center.checked, + frame: this.boxes.frame.checked, merge: this.boxes.merge.checked, + }; + if (isCad(this.sources[this.index].name)) o.cad_quality = custom ? JSON.parse(custom) : cad; + keep({ up_axis: up, stand_on_floor: o.stand_on_floor, center: o.center, frame: o.frame, merge: o.merge, cad_quality: cad }); + return o; + } + + private field(name: string, value: string): void { + setText(this.root.querySelector(`[data-f="${name}"]`), value); + } + + private show(i: number): void { + this.index = i; + const src = this.sources[i]; + const token = ++this.token; + this.path = src.kind === 'path' ? src.path : ''; + this.uploadId = ''; + this.probed = null; + this.job = null; + setText(q(this.root, '.fsh-imp-name'), src.name); + const size = src.kind === 'browser' ? bytesText(src.job.main.size + src.job.siblings.reduce((s, x) => s + x.file.size, 0)) : ''; + const beside = src.kind === 'browser' ? src.job.siblings.length : 0; + const extra = beside === 1 ? t('One file beside it') : beside > 1 ? t('{n} files beside it', { n: beside }) : ''; + setText(q(this.root, '.fsh-imp-meta'), [formatName(src.name), size, extra].filter(Boolean).join(' · ')); + setText(q(this.root, '.fsh-imp-count'), this.sources.length > 1 ? t('{i} of {n}', { i: i + 1, n: this.sources.length }) : ''); + q(this.root, '.fsh-imp-cad').classList.toggle('is-off', !isCad(src.name)); + for (const f of ['format', 'triangles', 'parts', 'materials', 'size', 'up']) this.field(f, ''); + this.field('format', formatName(src.name)); + this.notes(src.kind === 'browser' ? '' : t('Reading the file...'), []); + if (!this.unitsTouched && this.units.value !== 'auto') this.units.value = 'auto'; + this.unitNote(); + this.progress(null); + this.setPhase('preparing'); + void this.prepare(src, token); + } + + private async prepare(src: Source, token: number): Promise<void> { + if (src.kind === 'browser') { + this.progress({ stage: 'uploading', fraction: 0 }); + const sending = new Sending(src.job, (f) => { if (token === this.token) this.progress({ stage: 'uploading', fraction: f }); }); + this.sending = sending; + try { + const up = await sending.done; + if (token !== this.token || this.closed) { removeUpload(up.id); return; } + this.path = up.path; + this.uploadId = up.id; + } catch (err) { + if (token !== this.token) return; + this.sending = null; + this.progress(null); + const reason = t('Could not send the file: {reason}', { reason: errorText(err) }); + this.notes(reason, []); + this.setPhase('finished'); + if (this.index + 1 < this.sources.length) { toast(`${src.name}: ${reason}`, 'error'); this.next(); } + return; + } + this.sending = null; + this.progress(null); + this.notes(t('Reading the file...'), []); + } + if (catalogue.state === 'unknown') await catalogue.load(); + if (token !== this.token) return; + if (!catalogue.has(COMMANDS.probe)) { + this.notes(catalogue.state === 'ready' ? t('This engine cannot look inside a file before importing it, so the summary stays empty.') : catalogue.why(COMMANDS.probe), []); + } else { + try { + const p = await probe(this.path); + if (token !== this.token) return; + this.fill(p); + } catch (err) { + if (token !== this.token) return; + this.notes(t('Could not read the file: {reason}', { reason: errorText(err) }), []); + } + } + this.setPhase('ready'); + if (this.all) this.start(); + } + + private fill(p: Probe): void { + this.probed = p; + if (p.format) this.field('format', formatName(`file.${p.format}`) || p.format.toUpperCase()); + this.field('triangles', numberText(p.triangles)); + this.field('parts', numberText(p.meshes ?? p.nodes)); + this.field('materials', numberText(p.materials)); + this.field('size', sizeText(p)); + this.field('up', p.upAxis ? p.upAxis.toUpperCase() : ''); + this.notes(p.warnings.length ? '' : t('No warnings.'), p.warnings); + const unit = p.unitsDeclared || p.unitsGuess; + if (!this.unitsTouched && isUnit(unit) && this.units.value !== unit) this.units.value = unit; + this.unitNote(); + } + + private notes(text: string, warnings: readonly string[]): void { + setText(q(this.root, '.fsh-imp-notes-text'), text); + const list = q(this.root, '.fsh-imp-warnings'); + const key = warnings.join('\n'); + if (list.dataset.key === key) return; + list.dataset.key = key; + list.replaceChildren(...warnings.map((w) => { const li = document.createElement('li'); li.textContent = w; return li; })); + } + + private unitNote(): void { + const p = this.probed; + const note = q(this.root, '.fsh-imp-unit-note'); + let text = '', warn = false; + if (p && p.unitGuessed && p.unitsGuess && this.units.value === p.unitsGuess) { + text = t('This file does not say its units. FormShot guessed {unit} from its size; check it before importing.', { unit: t(UNIT_WORDS[p.unitsGuess] ?? p.unitsGuess) }); + warn = true; + } else if (p && p.unitsDeclared) { + text = t('The file says it is in {unit}.', { unit: t(UNIT_WORDS[p.unitsDeclared] ?? p.unitsDeclared) }); + } else if (this.units.value === 'auto') { + text = t('The engine decides from the file.'); + } + note.classList.toggle('is-warn', warn); + setText(q(note, '.fsh-imp-unit-text'), text); + } + + private progress(p: Progress | null): void { + const row = q(this.root, '.fsh-imp-progress'); + row.classList.toggle('is-on', p !== null); + if (!p) return; + const known = STAGES[p.stage]; + setText(q(row, '.fsh-imp-stage'), known ? t(known) : p.stage ? p.stage.charAt(0).toUpperCase() + p.stage.slice(1) : t('Importing')); + row.classList.toggle('is-indeterminate', p.fraction === null); + setStyleVar(row, '--fsh-imp-fraction', String(p.fraction ?? 0)); + setText(q(row, '.fsh-imp-pct'), p.fraction === null ? '' : `${Math.round(p.fraction * 100)}%`); + } + + private setPhase(phase: Phase): void { + this.phase = phase; + for (const c of [this.units, this.up, this.cad, ...Object.values(this.boxes)]) setDisabled(c, phase === 'running'); + this.syncButtons(); + if (phase === 'finished' && !this.closed) this.cancelBtn.focus(); + } + + private syncButtons(): void { + const reason = catalogue.canImport() ? '' : catalogue.importReason() || catalogue.why(COMMANDS.start); + const ready = this.phase === 'ready' && !reason; + setDisabled(this.importBtn, !ready); + setDisabled(this.allBtn, !ready); + const running = this.phase === 'running'; + setDisabled(this.cancelBtn, running && !(this.job?.cancellable ?? false)); + setAttr(this.cancelBtn, 'title', running && !(this.job?.cancellable ?? false) ? t('This engine cannot stop an import once it has started') : null); + let text = this.phase === 'finished' ? '' : reason; + if (!text && running && !this.job?.cancellable) text = t('This engine imports in one step, so there is no progress to show or stop.'); + setText(q(this.root, '.fsh-imp-reason'), text); + } + + private start(): void { + if (this.phase !== 'ready' || !catalogue.canImport()) return; + const src = this.sources[this.index]; + const options = this.options(); + if (this.all && !this.unitsTouched) options.units = 'auto'; + const path = this.path; + const uploadId = this.uploadId; + const job = new ImportJob(path, options, (p) => { if (this.job === job) this.progress(p); }); + this.job = job; + this.setPhase('running'); + this.progress({ stage: 'reading', fraction: job.cancellable ? 0 : null }); + void job.run().then((outcome) => { + if (outcome.state !== 'done' && uploadId) removeUpload(uploadId); + this.hooks.finished(src.name, path, outcome, options.frame); + if (this.job !== job) return; + this.job = null; + this.uploadId = ''; + if (outcome.state === 'failed') { + this.progress(null); + this.notes(t('Could not import the file: {reason}', { reason: outcome.error }), []); + this.setPhase('finished'); + if (this.index + 1 < this.sources.length) this.next(); + return; + } + this.next(); + }); + } + + private next(): void { + if (this.closed) return; + if (this.index + 1 < this.sources.length) { this.show(this.index + 1); return; } + this.closed = true; + this.dialog.close(); + } + + private cancel(): void { + if (this.phase === 'running' && this.job) { this.job.cancel(); return; } + this.dialog.close(); + } + + private closing(): void { + const wasClosed = this.closed; + this.closed = true; + this.token++; + this.sending?.abort(); + this.sending = null; + if (this.uploadId && this.phase !== 'running') removeUpload(this.uploadId); + const after = this.sources.length - this.index - 1; + if (wasClosed || after <= 0) return; + const left = after + (this.phase === 'finished' ? 0 : 1); + if (this.phase === 'running') toast(t('The import goes on; the files after it were not imported.')); + else if (left > 1) toast(t('{n} files were not imported.', { n: left })); + } +} diff --git a/frontend/src/ui/import/upload.ts b/frontend/src/ui/import/upload.ts new file mode 100644 index 00000000..12d9b9ec --- /dev/null +++ b/frontend/src/ui/import/upload.ts @@ -0,0 +1,105 @@ +import { api } from '../../shell/api'; +import { keyMessage, WINDOW_KEY_HEADER, windowKeyReady } from '../../shell/window-key'; +import { t } from '../../i18n'; +import { extOf, isModel, isSibling } from './formats'; + +export interface Uploaded { id: string; path: string; name: string; files: string[]; bytes: number } + +export interface LocalFile { file: File; rel: string } + +export interface BrowserJob { main: File; siblings: Array<{ file: File; name: string }> } + +const ROUTE = '/api/imports'; +const REFERS: readonly string[] = ['gltf', 'obj']; + +const dirOf = (rel: string): string => { const i = rel.lastIndexOf('/'); return i > 0 ? rel.slice(0, i) : ''; }; + +export function groupFiles(items: readonly LocalFile[]): BrowserJob[] { + const models = items.filter((x) => isModel(x.file.name)); + const extras = items.filter((x) => !isModel(x.file.name) && isSibling(x.file.name)); + return models.map((m) => { + if (!REFERS.includes(extOf(m.file.name))) return { main: m.file, siblings: [] }; + const dir = dirOf(m.rel); + const siblings = extras + .filter((x) => !dir || x.rel.startsWith(`${dir}/`)) + .map((x) => ({ file: x.file, name: dir ? x.rel.slice(dir.length + 1) : x.rel })); + return { main: m.file, siblings }; + }); +} + +async function entryFiles(entry: FileSystemEntry, out: LocalFile[], depth: number): Promise<void> { + if (entry.isFile) { + const file = await new Promise<File | null>((resolve) => (entry as FileSystemFileEntry).file(resolve, () => resolve(null))); + if (file) out.push({ file, rel: entry.fullPath.replace(/^\/+/, '') }); + return; + } + if (!entry.isDirectory || depth <= 0) return; + const reader = (entry as FileSystemDirectoryEntry).createReader(); + for (;;) { + const batch = await new Promise<FileSystemEntry[]>((resolve) => reader.readEntries(resolve, () => resolve([]))); + if (!batch.length) break; + for (const child of batch) if (!child.name.startsWith('.')) await entryFiles(child, out, depth - 1); + } +} + +export async function droppedFiles(data: DataTransfer): Promise<LocalFile[]> { + const entries = Array.from(data.items ?? []) + .map((item) => (item.kind === 'file' && typeof item.webkitGetAsEntry === 'function' ? item.webkitGetAsEntry() : null)) + .filter((e): e is FileSystemEntry => e !== null); + if (!entries.length) return Array.from(data.files ?? []).map((file) => ({ file, rel: file.name })); + const out: LocalFile[] = []; + for (const e of entries) await entryFiles(e, out, 6); + return out; +} + +function windowKey(): string { + try { return (JSON.parse(keyMessage()) as { key?: unknown }).key as string || ''; } catch { return ''; } +} + +export class Sending { + readonly done: Promise<Uploaded>; + private readonly xhr = new XMLHttpRequest(); + private aborted = false; + + constructor(job: BrowserJob, onProgress: (fraction: number) => void) { + this.done = this.send(job, onProgress); + } + + abort(): void { + this.aborted = true; + this.xhr.abort(); + } + + private async send(job: BrowserJob, onProgress: (fraction: number) => void): Promise<Uploaded> { + await windowKeyReady(); + if (this.aborted) throw new Error(t('The upload was cancelled')); + const form = new FormData(); + form.append('main', job.main, job.main.name); + for (const s of job.siblings) form.append('files', s.file, s.name); + const xhr = this.xhr; + return new Promise<Uploaded>((resolve, reject) => { + xhr.open('POST', api.url(ROUTE)); + const key = windowKey(); + if (key) xhr.setRequestHeader(WINDOW_KEY_HEADER, key); + xhr.responseType = 'text'; + xhr.upload.onprogress = (e) => { if (e.lengthComputable && e.total > 0) onProgress(e.loaded / e.total); }; + xhr.onabort = () => reject(new Error(t('The upload was cancelled'))); + xhr.onerror = () => reject(new Error(t('The FormShot service is not reachable'))); + xhr.onload = () => { + let body: Record<string, unknown> = {}; + try { body = JSON.parse(xhr.responseText) as Record<string, unknown>; } catch { body = {}; } + if (xhr.status >= 200 && xhr.status < 300 && typeof body.path === 'string' && typeof body.id === 'string') { + resolve(body as unknown as Uploaded); + return; + } + const detail = typeof body.detail === 'string' ? body.detail : t('The upload failed ({status})', { status: xhr.status }); + reject(new Error(detail)); + }; + xhr.send(form); + }); + } +} + +export function removeUpload(id: string): void { + void api.del(`${ROUTE}/${encodeURIComponent(id)}`).catch(() => undefined); +} diff --git a/frontend/src/ui/inspector.ts b/frontend/src/ui/inspector.ts index 3525c560..5fe996a4 100644 --- a/frontend/src/ui/inspector.ts +++ b/frontend/src/ui/inspector.ts @@ -8,6 +8,7 @@ import type { Workspace } from './context'; import { mountCameraPage } from './pages/camera'; import { mountEnvironmentPage } from './pages/environment'; import { mountImagePage } from './pages/image'; +import { mountMaterialPage } from './pages/material'; import { emptyPage, type PageMount } from './pages/page'; import { mountScenePage } from './pages/scene'; @@ -17,7 +18,7 @@ interface OwnPage { id: string; title: string; command: string; icon: InspectorP const PAGES: readonly OwnPage[] = [ { id: 'scene', title: 'Scene', command: 'Scene Page', icon: 'scene', order: 10, mount: mountScenePage }, - { id: 'material', title: 'Material', command: 'Material Page', icon: 'material', order: 20, mount: emptyPage('Material', 'Material editing arrives in 0.5.0.') }, + { id: 'material', title: 'Material', command: 'Material Page', icon: 'material', order: 20, mount: mountMaterialPage }, { id: 'environment', title: 'Environment', command: 'Environment Page', icon: 'environment', order: 30, mount: mountEnvironmentPage }, { id: 'lighting', title: 'Lighting', command: 'Lighting Page', icon: 'light', order: 40, mount: emptyPage('Lighting', 'Lights and studio presets arrive in 0.7.0.') }, { id: 'camera', title: 'Camera', command: 'Camera Page', icon: 'camera', order: 50, mount: mountCameraPage }, diff --git a/frontend/src/ui/labels/image.ts b/frontend/src/ui/labels/image.ts new file mode 100644 index 00000000..55d0e377 --- /dev/null +++ b/frontend/src/ui/labels/image.ts @@ -0,0 +1,83 @@ +import { api, ApiError } from '../../shell/api'; +import { inTauri } from '../../shell/dom'; +import { t } from '../../i18n'; + +export const IMAGE_EXTS = ['png', 'jpg', 'jpeg', 'hdr', 'exr'] as const; +const ROUTE = '/api/textures'; + +export interface PickedImage { path: string; size: [number, number] | null } + +export type ImageSource = 'desktop' | 'upload' | 'none'; + +let routeProbe: Promise<boolean> | null = null; + +function uploadRoute(): Promise<boolean> { + if (!routeProbe) { + routeProbe = fetch(api.url(ROUTE), { method: 'GET' }) + .then((r) => r.status !== 404) + .catch(() => false); + } + return routeProbe; +} + +export async function imageSource(): Promise<ImageSource> { + if (inTauri()) return 'desktop'; + return (await uploadRoute()) ? 'upload' : 'none'; +} + +export function noSourceReason(): string { + return t('Choosing an image in the browser needs the service texture upload (POST /api/textures), which this service does not offer yet.'); +} + +async function pickDesktop(): Promise<PickedImage | null> { + const { invoke } = await import('@tauri-apps/api/core'); + const picked = await invoke<string | string[] | null>('plugin:dialog|open', { + options: { multiple: false, directory: false, title: t('Choose Label Image'), filters: [{ name: t('Images'), extensions: [...IMAGE_EXTS] }] }, + }); + const path = Array.isArray(picked) ? picked[0] : picked; + return path ? { path, size: null } : null; +} + +function chooseFile(): Promise<File | null> { + return new Promise((resolve) => { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = IMAGE_EXTS.map((e) => `.${e}`).join(','); + input.addEventListener('change', () => resolve(input.files?.[0] ?? null), { once: true }); + input.addEventListener('cancel', () => resolve(null), { once: true }); + input.click(); + }); +} + +async function pixelSize(file: File): Promise<[number, number] | null> { + try { + const bmp = await createImageBitmap(file); + const size: [number, number] = [bmp.width, bmp.height]; + bmp.close(); + return size[0] > 0 && size[1] > 0 ? size : null; + } catch { + return null; + } +} + +async function pickUpload(): Promise<PickedImage | null> { + const file = await chooseFile(); + if (!file) return null; + const size = await pixelSize(file); + const form = new FormData(); + form.append('file', file, file.name); + const res = await fetch(api.url(ROUTE), { method: 'POST', body: form }); + const body = await res.json().catch(() => ({})) as { path?: unknown; detail?: unknown }; + if (!res.ok || typeof body.path !== 'string') { + const why = typeof body.detail === 'string' ? body.detail : t('The image could not be uploaded'); + throw new ApiError(why, res.status); + } + return { path: body.path, size }; +} + +export async function pickImage(): Promise<PickedImage | null> { + const source = await imageSource(); + if (source === 'desktop') return pickDesktop(); + if (source === 'upload') return pickUpload(); + throw new Error(noSourceReason()); +} diff --git a/frontend/src/ui/labels/index.ts b/frontend/src/ui/labels/index.ts new file mode 100644 index 00000000..f9c8c619 --- /dev/null +++ b/frontend/src/ui/labels/index.ts @@ -0,0 +1,454 @@ +import './labels.css'; +import { el, escapeHtml, patchList, q, setAttr, setChecked, setClass, setDisabled, setHidden, setHtml, setPressed, setStyleVar, setText, setTitle, setValue } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { coalesce, type Workspace } from '../context'; +import { NumberField } from '../number-field'; +import { imageSource, noSourceReason, pickImage, type ImageSource } from './image'; +import { baseName, fileName, parseLabels, type LabelView } from './model'; +import { PlaceMode } from './place'; + +export interface LabelsSection { + show(material: string | null): void; +} + +const LIST = 'material.labels'; +const ADD = 'material.label_add'; +const SET = 'material.label_set'; +const REMOVE = 'material.label_remove'; +const MOVE = 'material.label_move'; +const BARRIER = 'history.barrier'; + +const SVG = 'viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"'; +const GRIP = `<svg ${SVG} width="14" height="14"><circle cx="9" cy="6" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="18" r="1"/></svg>`; +const TARGET = `<svg ${SVG} width="16" height="16"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/></svg>`; + +type Patch = Record<string, unknown>; + +const T = (english: string): string => escapeHtml(t(english)); + +interface Fields { + root: HTMLElement; + name: HTMLInputElement; + file: HTMLElement; + choose: HTMLButtonElement; + width: NumberField; + height: NumberField; + link: HTMLButtonElement; + rotation: NumberField; + depth: NumberField; + opacity: NumberField; + twoSided: HTMLInputElement; + roughOn: HTMLInputElement; + rough: NumberField; + metalOn: HTMLInputElement; + metal: NumberField; + place: HTMLButtonElement; +} + +export function mountLabels(host: HTMLElement, ws: Workspace): LabelsSection { + const root = el(`<section class="fsh-ws-section fsh-lbl" aria-label="Labels"> +<header class="fsh-lbl-head"> + <h3 class="fsh-ws-section-title">${T('Labels')}</h3> + <button class="fsh-btn is-sm fsh-lbl-add" type="button">${icon('plus', 14)}<span>${T('Add from Image')}</span></button> +</header> +<div class="fsh-lbl-listbox"> + <div class="fsh-lbl-list" role="listbox" aria-label="${T('Labels')}"></div> + <p class="fsh-lbl-empty">${T('No labels yet. Add an image, then place it on the part.')}</p> + <span class="fsh-lbl-drop" aria-hidden="true"></span> +</div> +<p class="fsh-lbl-note" role="status"></p> +</section>`); + host.appendChild(root); + const list = q(root, '.fsh-lbl-list'); + const empty = q(root, '.fsh-lbl-empty'); + const drop = q(root, '.fsh-lbl-drop'); + const note = q(root, '.fsh-lbl-note'); + const addBtn = q<HTMLButtonElement>(root, '.fsh-lbl-add'); + const placeMode = new PlaceMode(ws); + + let material: string | null = null; + let labels: LabelView[] = []; + let selected: number | null = null; + let source: ImageSource = 'none'; + let linked = true; + let ratio: number | null = null; + let fetchSeq = 0; + let noteText = ''; + let noteError = false; + let aspectFix: number | null = null; + let dragging: { id: number; from: number; to: number } | null = null; + + void imageSource().then((s) => { source = s; paint(); }); + + const say = (text: string, error = false): void => { noteText = text; noteError = error; paintNote(); }; + + const current = (): LabelView | null => labels.find((l) => l.id === selected) ?? null; + + const barrier = (): void => { if (ws.canRun(BARRIER)) void ws.client.dispatch(BARRIER, {}).catch(() => undefined); }; + + const send = async (patch: Patch, id = selected): Promise<void> => { + if (material === null || id === null) return; + const l = labels.find((x) => x.id === id); + if (l) Object.assign(l, localPatch(patch)); + await ws.run(SET, { key: material, id, label: patch }); + }; + + const live = coalesce<Patch>((p) => send(p)); + const commit = (p: Patch): void => { void send(p).then(barrier); }; + + const fields = buildFields(); + root.appendChild(fields.root); + + function localPatch(p: Patch): Partial<LabelView> { + const out: Partial<LabelView> = {}; + if (Array.isArray(p.size)) out.size = p.size as [number, number]; + if (typeof p.rotation === 'number') out.rotation = p.rotation; + if (typeof p.depth === 'number') out.depth = p.depth; + if (typeof p.opacity === 'number') out.opacity = p.opacity; + if (typeof p.name === 'string') out.name = p.name; + if (typeof p.visible === 'boolean') out.visible = p.visible; + if (typeof p.two_sided === 'boolean') out.twoSided = p.two_sided; + if ('roughness' in p) out.roughness = typeof p.roughness === 'number' ? p.roughness : null; + if ('metalness' in p) out.metalness = typeof p.metalness === 'number' ? p.metalness : null; + return out; + } + + function sizeFrom(width: number | null, height: number | null): [number, number] | null { + const l = current(); + if (!l) return null; + let w = width ?? l.size[0], h = height ?? l.size[1]; + const r = linked ? (ratio ?? l.size[1] / l.size[0]) : null; + if (r && width !== null) h = w * r; + else if (r && height !== null) w = h / r; + return [Math.max(1e-4, w), Math.max(1e-4, h)]; + } + + function buildFields(): Fields { + const box = el(`<div class="fsh-lbl-fields"> +<label class="fsh-ws-row"><span class="fsh-ws-row-label">${T('Name')}</span><input class="fsh-input fsh-lbl-name-input" type="text" spellcheck="false" data-no-i18n></label> +<div class="fsh-ws-row"><span class="fsh-ws-row-label">${T('Image')}</span><span class="fsh-lbl-image"><span class="fsh-lbl-file" data-no-i18n></span><button class="fsh-btn is-sm fsh-lbl-choose" type="button">${T('Choose')}</button></span></div> +<div class="fsh-lbl-size"><div class="fsh-lbl-size-fields"></div><button class="fsh-icon-btn fsh-lbl-link" type="button" aria-pressed="true" title="${T('Keep the image proportions')}" aria-label="${T('Keep the image proportions')}">${icon('link', 14)}</button></div> +<div class="fsh-lbl-nums"></div> +<label class="fsh-lbl-check"><input type="checkbox" class="fsh-lbl-two"><span>${T('Print on both sides')}</span></label> +<div class="fsh-lbl-override fsh-lbl-rough"><label class="fsh-lbl-check"><input type="checkbox"><span>${T('Own roughness')}</span></label></div> +<div class="fsh-lbl-override fsh-lbl-metal"><label class="fsh-lbl-check"><input type="checkbox"><span>${T('Own metalness')}</span></label></div> +<button class="fsh-btn fsh-lbl-place" type="button" aria-pressed="false">${TARGET}<span>${T('Place on Surface')}</span></button> +</div>`); + const mm = 1000; + const num = (label: string, opts: { min: number; max: number; step: number; unit?: string }, toDoc: (v: number) => Patch): NumberField => + new NumberField({ label, ...opts, onInput: (v) => live(toDoc(v)), onCommit: (v) => commit(toDoc(v)) }); + const width = num('Width', { min: 0.1, max: 10000, step: 0.5, unit: 'mm' }, (v) => ({ size: sizeFrom(v / mm, null) })); + const height = num('Height', { min: 0.1, max: 10000, step: 0.5, unit: 'mm' }, (v) => ({ size: sizeFrom(null, v / mm) })); + const rotation = num('Rotation', { min: -180, max: 180, step: 1, unit: 'deg' }, (v) => ({ rotation: (v * Math.PI) / 180 })); + const depth = num('Depth', { min: 0.01, max: 1000, step: 0.1, unit: 'mm' }, (v) => ({ depth: v / mm })); + const opacity = num('Opacity', { min: 0, max: 1, step: 0.01 }, (v) => ({ opacity: v })); + const rough = num('Roughness', { min: 0, max: 1, step: 0.01 }, (v) => ({ roughness: v })); + const metal = num('Metalness', { min: 0, max: 1, step: 0.01 }, (v) => ({ metalness: v })); + q(box, '.fsh-lbl-size-fields').append(width.root, height.root); + q(box, '.fsh-lbl-nums').append(rotation.root, depth.root, opacity.root); + q(box, '.fsh-lbl-rough').appendChild(rough.root); + q(box, '.fsh-lbl-metal').appendChild(metal.root); + const f: Fields = { + root: box, + name: q<HTMLInputElement>(box, '.fsh-lbl-name-input'), + file: q(box, '.fsh-lbl-file'), + choose: q<HTMLButtonElement>(box, '.fsh-lbl-choose'), + width, height, rotation, depth, opacity, rough, metal, + link: q<HTMLButtonElement>(box, '.fsh-lbl-link'), + twoSided: q<HTMLInputElement>(box, '.fsh-lbl-two'), + roughOn: q<HTMLInputElement>(box, '.fsh-lbl-rough input'), + metalOn: q<HTMLInputElement>(box, '.fsh-lbl-metal input'), + place: q<HTMLButtonElement>(box, '.fsh-lbl-place'), + }; + f.name.addEventListener('change', () => commit({ name: f.name.value.trim() || t('Label') })); + f.name.addEventListener('keydown', (e) => { if (e.key === 'Enter') f.name.blur(); e.stopPropagation(); }); + f.choose.addEventListener('click', () => { void chooseImage(); }); + f.link.addEventListener('click', () => { + linked = !linked; + const l = current(); + if (linked && l && !l.imageSize) ratio = l.size[1] / l.size[0]; + paint(); + }); + f.twoSided.addEventListener('change', () => commit({ two_sided: f.twoSided.checked })); + f.roughOn.addEventListener('change', () => commit({ roughness: f.roughOn.checked ? (current()?.roughness ?? 0.5) : null })); + f.metalOn.addEventListener('change', () => commit({ metalness: f.metalOn.checked ? (current()?.metalness ?? 1) : null })); + f.place.addEventListener('click', () => { void place(); }); + return f; + } + + async function chooseImage(): Promise<void> { + const l = current(); + if (!material || !l) return; + try { + const picked = await pickImage(); + if (!picked) return; + const r = picked.size ? picked.size[1] / picked.size[0] : null; + const label: Patch = {}; + if (linked && r) label.size = [l.size[0], l.size[0] * r]; + if (!r) aspectFix = l.id; + await ws.run(SET, { key: material, id: l.id, path: picked.path, label }); + barrier(); + } catch (err) { + say(err instanceof Error ? err.message : String(err), true); + } + } + + async function addLabel(): Promise<void> { + if (!material) return; + const key = material; + try { + const picked = await pickImage(); + if (!picked) return; + const r = picked.size ? picked.size[1] / picked.size[0] : 1; + const reply = await ws.run(ADD, { key, path: picked.path, label: { name: baseName(picked.path) || t('Label'), size: [0.1, 0.1 * r] } }); + const created = (reply as { created?: unknown[] } | undefined)?.created; + const id = Array.isArray(created) ? Number(created[0]) : NaN; + if (Number.isFinite(id) && id > 0) { + selected = id; + if (!picked.size) aspectFix = id; + say(t('Label added. Use Place on Surface to put it on the part.')); + } + barrier(); + await refresh(); + } catch (err) { + say(err instanceof Error ? err.message : String(err), true); + } + } + + async function place(): Promise<void> { + if (placeMode.armed) { placeMode.cancel(); return; } + const l = current(); + if (!material || !l) return; + const key = material, id = l.id; + say(t('Click the part where the label goes. Escape cancels.')); + setPressed(fields.place, true); + const result = await placeMode.start(key); + setPressed(fields.place, false); + if (!result) { say(''); return; } + if (!result.placement) { say(result.message, true); return; } + if (material !== key) return; + await ws.run(SET, { key, id, label: { ...result.placement } }); + barrier(); + say(t('Label placed.')); + } + + addBtn.addEventListener('click', () => { void addLabel(); }); + + function rowFor(l: LabelView): HTMLElement { + const row = el(`<div class="fsh-lbl-row" role="option" aria-selected="false" tabindex="-1"> +<span class="fsh-lbl-grip" title="${T('Drag to reorder')}">${GRIP}</span> +<button class="fsh-icon-btn fsh-lbl-eye" type="button" aria-pressed="true"></button> +<span class="fsh-lbl-name" data-no-i18n></span> +<span class="fsh-lbl-row-file" data-no-i18n></span> +<button class="fsh-icon-btn fsh-lbl-del" type="button" title="${T('Remove Label')}" aria-label="${T('Remove Label')}">${icon('trash', 14)}</button> +</div>`); + const id = l.id; + row.addEventListener('click', (e) => { + if ((e.target as Element).closest('button, .fsh-lbl-grip')) return; + select(id); + }); + q(row, '.fsh-lbl-eye').addEventListener('click', () => { + const cur = labels.find((x) => x.id === id); + if (cur) void send({ visible: !cur.visible }, id).then(barrier); + }); + q(row, '.fsh-lbl-del').addEventListener('click', () => { + if (!material) return; + void ws.run(REMOVE, { key: material, id }).then(barrier); + }); + grip(row, id); + return row; + } + + function grip(row: HTMLElement, id: number): void { + const handle = q(row, '.fsh-lbl-grip'); + let pointer = -1, startY = 0, rowH = 1; + handle.addEventListener('pointerdown', (e) => { + if (e.button !== 0 || !material || !ws.canRun(MOVE)) return; + const from = labels.findIndex((l) => l.id === id); + if (from < 0) return; + e.preventDefault(); + pointer = e.pointerId; + startY = e.clientY; + rowH = row.getBoundingClientRect().height || 1; + handle.setPointerCapture(e.pointerId); + dragging = { id, from, to: from }; + setClass(row, 'is-dragging', true); + }); + handle.addEventListener('pointermove', (e) => { + if (e.pointerId !== pointer || !dragging) return; + const dy = e.clientY - startY; + dragging.to = Math.max(0, Math.min(labels.length - 1, dragging.from + Math.round(dy / rowH))); + setStyleVar(row, '--fsh-lbl-dy', `${dy}px`); + paintDrop(); + }); + const end = (e: PointerEvent): void => { + if (e.pointerId !== pointer) return; + pointer = -1; + const d = dragging; + dragging = null; + setClass(row, 'is-dragging', false); + setStyleVar(row, '--fsh-lbl-dy', '0px'); + paintDrop(); + if (d && d.to !== d.from && material && e.type === 'pointerup') { + const moved = labels.splice(d.from, 1)[0]; + labels.splice(d.to, 0, moved); + paint(); + void ws.run(MOVE, { key: material, id, index: d.to }).then(barrier); + } + }; + handle.addEventListener('pointerup', end); + handle.addEventListener('pointercancel', end); + } + + function paintDrop(): void { + const on = dragging !== null && dragging.to !== dragging.from; + setClass(drop, 'is-shown', on); + if (on && dragging) { + const slot = dragging.to > dragging.from ? dragging.to + 1 : dragging.to; + setStyleVar(drop, '--fsh-lbl-slot', String(slot)); + } + } + + function select(id: number | null): void { + if (selected === id) return; + selected = id; + const l = current(); + ratio = l?.imageSize ? l.imageSize[1] / l.imageSize[0] : (l ? l.size[1] / l.size[0] : null); + if (placeMode.armed) placeMode.cancel(); + paint(); + } + + function paintNote(): void { + let text = noteText, error = noteError; + if (!text) { + if (material === null) text = t('Choose a material to edit its labels.'); + else if (!ws.canRun(LIST)) { text = ws.why(LIST); error = true; } + } + setText(note, text); + setClass(note, 'is-error', error); + } + + function paint(): void { + const can = (n: string): boolean => material !== null && ws.canRun(n); + patchList(list, labels, { + key: (l) => String(l.id), + create: rowFor, + update: () => undefined, + }); + for (const row of Array.from(list.children) as HTMLElement[]) { + const l = labels.find((x) => String(x.id) === row.dataset.key); + if (!l) continue; + setText(q(row, '.fsh-lbl-name'), l.name || t('Label')); + setText(q(row, '.fsh-lbl-row-file'), l.path ? fileName(l.path) : t('No image')); + setClass(row, 'is-hidden', !l.visible); + setClass(row, 'has-no-image', !l.texture); + setAttr(row, 'aria-selected', l.id === selected ? 'true' : 'false'); + const eye = q(row, '.fsh-lbl-eye'); + const eyeIcon = l.visible ? 'eye' : 'eyeOff'; + setHtml(eye, icon(eyeIcon, 14), eyeIcon); + setPressed(eye, l.visible); + const eyeText = l.visible ? t('Hide Label') : t('Show Label'); + setTitle(eye, eyeText); + setAttr(eye, 'aria-label', eyeText); + setDisabled(eye as HTMLButtonElement, !can(SET)); + setDisabled(q<HTMLButtonElement>(row, '.fsh-lbl-del'), !can(REMOVE)); + } + setHidden(empty, labels.length > 0); + const addReason = material === null ? t('Choose a material to edit its labels.') : !ws.canRun(ADD) ? ws.why(ADD) : source === 'none' ? noSourceReason() : ''; + setDisabled(addBtn, addReason !== ''); + setTitle(addBtn, addReason || t('Add a label from an image file')); + + const l = current(); + const f = fields; + setClass(f.root, 'is-empty', l === null); + setAttr(f.root, 'aria-hidden', l === null ? 'true' : null); + const editable = l !== null && can(SET); + const why = l === null ? '' : can(SET) ? '' : ws.why(SET); + for (const n of [f.width, f.height, f.rotation, f.depth, f.opacity]) n.setDisabled(!editable, why); + for (const input of [f.name, f.twoSided, f.roughOn, f.metalOn]) setDisabled(input, !editable); + setDisabled(f.link, !editable); + const chooseReason = !editable ? why : source === 'none' ? noSourceReason() : ''; + setDisabled(f.choose, chooseReason !== ''); + setTitle(f.choose, chooseReason || t('Choose the label image')); + const placeReason = !editable ? why : !placeMode.available() ? t('Placing needs the viewport and the engine commands view.pick and scene.meshes.') : !l?.texture ? t('Choose an image first') : ''; + setDisabled(f.place, placeReason !== '' && !placeMode.armed); + setTitle(f.place, placeReason || t('Click a point on the part to put the label there')); + setPressed(f.link, linked); + if (!l) { paintNote(); return; } + setValue(f.name, l.name); + setText(f.file, l.path ? fileName(l.path) : t('No image')); + setTitle(f.file, l.path ?? ''); + f.width.set(+(l.size[0] * 1000).toFixed(3)); + f.height.set(+(l.size[1] * 1000).toFixed(3)); + f.rotation.set(+((l.rotation * 180) / Math.PI).toFixed(2)); + f.depth.set(+(l.depth * 1000).toFixed(3)); + f.opacity.set(l.opacity); + setChecked(f.twoSided, l.twoSided); + setChecked(f.roughOn, l.roughness !== null); + setChecked(f.metalOn, l.metalness !== null); + f.rough.set(l.roughness ?? 0.5); + f.metal.set(l.metalness ?? 1); + f.rough.setDisabled(!editable || l.roughness === null, why); + f.metal.setDisabled(!editable || l.metalness === null, why); + paintNote(); + } + + async function refresh(): Promise<void> { + const key = material; + const seq = ++fetchSeq; + if (key === null || !ws.canRun(LIST)) { + labels = []; + paint(); + return; + } + let next: LabelView[]; + try { + next = parseLabels(await ws.client.dispatch(LIST, { key })); + } catch (err) { + if (seq === fetchSeq) say(err instanceof Error ? err.message : String(err), true); + return; + } + if (seq !== fetchSeq || key !== material || dragging) return; + labels = next; + if (selected === null || !labels.some((l) => l.id === selected)) select(labels[0]?.id ?? null); + const l = current(); + if (l?.imageSize) ratio = l.imageSize[1] / l.imageSize[0]; + if (aspectFix !== null) { + const fix = labels.find((x) => x.id === aspectFix); + if (fix?.imageSize) { + aspectFix = null; + const r = fix.imageSize[1] / fix.imageSize[0]; + if (linked && Math.abs(fix.size[1] - fix.size[0] * r) > 1e-6) void send({ size: [fix.size[0], fix.size[0] * r] }, fix.id).then(barrier); + } else if (fix && !fix.texture) aspectFix = null; + } + paint(); + } + + let refreshQueued = false; + const queueRefresh = (): void => { + if (refreshQueued) return; + refreshQueued = true; + requestAnimationFrame(() => { refreshQueued = false; void refresh(); }); + }; + + ws.client.onSummary(queueRefresh); + ws.client.onCatalogue(() => { paint(); queueRefresh(); }); + ws.client.onState(paint); + paint(); + + return { + show(next: string | null): void { + const key = next === null || next === '' ? null : String(next); + if (key === material) { queueRefresh(); return; } + if (placeMode.armed) placeMode.cancel(); + material = key; + labels = []; + selected = null; + noteText = ''; + aspectFix = null; + paint(); + void refresh(); + }, + }; +} diff --git a/frontend/src/ui/labels/labels.css b/frontend/src/ui/labels/labels.css new file mode 100644 index 00000000..c9055d87 --- /dev/null +++ b/frontend/src/ui/labels/labels.css @@ -0,0 +1,40 @@ +.fsh-lbl { --fsh-lbl-row-h: var(--ctl-md); --fsh-lbl-rows: 3; display: flex; flex-direction: column; gap: var(--space-2); padding-bottom: var(--space-3); } +.fsh-lbl-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); min-height: var(--ctl-md); } +.fsh-lbl-head .fsh-ws-section-title { margin: 0; } +.fsh-lbl-add { display: inline-flex; align-items: center; gap: var(--space-1); } + +.fsh-lbl-listbox { position: relative; min-height: calc(var(--fsh-lbl-row-h) * var(--fsh-lbl-rows) + var(--space-1) * 2); border: 1px solid var(--line-1); border-radius: var(--radius-md); background: var(--surface-1); } +.fsh-lbl-list { display: flex; flex-direction: column; padding: var(--space-1) 0; } +.fsh-lbl-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; margin: 0; padding: var(--space-2) var(--space-3); color: var(--text-faint); font-size: var(--fs-11); text-align: center; pointer-events: none; } +.fsh-lbl-empty[hidden] { display: none; } +.fsh-lbl-drop { position: absolute; left: var(--space-2); right: var(--space-2); top: calc(var(--space-1) + var(--fsh-lbl-row-h) * var(--fsh-lbl-slot, 0) - 1px); height: 2px; border-radius: var(--radius-pill); background: var(--accent-color); visibility: hidden; pointer-events: none; } +.fsh-lbl-drop.is-shown { visibility: visible; } + +.fsh-lbl-row { position: relative; display: grid; grid-template-columns: auto auto minmax(0, 1fr) minmax(0, auto) auto; align-items: center; gap: var(--space-1); height: var(--fsh-lbl-row-h); padding: 0 var(--space-1); color: var(--text-secondary); font-size: var(--fs-12); cursor: default; transform: translateY(var(--fsh-lbl-dy, 0px)); } +.fsh-lbl-row:hover { background: var(--bg-hover); } +.fsh-lbl-row[aria-selected="true"] { background: var(--accent-soft); color: var(--text-primary); } +.fsh-lbl-row.is-dragging { z-index: var(--z-raised); background: var(--surface-raised); box-shadow: var(--shadow-sm); } +.fsh-lbl-row.is-hidden .fsh-lbl-name, .fsh-lbl-row.is-hidden .fsh-lbl-row-file { opacity: 0.5; } +.fsh-lbl-row.has-no-image .fsh-lbl-row-file { color: var(--warn); } +.fsh-lbl-grip { display: inline-grid; place-items: center; width: var(--ctl-sm); height: var(--ctl-sm); color: var(--text-faint); cursor: grab; touch-action: none; } +.fsh-lbl-row.is-dragging .fsh-lbl-grip { cursor: grabbing; } +.fsh-lbl-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-lbl-row-file { max-width: 12ch; overflow: hidden; color: var(--text-faint); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-lbl-eye, .fsh-lbl-del { width: var(--ctl-sm); height: var(--ctl-sm); } + +.fsh-lbl-note { min-height: calc(var(--fs-11) * 2 * 1.4); margin: 0; color: var(--text-faint); font-size: var(--fs-11); line-height: 1.4; } +.fsh-lbl-note.is-error { color: var(--danger-text); } + +.fsh-lbl-fields { display: flex; flex-direction: column; gap: var(--space-1); } +.fsh-lbl-fields.is-empty { visibility: hidden; } +.fsh-lbl-image { display: flex; align-items: center; justify-content: flex-end; gap: var(--space-2); min-width: 0; } +.fsh-lbl-file { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.fsh-lbl-size { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: var(--space-1); } +.fsh-lbl-size-fields, .fsh-lbl-nums { display: flex; flex-direction: column; gap: var(--space-1); } +.fsh-lbl-link { width: var(--ctl-sm); height: calc(var(--ctl-md) * 2 + var(--space-1)); border-radius: var(--radius-md); } +.fsh-lbl-link[aria-pressed="true"] { color: var(--accent-color); background: var(--accent-soft); } +.fsh-lbl-check { display: flex; align-items: center; gap: var(--space-2); min-height: var(--ctl-md); color: var(--text-secondary); font-size: var(--fs-12); cursor: pointer; } +.fsh-lbl-check input { margin: 0; accent-color: var(--accent-color); } +.fsh-lbl-override { display: grid; grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr); align-items: center; gap: var(--space-2); } +.fsh-lbl-place { display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2); margin-top: var(--space-1); } +.fsh-lbl-place[aria-pressed="true"] { border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-color); } diff --git a/frontend/src/ui/labels/model.ts b/frontend/src/ui/labels/model.ts new file mode 100644 index 00000000..8695eee0 --- /dev/null +++ b/frontend/src/ui/labels/model.ts @@ -0,0 +1,125 @@ +export type Vec3 = [number, number, number]; + +export interface LabelView { + id: number; + name: string; + texture: string | null; + path: string | null; + imageSize: [number, number] | null; + origin: Vec3; + normal: Vec3; + up: Vec3; + size: [number, number]; + rotation: number; + depth: number; + opacity: number; + twoSided: boolean; + visible: boolean; + roughness: number | null; + metalness: number | null; +} + +const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d); +const opt = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null); +const vec = (v: unknown, d: Vec3): Vec3 => (Array.isArray(v) && v.length === 3 ? [num(v[0], d[0]), num(v[1], d[1]), num(v[2], d[2])] : d); + +function key(v: unknown): string | null { + return typeof v === 'number' || (typeof v === 'string' && v !== '') ? String(v) : null; +} + +export function parseLabels(reply: unknown): LabelView[] { + const list = reply && typeof reply === 'object' ? (reply as { labels?: unknown }).labels : null; + if (!Array.isArray(list)) return []; + const out: LabelView[] = []; + for (const raw of list) { + if (!raw || typeof raw !== 'object') continue; + const r = raw as Record<string, unknown>; + const id = num(r.id, 0); + if (id <= 0) continue; + const size = Array.isArray(r.size) && r.size.length === 2 ? [num(r.size[0], 0.1), num(r.size[1], 0.1)] as [number, number] : [0.1, 0.1] as [number, number]; + const img = Array.isArray(r.image_size) && r.image_size.length === 2 ? [num(r.image_size[0], 0), num(r.image_size[1], 0)] as [number, number] : null; + out.push({ + id, + name: typeof r.name === 'string' ? r.name : '', + texture: key(r.texture), + path: typeof r.path === 'string' ? r.path : null, + imageSize: img && img[0] > 0 && img[1] > 0 ? img : null, + origin: vec(r.origin, [0, 0, 0]), + normal: vec(r.normal, [0, 0, 1]), + up: vec(r.up, [0, 1, 0]), + size, + rotation: num(r.rotation, 0), + depth: num(r.depth, 0.01), + opacity: num(r.opacity, 1), + twoSided: r.two_sided === true, + visible: r.visible !== false, + roughness: opt(r.roughness), + metalness: opt(r.metalness), + }); + } + return out; +} + +export function fileName(path: string | null): string { + if (!path) return ''; + const parts = path.split(/[\\/]/); + return parts[parts.length - 1] || path; +} + +export function baseName(path: string): string { + return fileName(path).replace(/\.[^.]+$/, ''); +} + +const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s]; +const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + +export function normalize(a: Vec3): Vec3 | null { + const l = Math.hypot(a[0], a[1], a[2]); + return l > 1e-9 && Number.isFinite(l) ? scale(a, 1 / l) : null; +} + +function invert3(m: number[]): number[] | null { + const [a, b, c, d, e, f, g, h, i] = m; + const A = e * i - f * h, B = -(d * i - f * g), C = d * h - e * g; + const det = a * A + b * B + c * C; + if (!Number.isFinite(det) || Math.abs(det) < 1e-12) return null; + const k = 1 / det; + return [ + A * k, -(b * i - c * h) * k, (b * f - c * e) * k, + B * k, (a * i - c * g) * k, -(a * f - c * d) * k, + C * k, -(a * h - b * g) * k, (a * e - b * d) * k, + ]; +} + +const mul3 = (m: number[], v: Vec3): Vec3 => [ + m[0] * v[0] + m[1] * v[1] + m[2] * v[2], + m[3] * v[0] + m[4] * v[1] + m[5] * v[2], + m[6] * v[0] + m[7] * v[1] + m[8] * v[2], +]; + +export interface Placement { origin: Vec3; normal: Vec3; up: Vec3 } + +/** Object-space origin, normal and up of a world hit on a part whose world matrix is `world` (16 numbers, + * row-major, translation in the last column). Up follows world +Y, or world -Z on faces that point up or down. */ +export function placeFromHit(world: readonly number[], point: Vec3, normal: Vec3): Placement | null { + if (world.length !== 16) return null; + const lin = [world[0], world[1], world[2], world[4], world[5], world[6], world[8], world[9], world[10]]; + const inv = invert3(lin); + if (!inv) return null; + const t: Vec3 = [world[3], world[7], world[11]]; + const origin = mul3(inv, sub(point, t)); + const transposed = [lin[0], lin[3], lin[6], lin[1], lin[4], lin[7], lin[2], lin[5], lin[8]]; + const n = normalize(mul3(transposed, normal)); + if (!n) return null; + let up: Vec3 | null = null; + for (const w of [[0, 1, 0], [0, 0, -1], [1, 0, 0]] as Vec3[]) { + const u = normalize(mul3(inv, w)); + if (!u) continue; + const flat = normalize(sub(u, scale(n, dot(u, n)))); + if (flat && Math.abs(dot(u, n)) < 0.95) { up = flat; break; } + } + if (!up) return null; + const round = (v: Vec3): Vec3 => [+v[0].toFixed(6), +v[1].toFixed(6), +v[2].toFixed(6)]; + return { origin: round(origin), normal: round(n), up: round(up) }; +} diff --git a/frontend/src/ui/labels/place.ts b/frontend/src/ui/labels/place.ts new file mode 100644 index 00000000..b49888c8 --- /dev/null +++ b/frontend/src/ui/labels/place.ts @@ -0,0 +1,111 @@ +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { placeFromHit, type Placement, type Vec3 } from './model'; + +const FRAME = '.fsh-ws-vp-frame'; + +export interface PlaceResult { placement: Placement | null; message: string } + +function vec3(v: unknown): Vec3 | null { + return Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === 'number' && Number.isFinite(x)) ? [v[0], v[1], v[2]] : null; +} + +async function resolveHit(ws: Workspace, material: string, x: number, y: number, width: number, height: number): Promise<PlaceResult> { + const pick = await ws.client.dispatch<Record<string, unknown>>('view.pick', { x, y, width, height }); + const node = pick?.node; + const point = vec3(pick?.point), normal = vec3(pick?.normal); + if ((typeof node !== 'string' && typeof node !== 'number') || !point || !normal) { + return { placement: null, message: t('Nothing under the pointer; click a part that wears this material.') }; + } + const scene = await ws.client.dispatch<{ instances?: unknown }>('scene.meshes', {}); + const list = Array.isArray(scene?.instances) ? scene.instances as Array<Record<string, unknown>> : []; + const inst = list.find((i) => String(i.node) === String(node)); + if (!inst || !Array.isArray(inst.world)) return { placement: null, message: t('The picked part could not be read.') }; + if (String(inst.material ?? '') !== material) { + return { placement: null, message: t('That part does not wear this material.') }; + } + const placement = placeFromHit(inst.world as number[], point, normal); + return placement ? { placement, message: '' } : { placement: null, message: t('The picked part could not be read.') }; +} + +/** One click in the viewport frame, taken before the viewport's own selection handling. Resolves with the hit's + * placement in the part's object space, or a message; `cancel` ends it without a result. */ +export class PlaceMode { + private done: ((r: PlaceResult | null) => void) | null = null; + private readonly onDown = (e: PointerEvent): void => this.down(e); + private readonly onSwallow = (e: Event): void => { if (this.inFrame(e)) { e.preventDefault(); e.stopPropagation(); } }; + private readonly onKey = (e: KeyboardEvent): void => { + if (e.key !== 'Escape') return; + e.preventDefault(); + e.stopPropagation(); + this.finish(null); + }; + + constructor(private readonly ws: Workspace) {} + + get armed(): boolean { return this.done !== null; } + + available(): boolean { + return this.ws.canRun('view.pick') && this.ws.canRun('scene.meshes') && document.querySelector(FRAME) !== null; + } + + start(material: string): Promise<PlaceResult | null> { + this.finish(null); + return new Promise((resolve) => { + this.done = (r) => resolve(r); + this.material = material; + window.addEventListener('pointerdown', this.onDown, true); + window.addEventListener('pointerup', this.onSwallow, true); + window.addEventListener('click', this.onSwallow, true); + window.addEventListener('dblclick', this.onSwallow, true); + window.addEventListener('keydown', this.onKey, true); + }); + } + + cancel(): void { this.finish(null); } + + private material = ''; + + private inFrame(e: Event): boolean { + const frame = document.querySelector(FRAME); + return frame !== null && e.target instanceof Node && frame.contains(e.target); + } + + private down(e: PointerEvent): void { + if (!this.inFrame(e)) return; + e.preventDefault(); + e.stopPropagation(); + if (e.button !== 0) { this.finish(null); return; } + const frame = document.querySelector(FRAME) as HTMLElement; + const r = frame.getBoundingClientRect(); + const material = this.material; + const done = this.done; + this.detach(); + this.done = null; + if (!done) return; + resolveHit(this.ws, material, e.clientX - r.left, e.clientY - r.top, Math.max(1, r.width), Math.max(1, r.height)) + .then(done) + .catch((err: unknown) => done({ placement: null, message: err instanceof Error ? err.message : String(err) })); + } + + private detach(): void { + window.removeEventListener('pointerdown', this.onDown, true); + window.removeEventListener('keydown', this.onKey, true); + window.clearTimeout(this.swallowTimer); + this.swallowTimer = window.setTimeout(() => { + if (this.done) return; + window.removeEventListener('pointerup', this.onSwallow, true); + window.removeEventListener('click', this.onSwallow, true); + window.removeEventListener('dblclick', this.onSwallow, true); + }, 400); + } + + private swallowTimer: number | undefined; + + private finish(r: PlaceResult | null): void { + const done = this.done; + this.done = null; + this.detach(); + done?.(r); + } +} diff --git a/frontend/src/ui/library.ts b/frontend/src/ui/library.ts index 4d9b5296..ffe9d3d5 100644 --- a/frontend/src/ui/library.ts +++ b/frontend/src/ui/library.ts @@ -1,30 +1,8 @@ -import { el, q, setAttr, setClass } from '../shell/dom'; -import { icon } from '../shell/icons'; +import { el, q, setClass } from '../shell/dom'; import { registerPanel } from '../shell/registry'; import { t } from '../i18n'; import type { Workspace } from './context'; - -const SHELF_KEY = 'formshot.library.shelf'; -const SHELVES: ReadonlyArray<readonly [string, string]> = [ - ['all', 'All'], - ['favorites', 'Favorites'], - ['recent', 'Recent'], - ['project', 'In project'], -]; -const CATEGORIES: readonly string[] = ['Metal', 'Plastic', 'Glass', 'Paint', 'Rubber', 'Fabric', 'Wood', 'Stone', 'Ceramic', 'Liquid', 'Gem', 'Emissive']; - -function storedShelf(): string { - try { - const v = localStorage.getItem(SHELF_KEY); - return SHELVES.some(([id]) => id === v) ? v as string : 'all'; - } catch { - return 'all'; - } -} - -function saveShelf(id: string): void { - try { localStorage.setItem(SHELF_KEY, id); } catch { return; } -} +import { mountLibraryPanel } from './library/panel'; export function mountLibrary(ws: Workspace): void { registerPanel({ @@ -34,50 +12,9 @@ export function mountLibrary(ws: Workspace): void { grow: true, title: 'Library', mount(host) { - const shelves = SHELVES.map(([id, label]) => `<button class="fsh-ws-shelf" type="button" role="tab" data-shelf="${id}" aria-selected="false">${t(label)}</button>`).join(''); - const cats = CATEGORIES.map((c) => `<li><button class="fsh-ws-cat" type="button" data-cat="${c}" aria-pressed="false"><span class="fsh-ws-cat-name">${t(c)}</span><span class="fsh-ws-cat-count fsh-tabular" data-no-i18n>0</span></button></li>`).join(''); - const root = el(`<div class="fsh-ws-lib"> -<div class="fsh-ws-lib-head"><span class="fsh-ws-lib-title">${icon('library', 14)}<span>${t('Library')}</span></span></div> -<label class="fsh-ws-lib-search">${icon('search', 14)}<input class="fsh-input" type="search" placeholder="Search materials" aria-label="Search materials" spellcheck="false" autocomplete="off"></label> -<div class="fsh-ws-lib-shelves" role="tablist" aria-label="Shelves">${shelves}</div> -<div class="fsh-ws-lib-body"> - <ul class="fsh-ws-lib-cats" aria-label="Categories">${cats}</ul> - <div class="fsh-ws-lib-grid" role="list"> - <div class="fsh-ws-empty is-center">${icon('material', 28)}<p>${t('Materials arrive in 0.5.0')}</p></div> - </div> -</div> -<div class="fsh-ws-splitter" role="separator" aria-orientation="vertical" aria-label="Resize the library" tabindex="0"></div> -</div>`); - host.appendChild(root); - - let shelf = storedShelf(); - let category = ''; - const paint = (): void => { - for (const b of root.querySelectorAll<HTMLElement>('.fsh-ws-shelf')) { - const on = b.dataset.shelf === shelf; - setAttr(b, 'aria-selected', on ? 'true' : 'false'); - setAttr(b, 'tabindex', on ? '0' : '-1'); - } - for (const b of root.querySelectorAll<HTMLElement>('.fsh-ws-cat')) setAttr(b, 'aria-pressed', b.dataset.cat === category ? 'true' : 'false'); - }; - q(root, '.fsh-ws-lib-shelves').addEventListener('click', (e) => { - const b = (e.target as HTMLElement).closest<HTMLElement>('.fsh-ws-shelf'); - if (!b?.dataset.shelf) return; - shelf = b.dataset.shelf; - saveShelf(shelf); - paint(); - }); - q(root, '.fsh-ws-lib-cats').addEventListener('click', (e) => { - const b = (e.target as HTMLElement).closest<HTMLElement>('.fsh-ws-cat'); - if (!b?.dataset.cat) return; - category = category === b.dataset.cat ? '' : b.dataset.cat; - paint(); - }); - const search = q<HTMLInputElement>(root, 'input[type="search"]'); - search.addEventListener('keydown', (e) => { - if (e.key === 'Escape' && search.value) { search.value = ''; e.stopPropagation(); } - }); - paint(); + const panel = mountLibraryPanel(ws, host); + const root = panel.root; + root.appendChild(el(`<div class="fsh-ws-splitter" role="separator" aria-orientation="vertical" aria-label="${t('Resize the library')}" tabindex="0"></div>`)); splitter(q(root, '.fsh-ws-splitter'), root, ws); }, }); diff --git a/frontend/src/ui/library/actions.ts b/frontend/src/ui/library/actions.ts new file mode 100644 index 00000000..de4f34e6 --- /dev/null +++ b/frontend/src/ui/library/actions.ts @@ -0,0 +1,150 @@ +import { registerCommands, registerMenu, runCommand, refreshState } from '../../shell/registry'; +import { toast } from '../../shell/toast'; +import { confirmDialog } from '../../shell/dialog'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { APPLY, ASSIGN, FAVORITE, GET, REMOVE, applyPreset, selectedParts, type Preset, type Scope } from './data'; +import { DetailsPopover } from './details'; + +export const TILE_MENU = 'context.library.tile'; + +export interface PanelLink { + find(id: string): Preset | undefined; + active(): Preset | null; + reload(): void; + repaint(id: string): void; + rectOf(id: string): DOMRect | null; + shelf(): string; +} + +export interface LibraryActions { + apply(preset: Preset, scope: Scope, nodes?: readonly string[]): Promise<boolean>; + menu(preset: Preset, x: number, y: number): void; + favorite(preset: Preset, on: boolean): Promise<void>; + details(preset: Preset): void; + remove(preset: Preset): Promise<void>; +} + +const SCOPE_DONE: Record<Scope, string> = { + part: 'Applied {name} to the selected parts', + group: 'Applied {name} to their groups', + same_material: 'Applied {name} to every part with the same material', +}; + +const DROP_DONE: Record<Scope, string> = { + part: 'Applied {name} to {part}', + group: 'Applied {name} to the group of {part}', + same_material: 'Applied {name} to every part with the material of {part}', +}; + +export function libraryActions(ws: Workspace, panel: PanelLink): LibraryActions { + let target: Preset | null = null; + const details = new DetailsPopover(ws.ctx.slots.overlayRoot); + + const fromArgs = (args?: Record<string, unknown>): Preset | null => { + const id = typeof args?.id === 'string' ? args.id : ''; + return (id ? panel.find(id) : undefined) ?? target ?? panel.active(); + }; + const canApply = (p: Preset | null): boolean => { + if (!p) return false; + if (!selectedParts(ws.client.summary).length) return false; + return ws.canRun(p.material !== null ? ASSIGN : APPLY); + }; + + const actions: LibraryActions = { + async apply(preset, scope, nodes) { + const picked = nodes ?? selectedParts(ws.client.summary); + try { + const out = await applyPreset(ws, preset, picked, scope); + if (!out.ok) { toast(out.message, 'error'); return false; } + } catch (err) { + toast(err instanceof Error ? err.message : String(err), 'error'); + return false; + } + const part = nodes?.length === 1 ? ws.client.summary?.nodes.find((n) => String(n.id) === nodes[0])?.name : undefined; + ws.client.message(part ? t(DROP_DONE[scope], { name: preset.name, part }) : t(SCOPE_DONE[scope], { name: preset.name })); + if (panel.shelf() === 'recent') panel.reload(); + return true; + }, + menu(preset, x, y) { + target = preset; + refreshState(); + runCommand('menu.context', { id: TILE_MENU, x, y, args: { id: preset.id } }); + }, + async favorite(preset, on) { + if (!ws.canRun(FAVORITE)) { toast(ws.why(FAVORITE), 'error'); return; } + try { + await ws.client.dispatch(FAVORITE, { id: preset.id, on }); + } catch (err) { + toast(err instanceof Error ? err.message : String(err), 'error'); + return; + } + preset.favorite = on; + panel.repaint(preset.id); + if (panel.shelf() === 'favorites') panel.reload(); + }, + details(preset) { + const rect = panel.rectOf(preset.id); + details.open(preset, rect, ws.canRun(GET) ? ws.client.dispatch(GET, { id: preset.id }) : Promise.reject(new Error(ws.why(GET)))); + }, + async remove(preset) { + if (!preset.user) return; + if (!ws.canRun(REMOVE)) { toast(ws.why(REMOVE), 'error'); return; } + const sure = await confirmDialog('Remove from Library', t('Remove {name} from your library? Documents that use it keep their material.', { name: preset.name }), { ok: 'Remove', danger: true }); + if (!sure) return; + try { + await ws.client.dispatch(REMOVE, { id: preset.id }); + } catch (err) { + toast(err instanceof Error ? err.message : String(err), 'error'); + return; + } + panel.reload(); + }, + }; + + registerCommands([ + { + id: 'preset.apply', label: 'Apply to Selected Parts', group: 'Library', palette: false, + enabled: () => canApply(fromArgs()), + run: (args) => { const p = fromArgs(args); if (p) void actions.apply(p, 'part'); }, + }, + { + id: 'preset.applyGroup', label: 'Apply to Their Groups', group: 'Library', palette: false, + enabled: () => canApply(fromArgs()), + run: (args) => { const p = fromArgs(args); if (p) void actions.apply(p, 'group'); }, + }, + { + id: 'preset.applySameMaterial', label: 'Apply to Every Part with the Same Material', group: 'Library', palette: false, + enabled: () => canApply(fromArgs()), + run: (args) => { const p = fromArgs(args); if (p) void actions.apply(p, 'same_material'); }, + }, + { + id: 'preset.favorite', label: 'Favorite', group: 'Library', palette: false, + enabled: () => { const p = fromArgs(); return !!p && p.material === null && ws.canRun(FAVORITE); }, + checked: () => fromArgs()?.favorite === true, + run: (args) => { const p = fromArgs(args); if (p) void actions.favorite(p, !p.favorite); }, + }, + { + id: 'preset.details', label: 'Details', group: 'Library', palette: false, + enabled: () => { const p = fromArgs(); return !!p && p.material === null; }, + run: (args) => { const p = fromArgs(args); if (p) actions.details(p); }, + }, + { + id: 'preset.remove', label: 'Remove from Library', group: 'Library', palette: false, + enabled: () => { const p = fromArgs(); return !!p && p.user && ws.canRun(REMOVE); }, + run: (args) => { const p = fromArgs(args); if (p) void actions.remove(p); }, + }, + ]); + registerMenu({ + id: TILE_MENU, + items: [ + { command: 'preset.apply', section: 0 }, + { command: 'preset.applyGroup', section: 0 }, + { command: 'preset.applySameMaterial', section: 0 }, + { command: 'preset.favorite', section: 1 }, + { command: 'preset.details', section: 1 }, + { command: 'preset.remove', section: 2 }, + ], + }); + return actions; +} diff --git a/frontend/src/ui/library/data.ts b/frontend/src/ui/library/data.ts new file mode 100644 index 00000000..6852d6c0 --- /dev/null +++ b/frontend/src/ui/library/data.ts @@ -0,0 +1,214 @@ +import { api } from '../../shell/api'; +import type { SceneSummary } from '../../engine/types'; +import type { Workspace } from '../context'; + +export const LIST = 'library.list'; +export const GET = 'library.get'; +export const APPLY = 'library.apply'; +export const FAVORITE = 'library.favorite'; +export const SAVE = 'library.save'; +export const REMOVE = 'library.remove'; +export const ASSIGN = 'material.assign'; + +export const CATEGORIES: readonly string[] = ['Metal', 'Plastic', 'Glass', 'Paint', 'Rubber', 'Fabric', 'Wood', 'Stone', 'Ceramic', 'Liquid', 'Gem', 'Emissive']; + +export type Shelf = 'all' | 'favorites' | 'recent' | 'project' | 'user'; +export const SHELVES: ReadonlyArray<readonly [Shelf, string]> = [ + ['all', 'All'], + ['favorites', 'Favorites'], + ['recent', 'Recent'], + ['project', 'In project'], + ['user', 'User'], +]; + +export type Scope = 'part' | 'group' | 'same_material'; + +export const TYPE_LABEL: Readonly<Record<string, string>> = { + generic: 'Generic', plastic: 'Plastic', plastic_clear: 'Clear plastic', metal: 'Metal', metal_brushed: 'Brushed metal', + paint: 'Paint', paint_metallic: 'Metallic paint', glass: 'Glass', glass_thin: 'Thin glass', liquid: 'Liquid', gem: 'Gem', + rubber: 'Rubber', fabric: 'Fabric', ceramic: 'Ceramic', diffuse: 'Diffuse', emissive: 'Emissive', wood: 'Wood', stone: 'Stone', +}; + +export interface Preset { + readonly id: string; + readonly name: string; + readonly category: string; + readonly type: string; + readonly tags: readonly string[]; + favorite: boolean; + readonly user: boolean; + readonly material: string | null; + readonly hash: string; +} + +export interface PresetDetail { + id: string; + name: string; + category: string; + type: string; + tags: string[]; + params: Record<string, unknown>; + sourceKind: string; + reference: string; + notes: string; + urls: string[]; + authored: string[]; + licence: string; +} + +function obj(v: unknown): Record<string, unknown> | null { + return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null; +} + +function str(v: unknown, fallback = ''): string { + return typeof v === 'string' ? v : typeof v === 'number' ? String(v) : fallback; +} + +function strings(v: unknown): string[] { + return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; +} + +export function parsePreset(raw: unknown, favorites?: ReadonlySet<string>): Preset | null { + const o = obj(raw); + const id = o ? str(o.id) : ''; + if (!o || !id) return null; + return { + id, + name: str(o.name, id), + category: str(o.category), + type: str(o.type, str(o.type_id)), + tags: strings(o.tags), + favorite: o.favorite === true || o.favourite === true || (favorites?.has(id) ?? false), + user: o.user === true || o.source === 'user' || id.startsWith('user/'), + material: null, + hash: str(o.sha256, str(o.hash)), + }; +} + +function listOf(o: Record<string, unknown> | null, raw: unknown): unknown[] { + if (Array.isArray(raw)) return raw; + for (const k of ['presets', 'items', 'results', 'ids', 'recent']) if (o && Array.isArray(o[k])) return o[k] as unknown[]; + return []; +} + +export function parseList(raw: unknown): Preset[] { + const top = obj(raw); + const o = obj(top?.result) ?? top; + const favs = new Set(strings(o?.favorites ?? o?.favourites)); + const out: Preset[] = []; + const seen = new Set<string>(); + for (const item of listOf(o, obj(raw) ? o : raw)) { + const p = typeof item === 'string' ? parsePreset({ id: item }, favs) : parsePreset(item, favs); + if (p && !seen.has(p.id)) { seen.add(p.id); out.push(p); } + } + return out; +} + +export function parseDetail(raw: unknown): PresetDetail | null { + const top = obj(raw); + const o = obj(top?.preset) ?? obj(top?.result) ?? top; + if (!o || !str(o.id)) return null; + const src = obj(o.source); + return { + id: str(o.id), + name: str(o.name, str(o.id)), + category: str(o.category), + type: str(o.type, str(o.type_id)), + tags: strings(o.tags), + params: obj(o.params) ?? {}, + sourceKind: str(src?.kind), + reference: str(src?.reference), + notes: str(src?.notes), + urls: strings(src?.urls), + authored: strings(src?.authored), + licence: str(o.licence, str(o.license)), + }; +} + +export function categoryOfType(type: string): string { + const base = type.split('_')[0]; + const hit = CATEGORIES.find((c) => c.toLowerCase() === base); + if (hit) return hit; + return base === 'diffuse' || base === 'generic' ? 'Plastic' : ''; +} + +export function projectMaterials(summary: SceneSummary | null): Preset[] { + if (!summary) return []; + return summary.materials.map((m) => { + const key = str(m.key); + const type = str(m.type_id, 'generic'); + return { + id: `project/${key}`, + name: str(m.name, key), + category: categoryOfType(type), + type, + tags: [], + favorite: false, + user: false, + material: key, + hash: '', + }; + }).filter((p) => p.material !== ''); +} + +export function thumbUrl(preset: Pick<Preset, 'id' | 'hash'>, size: number): string { + const path = preset.id.split('/').map(encodeURIComponent).join('/'); + const h = preset.hash ? `&h=${encodeURIComponent(preset.hash)}` : ''; + return api.url(`/api/library/thumbnail/${path}?size=${size}${h}`); +} + +export function partMaterial(summary: SceneSummary | null, node: string): string | null { + const n = summary?.nodes.find((x) => String(x.id) === node); + const m = n?.raw.material; + return typeof m === 'string' || typeof m === 'number' ? String(m) : null; +} + +export function selectedParts(summary: SceneSummary | null): string[] { + return (summary?.selection ?? []).map(String); +} + +export function scopeNodes(summary: SceneSummary | null, nodes: readonly string[], scope: Scope): string[] { + if (!summary || scope === 'part') return [...nodes]; + const byId = new Map(summary.nodes.map((n) => [String(n.id), n])); + if (scope === 'group') { + const out = new Set<string>(); + for (const id of nodes) { + const n = byId.get(id); + const parent = n?.parent; + out.add(parent !== null && parent !== undefined && byId.get(String(parent))?.kind === 'group' ? String(parent) : id); + } + return [...out]; + } + const keys = new Set(nodes.map((id) => partMaterial(summary, id)).filter((k): k is string => k !== null)); + if (!keys.size) return [...nodes]; + return summary.nodes.filter((n) => n.kind === 'part' && keys.has(String(n.raw.material ?? ''))).map((n) => String(n.id)); +} + +export function descendants(summary: SceneSummary | null, ids: readonly string[]): Set<string> { + const out = new Set<string>(ids); + if (!summary) return out; + let grew = true; + while (grew) { + grew = false; + for (const n of summary.nodes) { + const id = String(n.id); + if (!out.has(id) && n.parent !== null && out.has(String(n.parent))) { out.add(id); grew = true; } + } + } + return out; +} + +export interface ApplyOutcome { ok: boolean; message: string } + +export async function applyPreset(ws: Workspace, preset: Preset, nodes: readonly string[], scope: Scope): Promise<ApplyOutcome> { + if (!nodes.length) return { ok: false, message: 'Select a part first' }; + if (preset.material !== null) { + if (!ws.canRun(ASSIGN)) return { ok: false, message: ws.why(ASSIGN) }; + const ids = scopeNodes(ws.client.summary, nodes, scope); + await ws.client.dispatch(ASSIGN, { ids, material: preset.material }); + return { ok: true, message: '' }; + } + if (!ws.canRun(APPLY)) return { ok: false, message: ws.why(APPLY) }; + await ws.client.dispatch(APPLY, { id: preset.id, nodes: [...nodes], scope }); + return { ok: true, message: '' }; +} diff --git a/frontend/src/ui/library/details.ts b/frontend/src/ui/library/details.ts new file mode 100644 index 00000000..095c454d --- /dev/null +++ b/frontend/src/ui/library/details.ts @@ -0,0 +1,159 @@ +import { el, escapeHtml, patchList, q, setAttr, setHidden, setStyleVar, setText } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import { TYPE_LABEL, parseDetail, type Preset, type PresetDetail } from './data'; + +const WIDTH = 300; +const MARGIN = 8; + +type Format = (v: unknown) => string | null; + +const num = (digits: number, unit = ''): Format => (v) => typeof v === 'number' && Number.isFinite(v) ? `${v.toFixed(digits)}${unit}` : null; +const flag: Format = (v) => typeof v === 'boolean' ? (v ? t('Yes') : t('No')) : null; + +const VALUES: ReadonlyArray<readonly [string, string, Format]> = [ + ['base_metalness', 'Metalness', num(2)], + ['specular_roughness', 'Roughness', num(2)], + ['specular_ior', 'Index of refraction', num(3)], + ['specular_roughness_anisotropy', 'Anisotropy', num(2)], + ['transmission_weight', 'Transmission', num(2)], + ['transmission_depth', 'Transmission depth', num(3, ' m')], + ['transmission_dispersion_abbe_number', 'Abbe number', num(1)], + ['subsurface_weight', 'Subsurface', num(2)], + ['coat_weight', 'Coat', num(2)], + ['coat_roughness', 'Coat roughness', num(2)], + ['fuzz_weight', 'Fuzz', num(2)], + ['thin_film_thickness', 'Thin film thickness', num(3, ' µm')], + ['emission_luminance', 'Emission', num(0, ' cd/m²')], + ['geometry_opacity', 'Opacity', num(2)], + ['geometry_thin_walled', 'Thin walled', flag], +]; + +const SOURCE_KIND: Readonly<Record<string, string>> = { measured: 'Measured', published: 'Published', authored: 'Authored' }; + +export function displayColor(acescg: unknown): string | null { + if (!Array.isArray(acescg) || acescg.length < 3) return null; + const c = acescg.slice(0, 3).map(Number); + if (!c.every(Number.isFinite)) return null; + const m = [[1.70505, -0.62179, -0.08326], [-0.13026, 1.1408, -0.01055], [-0.024, -0.12897, 1.15297]]; + const enc = (x: number): number => { + const v = Math.max(0, Math.min(1, x)); + return Math.round((v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055) * 255); + }; + const rgb = m.map((r) => enc(r[0] * c[0] + r[1] * c[1] + r[2] * c[2])); + return `#${rgb.map((v) => v.toString(16).padStart(2, '0')).join('')}`; +} + +interface Row { key: string; label: string; value: string } + +export class DetailsPopover { + private readonly root: HTMLElement; + private readonly swatch: HTMLElement; + private readonly name: HTMLElement; + private readonly meta: HTMLElement; + private readonly values: HTMLElement; + private readonly tags: HTMLElement; + private readonly kind: HTMLElement; + private readonly reference: HTMLElement; + private readonly notes: HTMLElement; + private readonly status: HTMLElement; + private seq = 0; + private before: Element | null = null; + + constructor(overlayRoot: HTMLElement) { + this.root = el(`<div class="fsh-lib-pop" role="dialog" aria-label="${escapeHtml(t('Material details'))}" tabindex="-1" hidden> +<header class="fsh-lib-pop-head"><span class="fsh-lib-pop-swatch" aria-hidden="true"></span><span class="fsh-lib-pop-title"><span class="fsh-lib-pop-name" data-no-i18n></span><span class="fsh-lib-pop-meta" data-no-i18n></span></span><button type="button" class="fsh-icon-btn fsh-lib-pop-x" aria-label="${escapeHtml(t('Close'))}">${icon('close', 14)}</button></header> +<p class="fsh-lib-pop-status" data-no-i18n></p> +<dl class="fsh-lib-pop-values" data-no-i18n></dl> +<div class="fsh-lib-pop-tags" data-no-i18n></div> +<section class="fsh-lib-pop-source"><h4>${escapeHtml(t('Source'))}</h4><p class="fsh-lib-pop-kind" data-no-i18n></p><p class="fsh-lib-pop-ref fsh-selectable" data-no-i18n></p><p class="fsh-lib-pop-notes fsh-selectable" data-no-i18n></p></section> +</div>`); + overlayRoot.appendChild(this.root); + this.swatch = q(this.root, '.fsh-lib-pop-swatch'); + this.name = q(this.root, '.fsh-lib-pop-name'); + this.meta = q(this.root, '.fsh-lib-pop-meta'); + this.values = q(this.root, '.fsh-lib-pop-values'); + this.tags = q(this.root, '.fsh-lib-pop-tags'); + this.kind = q(this.root, '.fsh-lib-pop-kind'); + this.reference = q(this.root, '.fsh-lib-pop-ref'); + this.notes = q(this.root, '.fsh-lib-pop-notes'); + this.status = q(this.root, '.fsh-lib-pop-status'); + q(this.root, '.fsh-lib-pop-x').addEventListener('click', () => this.close()); + this.root.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.close(); } }); + document.addEventListener('pointerdown', (e) => { if (!this.root.hidden && !this.root.contains(e.target as Node)) this.close(); }, true); + window.addEventListener('blur', () => this.close()); + } + + open(preset: Preset, anchor: DOMRect | null, detail: Promise<unknown>): void { + const seq = ++this.seq; + this.before = document.activeElement; + setText(this.name, preset.name); + setText(this.meta, `${t(preset.category)} · ${t(TYPE_LABEL[preset.type] ?? preset.type)}`); + setStyleVar(this.swatch, '--fsh-lib-swatch', 'transparent'); + setText(this.status, t('Loading')); + setHidden(this.status, false); + this.fill(null); + this.place(anchor); + setHidden(this.root, false); + this.root.focus({ preventScroll: true }); + detail.then((raw) => { + if (seq !== this.seq) return; + const d = parseDetail(raw); + if (!d) throw new Error(t('The engine sent the preset in an unknown shape')); + setHidden(this.status, true); + this.fill(d); + }).catch((err: unknown) => { + if (seq !== this.seq) return; + setText(this.status, err instanceof Error ? err.message : String(err)); + }); + } + + close(): void { + if (this.root.hidden) return; + this.seq++; + setHidden(this.root, true); + if (this.before instanceof HTMLElement && document.contains(this.before)) this.before.focus({ preventScroll: true }); + } + + private place(anchor: DOMRect | null): void { + const vw = window.innerWidth, vh = window.innerHeight; + let x = anchor ? anchor.right + MARGIN : (vw - WIDTH) / 2; + if (x + WIDTH > vw - MARGIN) x = Math.max(MARGIN, (anchor ? anchor.left - WIDTH - MARGIN : vw - WIDTH - MARGIN)); + const y = Math.max(MARGIN, Math.min(anchor ? anchor.top : vh / 4, vh - 360)); + setStyleVar(this.root, '--fsh-lib-pop-x', `${Math.round(x)}px`); + setStyleVar(this.root, '--fsh-lib-pop-y', `${Math.round(y)}px`); + } + + private fill(d: PresetDetail | null): void { + const color = d ? displayColor(d.params.base_color ?? d.params.transmission_color ?? d.params.emission_color) : null; + setStyleVar(this.swatch, '--fsh-lib-swatch', color ?? 'transparent'); + const rows: Row[] = []; + if (d && color) rows.push({ key: 'base_color', label: t('Base color'), value: color.toUpperCase() }); + for (const [key, label, format] of VALUES) { + const value = d ? format(d.params[key]) : null; + if (value !== null) rows.push({ key, label: t(label), value }); + } + patchList(this.values, rows, { + key: (r) => r.key, + create: (r) => { const n = el(`<div class="fsh-lib-pop-row"><dt></dt><dd class="fsh-tabular"></dd></div>`); this.row(n, r); return n; }, + update: (n, r) => this.row(n, r), + }); + patchList(this.tags, d?.tags ?? [], { + key: (s) => s, + create: (s) => { const n = el('<span class="fsh-lib-pop-tag"></span>'); n.textContent = s; return n; }, + update: () => undefined, + }); + setHidden(this.tags, !d?.tags.length); + const kind = d ? SOURCE_KIND[d.sourceKind] : undefined; + setText(this.kind, kind ? t(kind) : d?.sourceKind ?? ''); + setText(this.reference, d?.reference ?? ''); + setText(this.notes, d?.notes ?? ''); + setAttr(this.reference, 'title', d?.urls.join('\n') || null); + setHidden(q(this.root, '.fsh-lib-pop-source'), !d || (!d.reference && !d.sourceKind)); + } + + private row(n: HTMLElement, r: Row): void { + setText(q(n, 'dt'), r.label); + setText(q(n, 'dd'), r.value); + } +} diff --git a/frontend/src/ui/library/drag.ts b/frontend/src/ui/library/drag.ts new file mode 100644 index 00000000..5e9ac579 --- /dev/null +++ b/frontend/src/ui/library/drag.ts @@ -0,0 +1,162 @@ +import { el, escapeHtml, q, setAttr, setClass, setHidden, setStyleVar, setText } from '../../shell/dom'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import type { Preset, Scope } from './data'; +import { dropTarget, type DropHit } from './drop'; + +const SLOP_PX = 5; + +function quietly(fn: () => void): void { + try { fn(); } catch { return; } +} + +export interface DragHooks { + thumb(preset: Preset): string | null; + drop(preset: Preset, node: string, scope: Scope): void; +} + +export class PresetDrag { + private readonly ghost: HTMLElement; + private readonly img: HTMLImageElement; + private readonly name: HTMLElement; + private readonly hint: HTMLElement; + private preset: Preset | null = null; + private pointer = -1; + private start = { x: 0, y: 0 }; + private last = { x: 0, y: 0 }; + private dragging = false; + private scope: Scope = 'part'; + private hit: DropHit = { inside: false, node: null, name: '' }; + private frame = 0; + + constructor(overlayRoot: HTMLElement, private readonly capture: HTMLElement, private readonly hooks: DragHooks) { + this.ghost = el(`<div class="fsh-lib-ghost" aria-hidden="true" hidden><span class="fsh-lib-ghost-thumb"><img alt="" draggable="false"></span><span class="fsh-lib-ghost-text"><span class="fsh-lib-ghost-name" data-no-i18n></span><span class="fsh-lib-ghost-hint" data-no-i18n></span><span class="fsh-lib-ghost-keys">${escapeHtml(t('Alt: whole group. Shift: same material.'))}</span></span></div>`); + overlayRoot.appendChild(this.ghost); + this.img = q<HTMLImageElement>(this.ghost, 'img'); + this.name = q(this.ghost, '.fsh-lib-ghost-name'); + this.hint = q(this.ghost, '.fsh-lib-ghost-hint'); + window.addEventListener('pointermove', (e) => this.move(e), true); + window.addEventListener('pointerup', (e) => this.up(e), true); + window.addEventListener('pointercancel', (e) => { if (e.pointerId === this.pointer) this.cancel(); }, true); + window.addEventListener('keydown', (e) => this.key(e), true); + window.addEventListener('keyup', (e) => this.key(e), true); + window.addEventListener('blur', () => this.cancel()); + } + + get active(): boolean { return this.dragging; } + + press(preset: Preset, e: PointerEvent): void { + if (e.pointerType === 'touch' || this.pointer !== -1) return; + this.preset = preset; + this.pointer = e.pointerId; + this.start = { x: e.clientX, y: e.clientY }; + this.last = this.start; + } + + private scopeOf(e: { altKey: boolean; shiftKey: boolean }): Scope { + if (e.altKey) return 'group'; + if (e.shiftKey) return 'same_material'; + return 'part'; + } + + private move(e: PointerEvent): void { + if (e.pointerId !== this.pointer || !this.preset) return; + this.last = { x: e.clientX, y: e.clientY }; + if (!this.dragging) { + if (Math.hypot(e.clientX - this.start.x, e.clientY - this.start.y) < SLOP_PX) return; + this.begin(); + } + e.preventDefault(); + this.scope = this.scopeOf(e); + this.schedule(); + } + + private begin(): void { + const p = this.preset as Preset; + this.dragging = true; + quietly(() => this.capture.setPointerCapture(this.pointer)); + setClass(this.capture, 'is-dragging', true); + setText(this.name, p.name); + const url = this.hooks.thumb(p); + if (url) { if (this.img.getAttribute('src') !== url) this.img.src = url; } else this.img.removeAttribute('src'); + this.hit = { inside: false, node: null, name: '' }; + this.paint(); + setHidden(this.ghost, false); + } + + private schedule(): void { + if (this.frame) return; + this.frame = requestAnimationFrame(() => { + this.frame = 0; + if (!this.dragging) return; + const target = dropTarget(); + this.hit = target ? target.over(this.last.x, this.last.y, this.scope) : { inside: false, node: null, name: '' }; + this.paint(); + }); + } + + private paint(): void { + setStyleVar(this.ghost, '--fsh-lib-ghost-x', `${Math.round(this.last.x + 14)}px`); + setStyleVar(this.ghost, '--fsh-lib-ghost-y', `${Math.round(this.last.y + 14)}px`); + let hint: string; + if (!this.hit.inside) hint = t('Drop on a part in the viewport'); + else if (this.hit.node === null) hint = t('No part here'); + else if (this.scope === 'group') hint = t('Apply to the group of {name}', { name: this.hit.name }); + else if (this.scope === 'same_material') hint = t('Apply to every part with the material of {name}', { name: this.hit.name }); + else hint = t('Apply to {name}', { name: this.hit.name }); + setText(this.hint, hint); + setAttr(this.ghost, 'data-state', !this.hit.inside ? 'out' : this.hit.node === null ? 'empty' : 'part'); + } + + private key(e: KeyboardEvent): void { + if (!this.dragging) return; + if (e.type === 'keydown' && e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + this.cancel(); + return; + } + if (e.key !== 'Alt' && e.key !== 'Shift') return; + e.preventDefault(); + const next = this.scopeOf(e); + if (next !== this.scope) { this.scope = next; this.schedule(); } + } + + private up(e: PointerEvent): void { + if (e.pointerId !== this.pointer) return; + const preset = this.preset; + const was = this.dragging; + const scope = this.scopeOf(e); + this.reset(); + if (!was || !preset) return; + e.preventDefault(); + const target = dropTarget(); + if (!target) return; + void target.settle(e.clientX, e.clientY).then((hit) => { + target.clear(); + if (!hit.inside) return; + if (hit.node === null) { toast('Drop the material on a part', 'info'); return; } + this.hooks.drop(preset, hit.node, scope); + }); + } + + private cancel(): void { + if (this.pointer === -1) return; + const was = this.dragging; + this.reset(); + if (was) dropTarget()?.clear(); + } + + private reset(): void { + if (this.dragging) { + quietly(() => this.capture.releasePointerCapture(this.pointer)); + } + if (this.frame) { cancelAnimationFrame(this.frame); this.frame = 0; } + this.dragging = false; + this.pointer = -1; + this.preset = null; + this.scope = 'part'; + setClass(this.capture, 'is-dragging', false); + setHidden(this.ghost, true); + } +} diff --git a/frontend/src/ui/library/drop.ts b/frontend/src/ui/library/drop.ts new file mode 100644 index 00000000..4f878cb9 --- /dev/null +++ b/frontend/src/ui/library/drop.ts @@ -0,0 +1,123 @@ +import type { Workspace } from '../context'; +import type { RasterView } from '../raster-view'; +import { descendants, scopeNodes, type Scope } from './data'; + +const PICK = 'view.pick'; + +export interface DropHit { + inside: boolean; + node: string | null; + name: string; +} + +export interface DropTarget { + over(clientX: number, clientY: number, scope: Scope): DropHit; + settle(clientX: number, clientY: number): Promise<DropHit>; + clear(): void; +} + +export interface ViewportDropHost { + frame(): DOMRect; + size(): { width: number; height: number }; + raster(): RasterView | null; + dpr(): number; +} + +let current: DropTarget | null = null; + +export function dropTarget(): DropTarget | null { return current; } + +export function attachPresetDrop(ws: Workspace, host: ViewportDropHost): void { + let lastKey = ''; + let lit = false; + let asyncHit: { x: number; y: number; node: string | null } | null = null; + let asking = false; + let want: { x: number; y: number } | null = null; + + const local = (cx: number, cy: number): { x: number; y: number; inside: boolean } => { + const r = host.frame(); + const s = host.size(); + const x = cx - r.left, y = cy - r.top; + return { x, y, inside: x >= 0 && y >= 0 && x <= s.width && y <= s.height && s.width > 0 }; + }; + const nameOf = (node: string | null): string => { + if (node === null) return ''; + return ws.client.summary?.nodes.find((n) => String(n.id) === node)?.name ?? node; + }; + const partOf = (node: string | null): string | null => { + if (node === null) return null; + const n = ws.client.summary?.nodes.find((x) => String(x.id) === node); + return n && n.kind !== 'part' && n.kind !== 'group' ? null : node; + }; + const rasterPick = (x: number, y: number): string | null | undefined => { + const r = host.raster(); + if (!r || !r.usable) return undefined; + const k = host.dpr(); + return r.renderer.pick(x * k, y * k); + }; + const ask = (): void => { + if (asking || !want || !ws.canRun(PICK)) return; + const at = want; + want = null; + asking = true; + const s = host.size(); + ws.client.dispatch<Record<string, unknown>>(PICK, { x: at.x, y: at.y, width: s.width, height: s.height }).then((reply) => { + const n = reply && typeof reply === 'object' ? reply.node : null; + asyncHit = { x: at.x, y: at.y, node: typeof n === 'string' || typeof n === 'number' ? String(n) : null }; + }, () => { asyncHit = { x: at.x, y: at.y, node: null }; }).finally(() => { asking = false; ask(); }); + }; + const highlight = (node: string | null, scope: Scope): void => { + const r = host.raster(); + if (!r) return; + const key = node === null ? '' : `${node}|${scope}`; + if (key === lastKey) return; + lastKey = key; + if (node === null) { + if (lit) { lit = false; r.select(); } + return; + } + const summary = ws.client.summary; + const set = descendants(summary, scopeNodes(summary, [node], scope)); + lit = true; + r.renderer.setSelected(set); + }; + + const pickAt = (x: number, y: number): string | null => { + const fast = rasterPick(x, y); + if (fast !== undefined) return partOf(fast); + want = { x, y }; + ask(); + return asyncHit ? partOf(asyncHit.node) : null; + }; + + current = { + over(cx, cy, scope) { + const p = local(cx, cy); + if (!p.inside) { highlight(null, scope); return { inside: false, node: null, name: '' }; } + const node = pickAt(p.x, p.y); + highlight(node, scope); + return { inside: true, node, name: nameOf(node) }; + }, + async settle(cx, cy) { + const p = local(cx, cy); + if (!p.inside) return { inside: false, node: null, name: '' }; + const fast = rasterPick(p.x, p.y); + if (fast !== undefined) return { inside: true, node: partOf(fast), name: nameOf(partOf(fast)) }; + if (!ws.canRun(PICK)) return { inside: true, node: null, name: '' }; + try { + const s = host.size(); + const reply = await ws.client.dispatch<Record<string, unknown>>(PICK, { x: p.x, y: p.y, width: s.width, height: s.height }); + const n = reply && typeof reply === 'object' ? reply.node : null; + const node = partOf(typeof n === 'string' || typeof n === 'number' ? String(n) : null); + return { inside: true, node, name: nameOf(node) }; + } catch { + return { inside: true, node: null, name: '' }; + } + }, + clear() { + asyncHit = null; + want = null; + highlight(null, 'part'); + }, + }; +} diff --git a/frontend/src/ui/library/grid.ts b/frontend/src/ui/library/grid.ts new file mode 100644 index 00000000..40df66cd --- /dev/null +++ b/frontend/src/ui/library/grid.ts @@ -0,0 +1,323 @@ +import { el, setAttr, setClass, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { frameLater } from '../context'; +import type { Preset } from './data'; +import { ThumbLoader } from './thumbs'; + +const GAP = 8; +const PAD = 12; +const NAME_H = 22; +const OVERSCAN_ROWS = 2; +const STAR = '<svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" aria-hidden="true"><path d="M12 3.5l2.6 5.3 5.9.9-4.3 4.1 1 5.8L12 16.9l-5.2 2.7 1-5.8-4.3-4.1 5.9-.9z"/></svg>'; + +export interface GridHooks { + thumb(item: Preset, px: number): string | null; + badge(item: Preset): string; + activate(item: Preset): void; + menu(item: Preset, x: number, y: number, keyboard: boolean): void; + press(item: Preset, e: PointerEvent): void; + activeChanged(item: Preset | null): void; + scrolled(top: number): void; +} + +interface Tile { + node: HTMLElement; + img: HTMLImageElement; + badge: HTMLElement; + name: HTMLElement; + index: number; + id: string; + url: string | null; + pending: (() => void) | null; + visible: boolean; + x: number; + y: number; +} + +let serial = 0; + +export class VirtualGrid { + readonly root: HTMLElement; + private readonly space: HTMLElement; + private readonly tiles: Tile[] = []; + private readonly byNode = new WeakMap<Element, Tile>(); + private readonly loader = new ThumbLoader(); + private readonly io: IntersectionObserver; + private readonly uid = ++serial; + private items: readonly Preset[] = []; + private tileW = 96; + private cols = 1; + private rowH = 96 + NAME_H + GAP; + private left = PAD; + private width = 0; + private height = 0; + private activeIndex = -1; + private readonly schedule: () => void; + + constructor(private readonly hooks: GridHooks, label: string) { + this.root = el(`<div class="fsh-lib-grid" role="listbox" tabindex="0" aria-label="${label}" data-no-i18n><div class="fsh-lib-space"></div></div>`); + this.space = this.root.firstElementChild as HTMLElement; + this.schedule = frameLater(() => this.render()); + this.io = new IntersectionObserver((entries) => { + for (const e of entries) { + const tile = this.byNode.get(e.target); + if (!tile) continue; + tile.visible = e.isIntersecting; + if (tile.visible) this.load(tile); + else this.cancel(tile); + } + }, { root: this.root, rootMargin: '48px 0px' }); + this.root.addEventListener('scroll', () => { this.schedule(); this.hooks.scrolled(this.root.scrollTop); }, { passive: true }); + new ResizeObserver(() => this.layout()).observe(this.root); + this.root.addEventListener('keydown', (e) => this.key(e)); + this.root.addEventListener('pointerdown', (e) => { + const tile = this.tileAt(e.target); + if (!tile) return; + this.setActive(tile.index, false); + this.root.focus({ preventScroll: true }); + if (e.button === 0) this.hooks.press(this.items[tile.index], e); + }); + this.root.addEventListener('dblclick', (e) => { + const tile = this.tileAt(e.target); + if (tile) this.hooks.activate(this.items[tile.index]); + }); + this.root.addEventListener('contextmenu', (e) => { + const tile = this.tileAt(e.target); + if (!tile) return; + e.preventDefault(); + this.setActive(tile.index, false); + this.hooks.menu(this.items[tile.index], e.clientX, e.clientY, false); + }); + } + + get active(): Preset | null { return this.items[this.activeIndex] ?? null; } + get count(): number { return this.items.length; } + + setTileSize(px: number): void { + if (px === this.tileW) return; + const anchor = this.firstVisible(); + this.tileW = px; + this.layout(true); + if (anchor >= 0) this.root.scrollTop = Math.floor(anchor / this.cols) * this.rowH; + this.render(true); + } + + setItems(items: readonly Preset[], activeId = ''): void { + const prev = this.active?.id ?? ''; + this.items = items; + const want = activeId || prev; + const i = want ? items.findIndex((p) => p.id === want) : -1; + this.activeIndex = i; + this.layout(true); + this.render(true); + this.hooks.activeChanged(this.active); + } + + refreshItem(id: string): void { + for (const tile of this.tiles) if (tile.id === id && tile.index >= 0) this.paint(tile, true); + } + + scrollTo(top: number): void { this.root.scrollTop = top; this.render(); } + + focus(): void { this.root.focus({ preventScroll: true }); } + + rectOf(id: string): DOMRect | null { + const tile = this.tiles.find((x) => x.id === id && x.index >= 0 && !x.node.hidden); + return tile ? tile.node.getBoundingClientRect() : null; + } + + private firstVisible(): number { + return Math.floor(this.root.scrollTop / this.rowH) * this.cols; + } + + private layout(force = false): void { + const w = this.root.clientWidth; + const h = this.root.clientHeight; + if (!force && w === this.width && h === this.height) return; + this.width = w; + this.height = h; + const inner = Math.max(this.tileW, w - PAD * 2); + this.cols = Math.max(1, Math.floor((inner + GAP) / (this.tileW + GAP))); + this.rowH = this.tileW + NAME_H + GAP; + const used = this.cols * this.tileW + (this.cols - 1) * GAP; + this.left = Math.max(PAD, Math.floor((w - used) / 2)); + const rows = Math.ceil(this.items.length / this.cols); + setStyleVar(this.root, '--fsh-lib-tile', `${this.tileW}px`); + setStyleVar(this.space, '--fsh-lib-space-h', `${rows ? rows * this.rowH - GAP + PAD * 2 : 0}px`); + this.render(true); + } + + private poolSize(): number { + const rows = Math.ceil(this.height / this.rowH) + 1 + OVERSCAN_ROWS * 2; + return rows * this.cols; + } + + private ensurePool(n: number): void { + while (this.tiles.length < n) { + const node = el(`<div class="fsh-lib-tile" role="option" id="fsh-lib-${this.uid}-${this.tiles.length}" aria-selected="false" hidden> +<div class="fsh-lib-thumb"><img class="fsh-lib-img" alt="" draggable="false"><span class="fsh-lib-badge"></span><span class="fsh-lib-fav">${STAR}</span></div> +<div class="fsh-lib-name"></div></div>`); + const tile: Tile = { + node, + img: node.querySelector('img') as HTMLImageElement, + badge: node.querySelector('.fsh-lib-badge') as HTMLElement, + name: node.querySelector('.fsh-lib-name') as HTMLElement, + index: -1, id: '', url: null, pending: null, visible: false, x: -1, y: -1, + }; + tile.img.addEventListener('load', () => { if (tile.img.getAttribute('src')) setClass(tile.img, 'is-loaded', true); }); + this.byNode.set(node, tile); + this.tiles.push(tile); + this.space.appendChild(node); + this.io.observe(node); + } + } + + private render(rebind = false): void { + const n = this.items.length; + const first = Math.max(0, Math.floor((this.root.scrollTop - PAD) / this.rowH) - OVERSCAN_ROWS) * this.cols; + const pool = this.poolSize(); + this.ensurePool(pool); + const size = this.tiles.length; + const last = Math.min(n, first + Math.min(pool, size)); + const used = new Set<Tile>(); + for (let i = first; i < last; i++) { + const tile = this.tiles[i % size]; + used.add(tile); + const changed = tile.index !== i || tile.id !== this.items[i].id; + tile.index = i; + this.place(tile, i); + if (changed || rebind) this.paint(tile, changed); + if (tile.node.hidden) tile.node.hidden = false; + } + for (const tile of this.tiles) { + if (used.has(tile)) continue; + if (!tile.node.hidden) tile.node.hidden = true; + tile.index = -1; + this.cancel(tile); + } + const act = this.tiles.find((x) => x.index === this.activeIndex && this.activeIndex >= 0); + setAttr(this.root, 'aria-activedescendant', act ? act.node.id : null); + } + + private place(tile: Tile, i: number): void { + const x = this.left + (i % this.cols) * (this.tileW + GAP); + const y = PAD + Math.floor(i / this.cols) * this.rowH; + if (x === tile.x && y === tile.y) return; + tile.x = x; + tile.y = y; + tile.node.style.transform = `translate3d(${x}px, ${y}px, 0)`; + } + + private paint(tile: Tile, changed: boolean): void { + const item = this.items[tile.index]; + tile.id = item.id; + setText(tile.name, item.name); + setTitle(tile.node, item.name); + setText(tile.badge, this.hooks.badge(item)); + setClass(tile.node, 'is-favorite', item.favorite); + setClass(tile.node, 'is-user', item.user); + setAttr(tile.node, 'aria-selected', tile.index === this.activeIndex ? 'true' : 'false'); + setAttr(tile.node, 'aria-posinset', String(tile.index + 1)); + setAttr(tile.node, 'aria-setsize', String(this.items.length)); + setAttr(tile.node, 'aria-label', item.name); + const px = Math.round(this.tileW * Math.min(window.devicePixelRatio || 1, 2)); + const url = this.hooks.thumb(item, px); + if (url === tile.url && (!changed || tile.img.getAttribute('src') === url || tile.pending)) return; + this.cancel(tile); + tile.url = url; + if (url && this.loader.isLoaded(url)) { + setClass(tile.img, 'is-instant', true); + tile.img.src = url; + setClass(tile.img, 'is-loaded', true); + return; + } + setClass(tile.img, 'is-loaded', false); + setClass(tile.img, 'is-instant', false); + if (tile.img.hasAttribute('src')) tile.img.removeAttribute('src'); + if (url && tile.visible) this.load(tile); + } + + private load(tile: Tile): void { + const url = tile.url; + if (!url || tile.pending || tile.img.getAttribute('src') === url) return; + tile.pending = this.loader.request(url, (ok) => { + tile.pending = null; + if (!ok || tile.url !== url) return; + setClass(tile.img, 'is-instant', false); + tile.img.src = url; + }); + } + + private cancel(tile: Tile): void { + if (!tile.pending) return; + const stop = tile.pending; + tile.pending = null; + stop(); + } + + private tileAt(target: EventTarget | null): Tile | null { + const node = target instanceof Element ? target.closest('.fsh-lib-tile') : null; + const tile = node ? this.byNode.get(node) : undefined; + return tile && tile.index >= 0 && tile.index < this.items.length ? tile : null; + } + + setActive(index: number, reveal = true): void { + const next = this.items.length ? Math.max(0, Math.min(this.items.length - 1, index)) : -1; + if (next === this.activeIndex) { if (reveal) this.reveal(next); return; } + this.activeIndex = next; + for (const tile of this.tiles) if (tile.index >= 0) setAttr(tile.node, 'aria-selected', tile.index === next ? 'true' : 'false'); + if (reveal) this.reveal(next); + this.render(); + this.hooks.activeChanged(this.active); + } + + private reveal(i: number): void { + if (i < 0) return; + const top = PAD + Math.floor(i / this.cols) * this.rowH; + const bottom = top + this.rowH - GAP; + const st = this.root.scrollTop, vh = this.root.clientHeight; + if (top < st + PAD) this.root.scrollTop = Math.max(0, top - PAD); + else if (bottom > st + vh - PAD) this.root.scrollTop = bottom - vh + PAD; + } + + private key(e: KeyboardEvent): void { + if (e.target !== this.root || !this.items.length) return; + const i = this.activeIndex < 0 ? 0 : this.activeIndex; + const page = Math.max(1, Math.floor(this.root.clientHeight / this.rowH)) * this.cols; + let next: number | null = null; + switch (e.key) { + case 'ArrowRight': next = this.activeIndex < 0 ? 0 : Math.min(i + 1, this.items.length - 1); break; + case 'ArrowLeft': next = Math.max(0, i - 1); break; + case 'ArrowDown': next = this.activeIndex < 0 ? 0 : i + this.cols < this.items.length ? i + this.cols : i; break; + case 'ArrowUp': next = i - this.cols >= 0 ? i - this.cols : i; break; + case 'PageDown': next = i + page; break; + case 'PageUp': next = i - page; break; + case 'Home': next = 0; break; + case 'End': next = this.items.length - 1; break; + case 'Enter': { + const item = this.active; + if (item) this.hooks.activate(item); + break; + } + case 'ContextMenu': { + const item = this.active; + if (item) this.keyboardMenu(item); + break; + } + case 'F10': + if (!e.shiftKey) return; + if (this.active) this.keyboardMenu(this.active); + break; + default: return; + } + e.preventDefault(); + e.stopPropagation(); + if (next !== null) this.setActive(next); + } + + private keyboardMenu(item: Preset): void { + this.reveal(this.activeIndex); + this.render(); + const r = this.rectOf(item.id); + this.hooks.menu(item, r ? r.left + r.width / 2 : 0, r ? r.top + r.height / 2 : 0, true); + } +} diff --git a/frontend/src/ui/library/library.css b/frontend/src/ui/library/library.css new file mode 100644 index 00000000..3f11e7bd --- /dev/null +++ b/frontend/src/ui/library/library.css @@ -0,0 +1,83 @@ +.fsh-lib { position: relative; display: flex; flex-direction: column; height: 100%; min-height: 0; } +.fsh-lib .fsh-ws-lib-head { justify-content: space-between; gap: var(--space-2); } +.fsh-lib-head-tools { display: inline-flex; align-items: center; gap: var(--space-0); } +.fsh-lib-head-tools .fsh-icon-btn { width: var(--ctl-sm); height: var(--ctl-sm); } +.fsh-lib-head-tools .fsh-icon-btn[hidden] { display: none; } +.fsh-lib .fsh-ws-shelf { flex: 1 1 auto; padding: 0 var(--space-1); } +.fsh-lib-body { display: flex; flex-direction: column; flex: 1 1 0; min-height: 0; } +.fsh-lib .fsh-ws-lib-cats { margin: var(--space-2) var(--space-3) 0; } +.fsh-lib .fsh-ws-cat-count { min-width: 4ch; text-align: right; } +.fsh-lib .fsh-ws-cat.is-empty .fsh-ws-cat-name { color: var(--text-faint); } +.fsh-lib-pane { position: relative; display: flex; flex: 1 1 0; min-height: 0; margin-top: var(--space-2); border-top: 1px solid var(--line-0); } +.fsh-lib-busy { position: absolute; top: 0; left: 0; right: 0; z-index: var(--z-raised); height: 2px; background: var(--accent-color); opacity: 0; pointer-events: none; transition: opacity var(--dur-fast) ease; } +.fsh-lib-busy.is-shown { opacity: 0.8; } +.fsh-lib-note { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--space-2); padding: var(--space-4); color: var(--text-muted); font-size: var(--fs-12); text-align: center; pointer-events: none; } +.fsh-lib-note[hidden] { display: none; } +.fsh-lib-note > p { margin: 0; max-width: 28ch; } +.fsh-lib-note > .fsh-icon { color: var(--text-faint); } + +.fsh-lib-grid { position: relative; flex: 1 1 0; min-width: 0; min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; outline: none; contain: strict; } +.fsh-lib-space { position: relative; height: var(--fsh-lib-space-h, 0px); } +.fsh-lib-tile { position: absolute; top: 0; left: 0; width: var(--fsh-lib-tile, 96px); height: calc(var(--fsh-lib-tile, 96px) + 22px); border-radius: var(--radius-md); cursor: pointer; contain: layout paint style; user-select: none; -webkit-user-select: none; touch-action: none; } +.fsh-lib-tile[hidden] { display: none; } +.fsh-lib-thumb { position: relative; width: var(--fsh-lib-tile, 96px); height: var(--fsh-lib-tile, 96px); overflow: hidden; border-radius: var(--radius-md); background: radial-gradient(circle at 38% 32%, var(--surface-3), var(--surface-1) 72%); } +.fsh-lib-thumb::after { content: ''; position: absolute; inset: 0; border-radius: inherit; box-shadow: inset 0 0 0 1px var(--line-1); pointer-events: none; } +.fsh-lib-tile:hover .fsh-lib-thumb::after { box-shadow: inset 0 0 0 1px var(--line-3); } +.fsh-lib-tile[aria-selected="true"] .fsh-lib-thumb::after { box-shadow: inset 0 0 0 2px var(--accent-line); } +.fsh-lib-grid:focus-visible .fsh-lib-tile[aria-selected="true"] .fsh-lib-thumb::after { box-shadow: inset 0 0 0 2px var(--accent-color); } +.fsh-lib-img { display: block; width: 100%; height: 100%; object-fit: cover; opacity: 0; transition: opacity var(--dur) ease; } +.fsh-lib-img:not([src]) { visibility: hidden; } +.fsh-lib-img.is-loaded { opacity: 1; } +.fsh-lib-img.is-instant { transition: none; } +.fsh-lib-badge { position: absolute; left: 4px; bottom: 4px; max-width: calc(100% - 8px); height: 14px; padding: 0 4px; overflow: hidden; border-radius: var(--radius-xs); background: var(--bg-scrim); color: var(--text-primary); font-size: var(--fs-9); line-height: 14px; white-space: nowrap; text-overflow: ellipsis; pointer-events: none; } +.fsh-lib-fav { position: absolute; top: 4px; right: 4px; display: block; color: var(--warn); visibility: hidden; pointer-events: none; } +.fsh-lib-tile.is-favorite .fsh-lib-fav { visibility: visible; } +.fsh-lib-fav > svg { display: block; } +.fsh-lib-name { height: 22px; padding: 0 2px; overflow: hidden; color: var(--text-secondary); font-size: var(--fs-11); line-height: 22px; white-space: nowrap; text-overflow: ellipsis; } +.fsh-lib-tile[aria-selected="true"] .fsh-lib-name { color: var(--text-primary); } + +.fsh-lib-pop { position: fixed; top: 0; left: 0; z-index: var(--z-menu); width: 300px; max-height: min(70vh, 520px); overflow-y: auto; padding: var(--space-3); border-radius: var(--radius-lg); background: var(--surface-2); border: 1px solid var(--glass-border); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); color: var(--text-primary); font-size: var(--fs-12); transform: translate(var(--fsh-lib-pop-x, 0px), var(--fsh-lib-pop-y, 0px)); pointer-events: auto; outline: none; } +.fsh-lib-pop[hidden] { display: none; } +.fsh-lib-pop-head { display: flex; align-items: center; gap: var(--space-2); } +.fsh-lib-pop-swatch { flex: none; width: 28px; height: 28px; border-radius: var(--radius-pill); background: var(--fsh-lib-swatch, transparent); box-shadow: inset 0 0 0 1px var(--line-2); } +.fsh-lib-pop-title { display: flex; flex-direction: column; flex: 1 1 auto; min-width: 0; } +.fsh-lib-pop-name { overflow: hidden; font-size: var(--fs-13); font-weight: var(--fw-semibold); white-space: nowrap; text-overflow: ellipsis; } +.fsh-lib-pop-meta { color: var(--text-muted); font-size: var(--fs-11); } +.fsh-lib-pop-status { margin: var(--space-2) 0 0; color: var(--text-muted); } +.fsh-lib-pop-status[hidden] { display: none; } +.fsh-lib-pop-values { display: grid; grid-template-columns: 1fr auto; gap: var(--space-0) var(--space-3); margin: var(--space-3) 0 0; } +.fsh-lib-pop-row { display: contents; } +.fsh-lib-pop-row > dt { color: var(--text-muted); } +.fsh-lib-pop-row > dd { margin: 0; text-align: right; } +.fsh-lib-pop-tags { display: flex; flex-wrap: wrap; gap: var(--space-1); margin-top: var(--space-3); } +.fsh-lib-pop-tags[hidden] { display: none; } +.fsh-lib-pop-tag { padding: 0 var(--space-2); border-radius: var(--radius-pill); background: var(--surface-3); color: var(--text-secondary); font-size: var(--fs-10); line-height: 18px; } +.fsh-lib-pop-source { margin-top: var(--space-3); padding-top: var(--space-2); border-top: 1px solid var(--line-1); } +.fsh-lib-pop-source[hidden] { display: none; } +.fsh-lib-pop-source > h4 { margin: 0 0 var(--space-1); color: var(--text-muted); font-size: var(--fs-11); font-weight: var(--fw-medium); } +.fsh-lib-pop-source > p { margin: 0 0 var(--space-1); line-height: var(--lh); } +.fsh-lib-pop-kind { color: var(--text-secondary); } +.fsh-lib-pop-notes { color: var(--text-muted); font-size: var(--fs-11); } +.fsh-lib-pop-notes:empty { display: none; } + +.fsh-lib-grid.is-dragging, .fsh-lib-grid.is-dragging .fsh-lib-tile { cursor: grabbing; } +.fsh-lib-ghost { position: fixed; top: 0; left: 0; z-index: var(--z-drag); display: flex; align-items: center; gap: var(--space-2); max-width: 380px; padding: var(--space-1) var(--space-2) var(--space-1) var(--space-1); border-radius: var(--radius-md); background: var(--glass-bg); border: 1px solid var(--glass-border); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); color: var(--text-primary); font-size: var(--fs-11); transform: translate(var(--fsh-lib-ghost-x, 0px), var(--fsh-lib-ghost-y, 0px)); pointer-events: none; will-change: transform; } +.fsh-lib-ghost[hidden] { display: none; } +.fsh-lib-ghost-thumb { flex: none; width: 36px; height: 36px; overflow: hidden; border-radius: var(--radius); background: radial-gradient(circle at 38% 32%, var(--surface-3), var(--surface-1) 72%); } +.fsh-lib-ghost-thumb > img { display: block; width: 100%; height: 100%; object-fit: cover; } +.fsh-lib-ghost-thumb > img:not([src]) { visibility: hidden; } +.fsh-lib-ghost-text { display: flex; flex-direction: column; min-width: 0; } +.fsh-lib-ghost-name { overflow: hidden; font-weight: var(--fw-semibold); white-space: nowrap; text-overflow: ellipsis; } +.fsh-lib-ghost-hint { overflow: hidden; color: var(--text-secondary); white-space: nowrap; text-overflow: ellipsis; } +.fsh-lib-ghost[data-state="part"] .fsh-lib-ghost-hint { color: var(--accent-color); } +.fsh-lib-ghost-keys { color: var(--text-faint); font-size: var(--fs-10); } + +.fsh-lib-save { display: flex; flex-direction: column; gap: var(--space-3); min-width: 300px; } +.fsh-lib-save-row { display: flex; flex-direction: column; gap: var(--space-1); color: var(--text-secondary); font-size: var(--fs-12); } +.fsh-lib-save-error { margin: 0; color: var(--danger-text); } +.fsh-lib-save-error[hidden] { display: none; } + +.fsh-lib-foot { display: flex; flex: none; align-items: center; justify-content: space-between; gap: var(--space-2); height: 32px; padding: 0 var(--space-3); border-top: 1px solid var(--line-0); color: var(--text-muted); font-size: var(--fs-11); } +.fsh-lib-count { flex: 1 1 0; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.fsh-lib-size { display: inline-flex; align-items: center; gap: var(--space-1); color: var(--text-faint); } +.fsh-lib-size > input { width: 72px; margin: 0; accent-color: var(--accent-color); } diff --git a/frontend/src/ui/library/panel.ts b/frontend/src/ui/library/panel.ts new file mode 100644 index 00000000..4f4773cd --- /dev/null +++ b/frontend/src/ui/library/panel.ts @@ -0,0 +1,276 @@ +import './library.css'; +import { el, escapeHtml, pendingClass, q, setAttr, setClass, setDisabled, setHidden, setText } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { CATEGORIES, LIST, SAVE, SHELVES, TYPE_LABEL, parseList, projectMaterials, thumbUrl, type Preset, type Shelf } from './data'; +import { VirtualGrid } from './grid'; +import { TILE_SIZES, loadState, stateSaver, viewKey } from './state'; +import { libraryActions, type LibraryActions, type PanelLink } from './actions'; +import { PresetDrag } from './drag'; +import { SAVE_COMMAND, registerSaveCommand } from './save'; +import { commandEnabled, getCommand, onRegistryChange } from '../../shell/registry'; + +export interface LibraryPanel { + readonly root: HTMLElement; + readonly grid: VirtualGrid; + readonly actions: LibraryActions; + reload(): void; +} + +const EMPTY_NOTE: Record<Shelf, string> = { + all: 'The library is empty', + favorites: 'No favorites yet. Right-click a material to add one.', + recent: 'Materials you apply appear here.', + project: 'This project has no materials yet.', + user: 'Materials you save from the selection appear here.', +}; + +const SEARCH_DELAY_MS = 180; + +export function thumbSize(px: number): number { + return px <= 128 ? 128 : 256; +} + +export function mountLibraryPanel(ws: Workspace, host: HTMLElement): LibraryPanel { + const state = loadState(); + const save = stateSaver(state); + const restoreView = state.view; + let restored = false; + let settled = false; + + const shelves = SHELVES.map(([id, label]) => `<button class="fsh-ws-shelf" type="button" role="tab" data-shelf="${id}" aria-selected="false">${escapeHtml(t(label))}</button>`).join(''); + const cats = CATEGORIES.map((c) => `<li><button class="fsh-ws-cat" type="button" data-cat="${c}" aria-pressed="false"><span class="fsh-ws-cat-name">${escapeHtml(t(c))}</span><span class="fsh-ws-cat-count fsh-tabular" data-no-i18n>0</span></button></li>`).join(''); + const root = el(`<div class="fsh-ws-lib fsh-lib"> +<div class="fsh-ws-lib-head"><span class="fsh-ws-lib-title">${icon('library', 14)}<span>${escapeHtml(t('Library'))}</span></span><span class="fsh-lib-head-tools"><button class="fsh-icon-btn fsh-lib-save-btn" type="button" data-cmd="${SAVE_COMMAND}" title="${escapeHtml(t('Save Selected Material to Library'))}" aria-label="${escapeHtml(t('Save Selected Material to Library'))}" hidden>${icon('plus', 14)}</button></span></div> +<label class="fsh-ws-lib-search">${icon('search', 14)}<input class="fsh-input" type="search" placeholder="${escapeHtml(t('Search materials'))}" aria-label="${escapeHtml(t('Search materials'))}" spellcheck="false" autocomplete="off"></label> +<div class="fsh-ws-lib-shelves" role="tablist" aria-label="${escapeHtml(t('Shelves'))}">${shelves}</div> +<div class="fsh-lib-body"> + <ul class="fsh-ws-lib-cats" aria-label="${escapeHtml(t('Categories'))}">${cats}</ul> + <div class="fsh-lib-pane"> + <div class="fsh-lib-busy" aria-hidden="true"></div> + <div class="fsh-lib-note" role="status" hidden>${icon('material', 28)}<p></p></div> + </div> +</div> +<div class="fsh-lib-foot"><span class="fsh-lib-count fsh-tabular" role="status"></span><label class="fsh-lib-size" title="${escapeHtml(t('Tile size'))}">${icon('grid', 12)}<input type="range" min="0" max="${TILE_SIZES.length - 1}" step="1" aria-label="${escapeHtml(t('Tile size'))}"></label></div> +</div>`); + host.appendChild(root); + + const pane = q(root, '.fsh-lib-pane'); + const busy = q(root, '.fsh-lib-busy'); + const note = q(root, '.fsh-lib-note'); + const noteText = q(note, 'p'); + const count = q(root, '.fsh-lib-count'); + const sizeInput = q<HTMLInputElement>(root, '.fsh-lib-size > input'); + const catButtons = [...root.querySelectorAll<HTMLElement>('.fsh-ws-cat')]; + const catCounts = new Map(catButtons.map((b) => [b.dataset.cat ?? '', q(b, '.fsh-ws-cat-count')])); + + let all: Preset[] = []; + let problem = ''; + let loadSeq = 0; + + let byId = new Map<string, Preset>(); + const byName = new Map<string, Preset>(); + const thumbFor = (item: Preset, size: number): string | null => { + if (item.material === null) return thumbUrl(item, size); + const same = byName.get(`${item.type}|${item.name}`); + return same ? thumbUrl(same, size) : null; + }; + const link: PanelLink = { + find: (id) => byId.get(id), + active: () => grid.active, + reload: () => { void load(); }, + repaint: (id) => grid.refreshItem(id), + rectOf: (id) => grid.rectOf(id), + shelf: () => state.shelf, + }; + const actions = libraryActions(ws, link); + const grid = new VirtualGrid({ + thumb: (item, px) => thumbFor(item, thumbSize(px)), + badge: (item) => t(TYPE_LABEL[item.type] ?? item.type), + activate: (item) => { void actions.apply(item, 'part'); }, + menu: (item, x, y) => actions.menu(item, x, y), + press: (item, e) => drag.press(item, e), + activeChanged: (item) => { if (!restored) return; state.active = item?.id ?? ''; save(); }, + scrolled: (top) => { if (!restored) return; state.scroll = Math.round(top); save(); }, + }, escapeHtml(t('Materials'))); + pane.insertBefore(grid.root, note); + const drag = new PresetDrag(ws.ctx.slots.overlayRoot, grid.root, { + thumb: (item) => thumbFor(item, thumbSize(TILE_SIZES[state.size])), + drop: (item, node, scope) => { void actions.apply(item, scope, [node]); }, + }); + grid.setTileSize(TILE_SIZES[state.size]); + + const paintControls = (): void => { + for (const b of root.querySelectorAll<HTMLElement>('.fsh-ws-shelf')) { + const on = b.dataset.shelf === state.shelf; + setAttr(b, 'aria-selected', on ? 'true' : 'false'); + setAttr(b, 'tabindex', on ? '0' : '-1'); + } + for (const b of catButtons) setAttr(b, 'aria-pressed', b.dataset.cat === state.category ? 'true' : 'false'); + if (sizeInput.value !== String(state.size)) sizeInput.value = String(state.size); + }; + + const show = (): void => { + const counts = new Map<string, number>(CATEGORIES.map((c) => [c, 0])); + for (const p of all) counts.set(p.category, (counts.get(p.category) ?? 0) + 1); + for (const [cat, node] of catCounts) { + const n = counts.get(cat) ?? 0; + setText(node, String(n)); + setClass(node.parentElement, 'is-empty', n === 0); + } + byId = new Map(all.map((p) => [p.id, p])); + const items = state.category ? all.filter((p) => p.category === state.category) : all; + grid.setItems(items, restored ? '' : state.active); + if (!restored && settled) { + if (viewKey(state) === restoreView && items.length) grid.scrollTo(state.scroll); + restored = true; + } + let text = problem; + if (!text && !items.length && state.query.trim()) text = t('No materials match {query}', { query: state.query.trim() }); + if (!text && !items.length) text = state.category && all.length ? t('Nothing in {category} here', { category: t(state.category) }) : t(EMPTY_NOTE[state.shelf]); + setText(noteText, text); + setHidden(note, items.length > 0 && !problem); + setText(count, problem ? '' : items.length === 1 ? t('1 material') : t('{n} materials', { n: items.length })); + }; + + const fetchList = async (): Promise<Preset[]> => { + const args: Record<string, unknown> = {}; + const query = state.query.trim(); + if (query) args.query = query; + if (state.shelf !== 'all') args.shelf = state.shelf; + const list = parseList(await ws.client.dispatch(LIST, args)); + return state.shelf === 'user' ? list.filter((p) => p.user) : list; + }; + + const load = async (): Promise<void> => { + const seq = ++loadSeq; + if (state.shelf === 'project') { + problem = ''; + const words = state.query.trim().toLowerCase().split(/\s+/).filter(Boolean); + all = projectMaterials(ws.client.summary).filter((p) => { + const hay = `${p.name} ${p.category} ${p.type}`.toLowerCase(); + return words.every((w) => hay.includes(w)); + }); + if (ws.client.summary) settled = true; + show(); + return; + } + if (!ws.canRun(LIST)) { + all = []; + problem = ws.why(LIST); + show(); + return; + } + const stop = pendingClass(busy); + try { + const list = await fetchList(); + if (seq !== loadSeq) return; + all = list; + for (const p of list) byName.set(`${p.type}|${p.name}`, p); + problem = ''; + } catch (err) { + if (seq !== loadSeq) return; + all = []; + problem = err instanceof Error ? err.message : String(err); + } finally { + stop(); + } + settled = true; + show(); + }; + + q(root, '.fsh-ws-lib-shelves').addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest<HTMLElement>('.fsh-ws-shelf'); + const next = b?.dataset.shelf as Shelf | undefined; + if (!next || next === state.shelf) return; + state.shelf = next; + state.scroll = 0; + save(); + paintControls(); + grid.scrollTo(0); + void load(); + }); + q(root, '.fsh-ws-lib-shelves').addEventListener('keydown', (e) => { + if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; + const i = SHELVES.findIndex(([id]) => id === state.shelf); + const next = SHELVES[(i + (e.key === 'ArrowRight' ? 1 : SHELVES.length - 1)) % SHELVES.length][0]; + e.preventDefault(); + e.stopPropagation(); + root.querySelector<HTMLElement>(`.fsh-ws-shelf[data-shelf="${next}"]`)?.click(); + root.querySelector<HTMLElement>(`.fsh-ws-shelf[data-shelf="${next}"]`)?.focus(); + }); + q(root, '.fsh-ws-lib-cats').addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest<HTMLElement>('.fsh-ws-cat'); + if (!b?.dataset.cat) return; + state.category = state.category === b.dataset.cat ? '' : b.dataset.cat; + state.scroll = 0; + save(); + paintControls(); + grid.scrollTo(0); + show(); + }); + const search = q<HTMLInputElement>(root, 'input[type="search"]'); + search.value = state.query; + let searchTimer: number | undefined; + const searchNow = (): void => { + window.clearTimeout(searchTimer); + searchTimer = undefined; + if (search.value === state.query) return; + state.query = search.value; + state.scroll = 0; + save(); + grid.scrollTo(0); + void load(); + }; + search.addEventListener('input', () => { + window.clearTimeout(searchTimer); + searchTimer = window.setTimeout(searchNow, SEARCH_DELAY_MS); + }); + search.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && search.value) { search.value = ''; searchNow(); e.stopPropagation(); return; } + if (e.key === 'Enter') { searchNow(); e.preventDefault(); return; } + if (e.key === 'ArrowDown') { searchNow(); grid.focus(); if (!grid.active) grid.setActive(0); e.preventDefault(); } + }); + sizeInput.addEventListener('input', () => { + const n = Math.max(0, Math.min(TILE_SIZES.length - 1, Number(sizeInput.value) | 0)); + if (n === state.size) return; + state.size = n; + save(); + grid.setTileSize(TILE_SIZES[n]); + }); + + let materialsSig = ''; + ws.client.onSummary(() => { + const sig = (ws.client.summary?.materials ?? []).map((m) => `${String(m.key)}:${String(m.name)}:${String(m.type_id)}`).join('|'); + if (sig === materialsSig) return; + materialsSig = sig; + if (state.shelf === 'project') void load(); + }); + const saveBtn = q<HTMLButtonElement>(root, '.fsh-lib-save-btn'); + registerSaveCommand(ws, () => { if (state.shelf === 'user') void load(); }); + const paintSave = (): void => { + setHidden(saveBtn, !ws.client.has(SAVE)); + const cmd = getCommand(SAVE_COMMAND); + setDisabled(saveBtn, !cmd || !commandEnabled(cmd)); + }; + onRegistryChange('state', paintSave); + ws.client.onSummary(paintSave); + ws.client.onCatalogue(paintSave); + paintSave(); + let listed = ws.canRun(LIST); + const catalogue = (): void => { + const has = ws.canRun(LIST); + if (!has && state.shelf !== 'project' && problem !== ws.why(LIST)) { problem = ws.why(LIST); show(); } + if (has === listed) return; + listed = has; + void load(); + }; + ws.client.onCatalogue(catalogue); + ws.client.onState(catalogue); + + paintControls(); + show(); + void load(); + return { root, grid, actions, reload: () => { void load(); } }; +} diff --git a/frontend/src/ui/library/save.ts b/frontend/src/ui/library/save.ts new file mode 100644 index 00000000..69b6efe9 --- /dev/null +++ b/frontend/src/ui/library/save.ts @@ -0,0 +1,79 @@ +import { Dialog } from '../../shell/dialog'; +import { el, escapeHtml, q, setDisabled, setHidden, setText } from '../../shell/dom'; +import { registerCommand } from '../../shell/registry'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { CATEGORIES, SAVE, categoryOfType, partMaterial, selectedParts } from './data'; + +export const SAVE_COMMAND = 'preset.saveSelected'; + +interface Source { key: string; name: string; type: string } + +function selectedMaterial(ws: Workspace): Source | null { + const summary = ws.client.summary; + for (const id of selectedParts(summary)) { + const key = partMaterial(summary, id); + if (key === null) continue; + const m = summary?.materials.find((x) => String(x.key) === key); + return { key, name: typeof m?.name === 'string' ? m.name : key, type: typeof m?.type_id === 'string' ? m.type_id : '' }; + } + return null; +} + +export function registerSaveCommand(ws: Workspace, saved: () => void): void { + registerCommand({ + id: SAVE_COMMAND, + label: 'Save Selected Material to Library', + group: 'Library', + icon: 'plus', + description: 'Keeps the material of the selected part as one of your own presets.', + enabled: () => ws.canRun(SAVE) && selectedMaterial(ws) !== null, + run: () => { + const source = selectedMaterial(ws); + if (!source) { toast('Select a part with a material first', 'error'); return; } + openSaveSheet(ws, source, saved); + }, + }); +} + +function openSaveSheet(ws: Workspace, source: Source, saved: () => void): void { + const d = new Dialog('Save Material to Library'); + const options = CATEGORIES.map((c) => `<option value="${c}">${escapeHtml(t(c))}</option>`).join(''); + const form = el(`<form class="fsh-lib-save"> +<label class="fsh-lib-save-row"><span>${escapeHtml(t('Name'))}</span><input class="fsh-input" name="name" type="text" maxlength="48" spellcheck="false" autocomplete="off" data-no-i18n></label> +<label class="fsh-lib-save-row"><span>${escapeHtml(t('Category'))}</span><select class="fsh-input" name="category">${options}</select></label> +<p class="fsh-note fsh-lib-save-error" role="alert" data-no-i18n hidden></p> +</form>`); + d.body.appendChild(form); + const name = q<HTMLInputElement>(form, 'input[name="name"]'); + const category = q<HTMLSelectElement>(form, 'select[name="category"]'); + const error = q(form, '.fsh-lib-save-error'); + name.value = source.name.slice(0, 48); + category.value = categoryOfType(source.type) || 'Plastic'; + let busy = false; + const submit = async (): Promise<void> => { + if (busy) return; + const label = name.value.trim(); + if (!label) { setText(error, t('Give the material a name')); setHidden(error, false); name.focus(); return; } + busy = true; + setDisabled(ok, true); + try { + await ws.client.dispatch(SAVE, { material: source.key, name: label, category: category.value }); + } catch (err) { + busy = false; + setDisabled(ok, false); + setText(error, err instanceof Error ? err.message : String(err)); + setHidden(error, false); + return; + } + d.close(); + toast(t('Saved {name} to your library', { name: label })); + saved(); + }; + form.addEventListener('submit', (e) => { e.preventDefault(); void submit(); }); + d.action('Cancel', () => d.close()); + const ok = d.action('Save', submit, 'primary'); + d.open(); + name.select(); +} diff --git a/frontend/src/ui/library/state.ts b/frontend/src/ui/library/state.ts new file mode 100644 index 00000000..fe7d0f1f --- /dev/null +++ b/frontend/src/ui/library/state.ts @@ -0,0 +1,62 @@ +import { CATEGORIES, SHELVES, type Shelf } from './data'; + +const KEY = 'formshot.library.panel'; +const OLD_SHELF_KEY = 'formshot.library.shelf'; +const SAVE_DELAY_MS = 250; + +export const TILE_SIZES: readonly number[] = [72, 96, 128]; + +export interface PanelState { + shelf: Shelf; + category: string; + query: string; + size: number; + scroll: number; + view: string; + active: string; +} + +function read(): Record<string, unknown> { + try { + const raw = localStorage.getItem(KEY); + const v: unknown = raw ? JSON.parse(raw) : null; + if (v && typeof v === 'object' && !Array.isArray(v)) return v as Record<string, unknown>; + const old = localStorage.getItem(OLD_SHELF_KEY); + return old ? { shelf: old } : {}; + } catch { + return {}; + } +} + +export function loadState(): PanelState { + const o = read(); + const shelf = SHELVES.some(([id]) => id === o.shelf) ? o.shelf as Shelf : 'all'; + const category = typeof o.category === 'string' && CATEGORIES.includes(o.category) ? o.category : ''; + const size = typeof o.size === 'number' && o.size >= 0 && o.size < TILE_SIZES.length ? Math.floor(o.size) : 1; + return { + shelf, + category, + query: typeof o.query === 'string' ? o.query.slice(0, 200) : '', + size, + scroll: typeof o.scroll === 'number' && o.scroll > 0 ? o.scroll : 0, + view: typeof o.view === 'string' ? o.view : '', + active: typeof o.active === 'string' ? o.active : '', + }; +} + +export function viewKey(s: PanelState): string { + return `${s.shelf}|${s.category}|${s.query.trim().toLowerCase()}|${s.size}`; +} + +export function stateSaver(state: PanelState): () => void { + let timer: number | undefined; + const write = (): void => { + timer = undefined; + try { localStorage.setItem(KEY, JSON.stringify({ ...state, view: viewKey(state) })); } catch { return; } + }; + window.addEventListener('pagehide', () => { if (timer !== undefined) { window.clearTimeout(timer); write(); } }); + return () => { + if (timer !== undefined) return; + timer = window.setTimeout(write, SAVE_DELAY_MS); + }; +} diff --git a/frontend/src/ui/library/thumbs.ts b/frontend/src/ui/library/thumbs.ts new file mode 100644 index 00000000..6ae1c02d --- /dev/null +++ b/frontend/src/ui/library/thumbs.ts @@ -0,0 +1,75 @@ +const CONCURRENCY = 3; +const RETRY_MS = 60000; + +type Done = (ok: boolean) => void; + +interface Job { url: string; waiters: Set<Done>; stop: (() => void) | null; aborted: boolean } + +export class ThumbLoader { + private readonly loaded = new Set<string>(); + private readonly failed = new Map<string, number>(); + private readonly queue: Job[] = []; + private readonly jobs = new Map<string, Job>(); + private running = 0; + + isLoaded(url: string): boolean { return this.loaded.has(url); } + + request(url: string, done: Done): () => void { + if (this.loaded.has(url)) { done(true); return () => undefined; } + const failedAt = this.failed.get(url); + if (failedAt !== undefined && performance.now() - failedAt < RETRY_MS) { done(false); return () => undefined; } + let job = this.jobs.get(url); + if (!job) { + job = { url, waiters: new Set(), stop: null, aborted: false }; + this.jobs.set(url, job); + this.queue.push(job); + } + job.waiters.add(done); + const j = job; + this.pump(); + return () => { + j.waiters.delete(done); + if (j.waiters.size) return; + const i = this.queue.indexOf(j); + if (i >= 0) { this.queue.splice(i, 1); this.jobs.delete(j.url); return; } + if (j.stop) { j.aborted = true; this.jobs.delete(j.url); j.stop(); } + }; + } + + private pump(): void { + while (this.running < CONCURRENCY) { + const job = this.queue.pop(); + if (!job) return; + this.running++; + void this.fetch(job).then((ok) => { + this.running--; + if (this.jobs.get(job.url) === job) this.jobs.delete(job.url); + job.stop = null; + if (!job.aborted) { + if (ok) { this.loaded.add(job.url); this.failed.delete(job.url); } else this.failed.set(job.url, performance.now()); + for (const fn of job.waiters) fn(ok); + } + this.pump(); + }); + } + } + + private fetch(job: Job): Promise<boolean> { + return new Promise((resolve) => { + const img = new Image(); + img.decoding = 'async'; + img.onload = () => { + if (typeof img.decode === 'function') img.decode().then(() => resolve(true), () => resolve(true)); + else resolve(true); + }; + img.onerror = () => resolve(false); + job.stop = () => { + img.onload = null; + img.onerror = null; + img.removeAttribute('src'); + resolve(false); + }; + img.src = job.url; + }); + } +} diff --git a/frontend/src/ui/material/edits.ts b/frontend/src/ui/material/edits.ts new file mode 100644 index 00000000..77da4517 --- /dev/null +++ b/frontend/src/ui/material/edits.ts @@ -0,0 +1,79 @@ +import type { Workspace } from '../context'; +import { CMD, type MaterialStore } from './store'; + +interface Gesture { + name: string; + pending: Record<string, unknown> | null; + inflight: Promise<unknown> | null; + release: () => void; + queued: boolean; +} + +export class Edits { + private readonly open = new Map<string, Gesture>(); + + constructor(private readonly ws: Workspace, private readonly store: MaterialStore) {} + + live(target: string, name: string, args: Record<string, unknown>): void { + const g = this.gesture(target, name); + g.pending = args; + this.queue(g); + } + + async commit(target: string, name: string, args: Record<string, unknown>): Promise<void> { + const g = this.gesture(target, name); + g.pending = args; + this.open.delete(target); + await this.drain(g); + if (this.ws.canRun(CMD.barrier)) await this.ws.run(CMD.barrier, {}); + g.release(); + } + + async once(name: string, args: Record<string, unknown>): Promise<unknown> { + const release = this.store.hold(); + try { + const out = await this.ws.run(name, args); + if (this.ws.canRun(CMD.barrier)) await this.ws.run(CMD.barrier, {}); + return out; + } finally { + release(); + } + } + + active(target: string): boolean { return this.open.has(target); } + + private gesture(target: string, name: string): Gesture { + let g = this.open.get(target); + if (!g) { + g = { name, pending: null, inflight: null, release: this.store.hold(), queued: false }; + this.open.set(target, g); + } + return g; + } + + private queue(g: Gesture): void { + if (g.queued) return; + g.queued = true; + requestAnimationFrame(() => { g.queued = false; this.pump(g); }); + } + + private pump(g: Gesture): void { + if (g.inflight || !g.pending) return; + const args = g.pending; + g.pending = null; + g.inflight = this.ws.run(g.name, args).finally(() => { + g.inflight = null; + if (g.pending) this.queue(g); + }); + } + + private async drain(g: Gesture): Promise<void> { + for (;;) { + if (g.inflight) { await g.inflight; continue; } + if (!g.pending) return; + const args = g.pending; + g.pending = null; + g.inflight = this.ws.run(g.name, args).finally(() => { g.inflight = null; }); + } + } +} diff --git a/frontend/src/ui/material/glyphs.ts b/frontend/src/ui/material/glyphs.ts new file mode 100644 index 00000000..3a72dae9 --- /dev/null +++ b/frontend/src/ui/material/glyphs.ts @@ -0,0 +1,17 @@ +const ATTRS = 'viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"'; + +const PATHS = { + copy: '<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6.5a2 2 0 0 0-2-2h-7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h2"/>', + pencil: '<path d="M4.5 19.5l1-4 10-10a2.1 2.1 0 0 1 3 3l-10 10z"/><path d="M13.5 7.5l3 3"/>', + assign: '<circle cx="9" cy="9" r="4.5"/><path d="M12.5 13.5l7 7"/><path d="M14.5 20.5h5v-5"/>', + graph: '<rect x="3.5" y="4.5" width="6" height="5" rx="1.2"/><rect x="14.5" y="14.5" width="6" height="5" rx="1.2"/><path d="M9.5 7h3a2 2 0 0 1 2 2v8"/>', + texture: '<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 12h16M12 4v16"/><path d="M4 4l8 8"/>', + unlink: '<path d="M9.5 14.5l5-5"/><path d="M7 11l-1.5 1.5a3.5 3.5 0 0 0 5 5L12 16"/><path d="M17 13l1.5-1.5a3.5 3.5 0 0 0-5-5L12 8"/><path d="M4 4l16 16"/>', + bookmark: '<path d="M7 4.5h10a1 1 0 0 1 1 1v14l-6-3.5-6 3.5v-14a1 1 0 0 1 1-1z"/>', +} as const; + +export type MatGlyph = keyof typeof PATHS; + +export function glyph(name: MatGlyph, size = 16): string { + return `<span class="fsh-icon" style="width:${size}px;height:${size}px"><svg ${ATTRS} width="${size}" height="${size}">${PATHS[name]}</svg></span>`; +} diff --git a/frontend/src/ui/material/graph.ts b/frontend/src/ui/material/graph.ts new file mode 100644 index 00000000..0d1c19a5 --- /dev/null +++ b/frontend/src/ui/material/graph.ts @@ -0,0 +1,45 @@ +import { el, q, setDisabled, setText, setTitle } from '../../shell/dom'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { openGraphEditor } from '../graph'; +import { glyph } from './glyphs'; +import type { Section } from './list'; +import { fieldLabel } from './model'; +import type { MaterialStore } from './store'; + +export interface GraphHost { current(): string | null } + +export function mountGraph(host: HTMLElement, ws: Workspace, store: MaterialStore, page: GraphHost): Section { + const root = el(`<div class="fsh-mat-graph"> +<div class="fsh-mat-graph-text"><span class="fsh-mat-graph-state"></span><span class="fsh-mat-graph-drives"></span></div> +<button type="button" class="fsh-btn is-sm fsh-mat-graph-edit">${glyph('graph', 14)}<span>Edit graph</span></button> +</div>`); + host.appendChild(root); + const state = q(root, '.fsh-mat-graph-state'); + const drives = q(root, '.fsh-mat-graph-drives'); + const edit = q<HTMLButtonElement>(root, '.fsh-mat-graph-edit'); + + const update = (): void => { + const key = page.current(); + const row = store.row(key); + const d = store.doc(key); + const type = store.type(d?.typeId ?? row?.typeId ?? ''); + const g = d?.graph ?? null; + setText(state, !row ? '' : !d ? t('Reading the material') : g + ? (g.nodes === 1 ? t('A graph of 1 node') : t('A graph of {n} nodes', { n: g.nodes })) + : type?.needsGraph ? t('No graph. This type looks right only with its graph; reset to type to get it back.') : t('No graph')); + const names = (g?.outputs ?? []).map((o) => t(fieldLabel(o))); + setText(drives, names.length ? t('Drives {inputs}', { inputs: names.join(', ') }) : g ? t('Drives no input yet') : ''); + setDisabled(edit, !row); + setTitle(edit, row ? t('Open the node editor for this material') : ''); + }; + + edit.addEventListener('click', () => { + const key = page.current(); + if (key) openGraphEditor(ws, key); + }); + + update(); + const offs = [store.onChange(update), ws.client.onState(update)]; + return { update, dispose: () => { for (const off of offs) off(); } }; +} diff --git a/frontend/src/ui/material/image.ts b/frontend/src/ui/material/image.ts new file mode 100644 index 00000000..df5d19a0 --- /dev/null +++ b/frontend/src/ui/material/image.ts @@ -0,0 +1,78 @@ +import { api, ApiError } from '../../shell/api'; +import { inTauri } from '../../shell/dom'; +import { t } from '../../i18n'; + +export const IMAGE_EXTS = ['png', 'jpg', 'jpeg', 'hdr', 'exr'] as const; + +export interface ChosenImage { path: string; upload: string | null; name: string } + +async function desktopPick(): Promise<string | null | undefined> { + try { + const { invoke } = await import('@tauri-apps/api/core'); + const picked = await invoke<string | string[] | null>('plugin:dialog|open', { + options: { multiple: false, directory: false, title: t('Choose a texture image'), filters: [{ name: t('Images'), extensions: [...IMAGE_EXTS] }] }, + }); + if (picked === null) return null; + return Array.isArray(picked) ? picked[0] ?? null : picked; + } catch { + return undefined; + } +} + +function browserPick(): Promise<File | null> { + return new Promise((resolve) => { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = IMAGE_EXTS.map((e) => `.${e}`).join(','); + input.hidden = true; + let done = false; + const finish = (f: File | null): void => { if (done) return; done = true; input.remove(); resolve(f); }; + input.addEventListener('change', () => finish(input.files?.[0] ?? null)); + input.addEventListener('cancel', () => finish(null)); + document.body.appendChild(input); + input.click(); + }); +} + +export async function uploadImage(file: File): Promise<ChosenImage> { + const form = new FormData(); + form.append('file', file, file.name); + let res: Response; + try { + res = await fetch(api.url('/api/textures'), { method: 'POST', body: form }); + } catch { + throw new ApiError(t('The FormShot service is not reachable'), 0, 'unreachable'); + } + const body = await res.json().catch(() => ({})) as { path?: unknown; id?: unknown; name?: unknown; detail?: unknown }; + if (!res.ok || typeof body.path !== 'string') { + throw new ApiError(typeof body.detail === 'string' ? body.detail : t('The image could not be uploaded ({status})', { status: res.status }), res.status, ''); + } + return { path: body.path, upload: typeof body.id === 'string' ? body.id : null, name: typeof body.name === 'string' ? body.name : file.name }; +} + +export async function discardUpload(id: string | null): Promise<void> { + if (!id) return; + try { await api.del(`/api/textures/${encodeURIComponent(id)}`); } catch { return; } +} + +export async function chooseImage(onUpload: (busy: boolean) => void): Promise<ChosenImage | null> { + if (inTauri()) { + const path = await desktopPick(); + if (path === null) return null; + if (typeof path === 'string') return { path, upload: null, name: baseName(path) }; + } + const file = await browserPick(); + if (!file) return null; + onUpload(true); + try { + return await uploadImage(file); + } finally { + onUpload(false); + } +} + +export function baseName(path: string): string { + const clean = path.startsWith('fshot:') ? path.slice(6) : path; + const name = clean.split(/[\\/]/).pop() ?? clean; + return name.replace(/^[0-9a-f]{16}-\d+\./, 'embedded.'); +} diff --git a/frontend/src/ui/material/library.ts b/frontend/src/ui/material/library.ts new file mode 100644 index 00000000..69e19aae --- /dev/null +++ b/frontend/src/ui/material/library.ts @@ -0,0 +1,71 @@ +import { Dialog } from '../../shell/dialog'; +import { el, escapeHtml, q, setDisabled, setText, setTitle } from '../../shell/dom'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import { glyph } from './glyphs'; +import type { Section } from './list'; +import { keyArg } from './model'; +import { CMD, type MaterialStore } from './store'; + +export interface LibraryHost { current(): string | null } + +const CATEGORIES = ['Metal', 'Plastic', 'Glass', 'Paint', 'Rubber', 'Fabric', 'Wood', 'Stone', 'Ceramic', 'Liquid', 'Gem', 'Emissive', 'Generic']; + +export function mountLibraryHook(host: HTMLElement, ws: Workspace, store: MaterialStore, page: LibraryHost): Section { + const root = el(`<div class="fsh-mat-lib"> +<button type="button" class="fsh-btn is-sm fsh-mat-lib-save">${glyph('bookmark', 14)}<span>Save to library</span></button> +<span class="fsh-mat-lib-why"></span> +</div>`); + host.appendChild(root); + const save = q<HTMLButtonElement>(root, '.fsh-mat-lib-save'); + const why = q(root, '.fsh-mat-lib-why'); + + const reason = (): string => { + const row = store.row(page.current()); + if (!row) return t('Pick a material first'); + if (ws.client.state !== 'ready') return ws.why(CMD.librarySave); + if (!ws.client.has(CMD.librarySave)) return t('Saving to the library needs an engine with library.save.'); + return ''; + }; + + const update = (): void => { + const r = reason(); + setDisabled(save, r !== ''); + setTitle(save, r || t('Keep this material as a preset in your library')); + setText(why, store.row(page.current()) ? r : ''); + }; + + const open = (): void => { + const key = page.current(); + const row = store.row(key); + if (!key || !row || reason()) return; + const category = store.type(row.typeId)?.category ?? 'Generic'; + const d = new Dialog('Save to library'); + const cats = [...new Set([category, ...CATEGORIES])]; + d.body.appendChild(el(`<div class="fsh-mat-lib-form"> +<label class="fsh-mat-lib-field"><span>Name</span><input class="fsh-input fsh-mat-lib-name" type="text" spellcheck="false" autocomplete="off" data-no-i18n></label> +<label class="fsh-mat-lib-field"><span>Category</span><select class="fsh-input fsh-mat-lib-cat">${cats.map((c) => `<option value="${escapeHtml(c)}">${escapeHtml(t(c))}</option>`).join('')}</select></label> +</div>`)); + const name = q<HTMLInputElement>(d.body, '.fsh-mat-lib-name'); + const cat = q<HTMLSelectElement>(d.body, '.fsh-mat-lib-cat'); + name.value = row.name; + cat.value = category; + const go = async (): Promise<void> => { + const text = name.value.trim(); + if (!text) { name.focus(); return; } + d.close(); + const out = await ws.run(CMD.librarySave, { material: keyArg(key), name: text, category: cat.value }); + if (out !== undefined) toast(t('Saved {name} to your library', { name: text })); + }; + name.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); void go(); } }); + d.action('Cancel', () => d.close()); + d.action('Save', go, 'primary'); + d.open(); + }; + + save.addEventListener('click', open); + update(); + const offs = [store.onChange(update), ws.client.onState(update), ws.client.onCatalogue(update)]; + return { update, dispose: () => { for (const off of offs) off(); } }; +} diff --git a/frontend/src/ui/material/list.ts b/frontend/src/ui/material/list.ts new file mode 100644 index 00000000..7c2ac200 --- /dev/null +++ b/frontend/src/ui/material/list.ts @@ -0,0 +1,261 @@ +import { el, escapeHtml, patchList, q, setAttr, setClass, setDisabled, setHidden, setHtml, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { toast } from '../../shell/toast'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import type { Edits } from './edits'; +import { glyph } from './glyphs'; +import { acescgToHex, isObj, keyArg, type MaterialRow, type MaterialType } from './model'; +import { Popover } from './popover'; +import { CMD, type MaterialStore } from './store'; +import { SWATCH_PX, type Swatches } from './swatch'; + +export interface ListHost { + current(): string | null; + pick(key: string | null): void; + selectionParts(): string[]; + selectionMaterials(): ReadonlySet<string>; +} + +const CATEGORY_ORDER = ['Generic', 'Plastic', 'Metal', 'Paint', 'Glass', 'Liquid', 'Gem', 'Rubber', 'Fabric', 'Ceramic', 'Wood', 'Stone', 'Emissive']; + +export function typeLabel(store: MaterialStore, id: string): string { + return t(store.type(id)?.name ?? id); +} + +function createdKey(reply: unknown): string | null { + const created = isObj(reply) && Array.isArray(reply.created) ? reply.created : []; + const k = created[0]; + return typeof k === 'string' || typeof k === 'number' ? String(k) : null; +} + +export interface Section { update(): void; dispose(): void } + +export function mountList(host: HTMLElement, ws: Workspace, store: MaterialStore, edits: Edits, swatches: Swatches, page: ListHost): Section { + const root = el(`<div class="fsh-mat-list-wrap"> +<div class="fsh-mat-tools" role="toolbar" aria-label="Material actions"> +<button type="button" class="fsh-btn is-sm fsh-mat-new" aria-haspopup="dialog">${icon('plus', 14)}<span>New</span>${icon('chevronDown', 12)}</button> +<span class="fsh-mat-tools-gap"></span> +<button type="button" class="fsh-icon-btn fsh-mat-assign">${glyph('assign')}</button> +<button type="button" class="fsh-icon-btn fsh-mat-dup">${glyph('copy')}</button> +<button type="button" class="fsh-icon-btn fsh-mat-rename">${glyph('pencil')}</button> +<button type="button" class="fsh-icon-btn fsh-mat-delete">${icon('trash', 16)}</button> +</div> +<div class="fsh-mat-list" role="listbox" aria-label="Materials"></div> +<p class="fsh-mat-list-empty" hidden></p> +</div>`); + host.appendChild(root); + const list = q(root, '.fsh-mat-list'); + const empty = q(root, '.fsh-mat-list-empty'); + const newBtn = q<HTMLButtonElement>(root, '.fsh-mat-new'); + const assignBtn = q<HTMLButtonElement>(root, '.fsh-mat-assign'); + const dupBtn = q<HTMLButtonElement>(root, '.fsh-mat-dup'); + const renameBtn = q<HTMLButtonElement>(root, '.fsh-mat-rename'); + const deleteBtn = q<HTMLButtonElement>(root, '.fsh-mat-delete'); + let renaming: string | null = null; + + const picker = new Popover('fsh-mat-types', t('Material types')); + picker.root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest<HTMLButtonElement>('button[data-type]'); + if (!b) return; + picker.close(); + void create(b.dataset.type ?? 'generic', b.dataset.metal ?? null); + }); + + const paintPicker = (): void => { + const groups = new Map<string, MaterialType[]>(); + for (const ty of store.types) { + const list = groups.get(ty.category) ?? []; + list.push(ty); + groups.set(ty.category, list); + } + const cats = [...groups.keys()].sort((a, b) => { + const ia = CATEGORY_ORDER.indexOf(a), ib = CATEGORY_ORDER.indexOf(b); + return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || a.localeCompare(b); + }); + const html = cats.map((cat) => { + const items = (groups.get(cat) ?? []).map((ty) => `<button type="button" class="fsh-mat-type" data-type="${escapeHtml(ty.id)}">${escapeHtml(t(ty.name))}</button>`).join(''); + const metals = cat === 'Metal' && store.metals.length + ? `<div class="fsh-mat-metals" role="group" aria-label="${escapeHtml(t('Measured metals'))}">${store.metals.map((m) => `<button type="button" class="fsh-mat-metal" data-type="metal" data-metal="${escapeHtml(m.id)}"><span class="fsh-mat-metal-chip" style="--fsh-mat-chip:${acescgToHex(m.baseColor)}"></span>${escapeHtml(t(m.name))}</button>`).join('')}</div>` + : ''; + return `<section class="fsh-mat-type-group"><h4>${escapeHtml(t(cat))}</h4><div class="fsh-mat-type-grid">${items}</div>${metals}</section>`; + }).join(''); + setHtml(picker.root, html || `<p class="fsh-mat-pop-empty">${escapeHtml(t('The engine lists no material types yet'))}</p>`, JSON.stringify([store.types.map((x) => x.id), store.metals.map((m) => m.id)])); + }; + + const create = async (typeId: string, metalId: string | null): Promise<void> => { + let args: Record<string, unknown> = { type: typeId }; + const metal = metalId ? store.metals.find((m) => m.id === metalId) : null; + const ty = store.type(typeId); + if (metal && ty) { + args = { material: { name: t(metal.name), type_id: ty.id, params: { ...ty.params, base_color: metal.baseColor }, textures: [], ...(ty.graph ? { graph: ty.graph } : {}) } }; + } else if (ty) args = { type: typeId, name: t(ty.name) }; + const key = createdKey(await edits.once(CMD.create, args)); + if (key) page.pick(key); + }; + + const duplicate = async (): Promise<void> => { + const key = page.current(); + const d = store.doc(key); + if (!key || !d) return; + const material: Record<string, unknown> = { + name: t('{name} copy', { name: d.name }), type_id: d.typeId, params: d.params, textures: d.textures, + }; + if (Object.keys(d.slots).length) material.slots = d.slots; + if (d.graph) material.graph = d.graph.raw; + const made = createdKey(await edits.once(CMD.create, { material })); + if (made) page.pick(made); + }; + + const inUseText = (n: number): string => n === 1 + ? t('In use by 1 part. Assign another material to it first.') + : t('In use by {n} parts. Assign another material to them first.', { n }); + + const remove = async (): Promise<void> => { + const key = page.current(); + const row = store.row(key); + if (!key || !row) return; + if (row.uses > 0) { toast(t('{name} cannot be deleted. {reason}', { name: row.name, reason: inUseText(row.uses) }), 'error'); return; } + const index = store.rows.findIndex((r) => r.key === key); + await edits.once(CMD.remove, { key: keyArg(key) }); + const next = store.rows.filter((r) => r.key !== key)[Math.max(0, index - 1)]; + page.pick(next?.key ?? null); + }; + + const assign = async (): Promise<void> => { + const key = page.current(); + const ids = page.selectionParts(); + if (!key || !ids.length) return; + await edits.once(CMD.assign, { ids: ids.map(keyArg), material: keyArg(key) }); + }; + + const beginRename = (row: HTMLElement): void => { + const r = store.row(row.dataset.key ?? null); + if (!r || !ws.canRun(CMD.rename)) return; + renaming = r.key; + const input = q<HTMLInputElement>(row, '.fsh-mat-rename-input'); + input.value = r.name; + setClass(row, 'is-renaming', true); + setHidden(input, false); + input.focus(); + input.select(); + }; + + const endRename = (row: HTMLElement, commit: boolean): void => { + const input = q<HTMLInputElement>(row, '.fsh-mat-rename-input'); + const r = store.row(row.dataset.key ?? null); + renaming = null; + setHidden(input, true); + setClass(row, 'is-renaming', false); + const name = input.value.trim(); + if (commit && r && name && name !== r.name) { + setText(q(row, '.fsh-mat-row-name'), name); + void edits.once(CMD.rename, { key: keyArg(r.key), name }); + } + }; + + const paintRow = (row: HTMLElement, r: MaterialRow): void => { + const current = page.current() === r.key; + setAttr(row, 'aria-selected', current ? 'true' : 'false'); + setClass(row, 'is-in-selection', page.selectionMaterials().has(r.key)); + if (renaming !== r.key) setText(q(row, '.fsh-mat-row-name'), r.name); + setText(q(row, '.fsh-mat-row-type'), typeLabel(store, r.typeId)); + const count = q(row, '.fsh-mat-row-uses'); + setText(count, r.uses ? String(r.uses) : ''); + setTitle(count, r.uses === 1 ? t('Used by 1 part') : t('Used by {n} parts', { n: r.uses })); + swatches.paint(q<HTMLCanvasElement>(row, 'canvas'), r.key); + }; + + const action = (b: HTMLButtonElement, label: string, ok: boolean, why: string): void => { + setDisabled(b, !ok); + const text = ok || !why ? t(label) : `${t(label)}: ${why}`; + setTitle(b, text); + setAttr(b, 'aria-label', t(label)); + }; + + const update = (): void => { + patchList(list, store.rows, { + key: (r) => r.key, + create: (r) => { + const row = el(`<div class="fsh-mat-row" role="option" tabindex="-1"> +<canvas class="fsh-mat-swatch" width="${SWATCH_PX}" height="${SWATCH_PX}" aria-hidden="true"></canvas> +<span class="fsh-mat-row-text"><span class="fsh-mat-row-name" data-no-i18n></span><span class="fsh-mat-row-type"></span></span> +<input class="fsh-input fsh-mat-rename-input" type="text" spellcheck="false" autocomplete="off" data-no-i18n hidden> +<span class="fsh-mat-row-uses fsh-tabular"></span> +</div>`); + paintRow(row, r); + return row; + }, + update: paintRow, + }); + const s = ws.client.summary; + const msg = ws.client.state !== 'ready' || !s ? '' : store.rows.length ? '' : t('No materials yet. Create one from a type with New.'); + setText(empty, msg); + setHidden(empty, msg === ''); + const key = page.current(); + const row = store.row(key); + const parts = page.selectionParts(); + action(newBtn, 'New material', ws.canRun(CMD.create) && store.types.length > 0, ws.canRun(CMD.create) ? t('Waiting for the material types') : ws.why(CMD.create)); + action(dupBtn, 'Duplicate material', !!row && !!store.doc(key) && ws.canRun(CMD.create), !row ? t('Pick a material first') : ws.why(CMD.create) || t('Waiting for the material settings')); + action(renameBtn, 'Rename material', !!row && ws.canRun(CMD.rename), !row ? t('Pick a material first') : ws.why(CMD.rename)); + const inUse = row ? row.uses : 0; + action(deleteBtn, 'Delete material', !!row && ws.canRun(CMD.remove), !row ? t('Pick a material first') : ws.why(CMD.remove)); + setAttr(deleteBtn, 'aria-disabled', inUse > 0 ? 'true' : null); + if (inUse > 0) setTitle(deleteBtn, `${t('Delete material')}: ${inUseText(inUse)}`); + const assignWhy = !row ? t('Pick a material first') : !ws.canRun(CMD.assign) ? ws.why(CMD.assign) : parts.length ? '' : t('Select parts in the viewport or the scene first'); + action(assignBtn, 'Assign to selection', !!row && parts.length > 0 && ws.canRun(CMD.assign), assignWhy); + if (picker.isOpen) paintPicker(); + }; + + newBtn.addEventListener('click', () => { + if (picker.isOpen) { picker.close(); return; } + paintPicker(); + picker.open(newBtn); + }); + assignBtn.addEventListener('click', () => { void assign(); }); + dupBtn.addEventListener('click', () => { void duplicate(); }); + renameBtn.addEventListener('click', () => { + const row = Array.from(list.children).find((n) => (n as HTMLElement).dataset.key === page.current()) as HTMLElement | undefined; + if (row) beginRename(row); + }); + deleteBtn.addEventListener('click', () => { void remove(); }); + + const rowOf = (target: EventTarget | null): HTMLElement | null => (target as HTMLElement | null)?.closest<HTMLElement>('.fsh-mat-row') ?? null; + list.addEventListener('click', (e) => { + const row = rowOf(e.target); + if (!row || (e.target as HTMLElement).closest('input')) return; + row.focus(); + page.pick(row.dataset.key ?? null); + }); + list.addEventListener('dblclick', (e) => { + const row = rowOf(e.target); + if (row && (e.target as HTMLElement).closest('.fsh-mat-row-name')) beginRename(row); + }); + list.addEventListener('keydown', (e) => { + const row = rowOf(e.target); + if (!row) return; + const input = (e.target as HTMLElement).closest('input'); + if (input) { + if (e.key === 'Enter') { endRename(row, true); row.focus(); } + else if (e.key === 'Escape') { endRename(row, false); row.focus(); } + e.stopPropagation(); + return; + } + if (e.key === 'F2') beginRename(row); + else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + const next = (e.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling) as HTMLElement | null; + if (next) { next.focus(); page.pick(next.dataset.key ?? null); } + } else return; + e.preventDefault(); + e.stopPropagation(); + }); + list.addEventListener('focusout', (e) => { + const input = (e.target as HTMLElement).closest('.fsh-mat-rename-input'); + const row = rowOf(e.target); + if (input && row && renaming === row.dataset.key) endRename(row, true); + }); + + update(); + const offs = [store.onChange(update), ws.client.onState(update), ws.client.onCatalogue(update)]; + return { update, dispose: () => { picker.close(); picker.root.remove(); for (const off of offs) off(); } }; +} diff --git a/frontend/src/ui/material/model.ts b/frontend/src/ui/material/model.ts new file mode 100644 index 00000000..7681326b --- /dev/null +++ b/frontend/src/ui/material/model.ts @@ -0,0 +1,265 @@ +export type Rgb = [number, number, number]; +export type ParamKind = 'float' | 'colour' | 'bool'; + +export interface FieldSpec { + field: string; + kind: ParamKind; + min: number; + max: number; + unit: string; + slot: boolean; +} + +export interface MaterialType { + id: string; + name: string; + category: string; + needsGraph: boolean; + params: Record<string, unknown>; + shown: FieldSpec[]; + graph: unknown; +} + +export interface Metal { id: string; name: string; baseColor: Rgb } + +export interface GraphInfo { nodes: number; outputs: string[]; raw: Record<string, unknown> } + +export interface MaterialDoc { + key: string; + name: string; + typeId: string; + params: Record<string, unknown>; + slots: Record<string, Record<string, unknown>>; + graph: GraphInfo | null; + textures: string[]; +} + +export interface TextureInfo { key: string; path: string; colourSpace: string | null } + +export interface MaterialRow { key: string; name: string; typeId: string; uses: number } + +export const SLOTTABLE = [ + 'base_color', 'specular_roughness', 'base_metalness', 'specular_weight', 'coat_weight', 'coat_roughness', + 'emission_color', 'geometry_opacity', 'normal', 'bump', 'displacement', +] as const; + +export const GEOMETRY_INPUTS = ['normal', 'bump', 'displacement'] as const; +export const COLOUR_INPUTS: ReadonlySet<string> = new Set(['base_color', 'specular_color', 'transmission_color', 'coat_color', 'fuzz_color', 'emission_color']); + +interface FieldInfo { label: string; kind: ParamKind; min: number; max: number; unit?: string } + +const F = (label: string, min = 0, max = 1, unit = ''): FieldInfo => ({ label, kind: 'float', min, max, unit }); +const C = (label: string): FieldInfo => ({ label, kind: 'colour', min: 0, max: 1 }); + +export const FIELDS: Readonly<Record<string, FieldInfo>> = { + base_weight: F('Base weight'), + base_color: C('Base colour'), + base_metalness: F('Metalness'), + base_diffuse_roughness: F('Diffuse roughness'), + specular_weight: F('Specular weight'), + specular_color: C('Specular colour'), + specular_roughness: F('Roughness'), + specular_ior: F('IOR', 1, 4), + specular_roughness_anisotropy: F('Anisotropy'), + transmission_weight: F('Transmission'), + transmission_color: C('Transmission colour'), + transmission_depth: F('Transmission depth', 0, 1, 'm'), + transmission_dispersion_scale: F('Dispersion'), + transmission_dispersion_abbe_number: F('Abbe number', 1, 200), + subsurface_weight: F('Subsurface'), + subsurface_color: C('Subsurface colour'), + subsurface_radius: F('Subsurface radius', 0, 0.1, 'm'), + subsurface_radius_scale: C('Subsurface radius scale'), + coat_weight: F('Coat'), + coat_color: C('Coat colour'), + coat_roughness: F('Coat roughness'), + coat_ior: F('Coat IOR', 1, 3), + coat_darkening: F('Coat darkening'), + fuzz_weight: F('Fuzz'), + fuzz_color: C('Fuzz colour'), + fuzz_roughness: F('Fuzz roughness'), + thin_film_weight: F('Thin film'), + thin_film_thickness: F('Film thickness', 0, 10, 'um'), + thin_film_ior: F('Film IOR', 1, 3), + emission_luminance: F('Emission', 0, 10000, 'nits'), + emission_color: C('Emission colour'), + geometry_opacity: F('Opacity'), + geometry_thin_walled: { label: 'Thin walled', kind: 'bool', min: 0, max: 1 }, + normal: { label: 'Normal', kind: 'float', min: 0, max: 1 }, + bump: { label: 'Bump', kind: 'float', min: 0, max: 1 }, + displacement: { label: 'Displacement', kind: 'float', min: 0, max: 1 }, +}; + +export const FIELD_ORDER: readonly string[] = Object.keys(FIELDS).filter((f) => !(GEOMETRY_INPUTS as readonly string[]).includes(f)); + +export function fieldLabel(field: string): string { + return FIELDS[field]?.label ?? field.replace(/_/g, ' '); +} + +export function unitText(unit: string): string { + return unit === 'um' ? 'µm' : unit; +} + +export function specFor(field: string, type: MaterialType | null): FieldSpec { + const shown = type?.shown.find((s) => s.field === field); + if (shown) return shown; + const info = FIELDS[field]; + return { + field, + kind: info?.kind ?? 'float', + min: info?.min ?? 0, + max: info?.max ?? 1, + unit: info?.unit ?? '', + slot: (SLOTTABLE as readonly string[]).includes(field), + }; +} + +export function stepFor(spec: FieldSpec): number { + const span = Math.max(1e-6, spec.max - spec.min); + const raw = span / 200; + const p = Math.pow(10, Math.floor(Math.log10(raw))); + const n = raw / p; + return +(n < 2 ? p : n < 5 ? 2 * p : 5 * p).toPrecision(6); +} + +export const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v); +const str = (v: unknown, d = ''): string => typeof v === 'string' ? v : typeof v === 'number' ? String(v) : d; +const num = (v: unknown, d = 0): number => typeof v === 'number' && Number.isFinite(v) ? v : d; + +export function rgbOf(v: unknown): Rgb | null { + if (!Array.isArray(v) || v.length < 3) return null; + const out = v.slice(0, 3).map(Number); + return out.every(Number.isFinite) ? [out[0], out[1], out[2]] : null; +} + +function kindOf(v: unknown): ParamKind { + return v === 'colour' || v === 'color' ? 'colour' : v === 'bool' ? 'bool' : 'float'; +} + +export function parseTypes(raw: unknown): { types: MaterialType[]; metals: Metal[] } { + const o = isObj(raw) ? (isObj(raw.result) ? raw.result : raw) : {}; + const types: MaterialType[] = (Array.isArray(o.types) ? o.types : []).filter(isObj).map((t) => ({ + id: str(t.id), + name: str(t.name, str(t.id)), + category: str(t.category, 'Generic'), + needsGraph: t.needs_graph === true, + params: isObj(t.params) ? t.params : {}, + shown: (Array.isArray(t.shown) ? t.shown : []).filter(isObj).map((s) => ({ + field: str(s.field), kind: kindOf(s.kind), min: num(s.min), max: num(s.max, 1), unit: str(s.unit), slot: s.slot === true, + })).filter((s) => s.field !== ''), + graph: t.graph ?? null, + })).filter((t) => t.id !== ''); + const metals: Metal[] = (Array.isArray(o.metals) ? o.metals : []).filter(isObj).map((m) => ({ + id: str(m.id), name: str(m.name, str(m.id)), baseColor: rgbOf(m.base_color) ?? [0.9, 0.9, 0.9], + })).filter((m) => m.id !== ''); + return { types, metals }; +} + +function graphInfo(v: unknown): GraphInfo | null { + if (!isObj(v)) return null; + const nodes = isObj(v.nodes) ? Object.keys(v.nodes).length : Array.isArray(v.nodes) ? v.nodes.length : 0; + const outputs = isObj(v.outputs) ? Object.keys(v.outputs) : []; + return { nodes, outputs, raw: v }; +} + +export function parseMaterial(key: string, raw: unknown): MaterialDoc | null { + if (!isObj(raw)) return null; + const m = isObj(raw.material) ? raw.material : raw; + const slots: Record<string, Record<string, unknown>> = {}; + if (isObj(m.slots)) for (const [k, v] of Object.entries(m.slots)) if (isObj(v)) slots[k] = v; + return { + key, + name: str(m.name, 'Material'), + typeId: str(m.type_id, 'generic'), + params: isObj(m.params) ? { ...m.params } : {}, + slots, + graph: graphInfo(m.graph), + textures: Array.isArray(m.textures) ? m.textures.map((k) => str(k)) : [], + }; +} + +export function parseTextures(raw: unknown): Map<string, TextureInfo> { + const out = new Map<string, TextureInfo>(); + const add = (key: string, v: unknown): void => { + if (!isObj(v)) return; + const path = str(v.path); + if (path) out.set(key, { key, path, colourSpace: typeof v.colour_space === 'string' ? v.colour_space : null }); + }; + if (isObj(raw)) for (const [k, v] of Object.entries(raw)) add(k, v); + else if (Array.isArray(raw)) { + for (const item of raw) { + if (Array.isArray(item) && item.length >= 2) add(str(item[0]), item[1]); + else if (isObj(item)) add(str(item.key), isObj(item.texture) ? item.texture : item); + } + } + return out; +} + +export function signature(m: MaterialDoc): string { + const text = JSON.stringify([m.typeId, m.params, m.slots, m.graph?.raw ?? null]); + let h = 0x811c9dc5; + for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193); + return `${(h >>> 0).toString(36)}.${text.length.toString(36)}`; +} + +export function deepMerge(base: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> { + const out: Record<string, unknown> = { ...base }; + for (const [k, v] of Object.entries(patch)) { + const cur = out[k]; + if (isObj(cur) && isObj(v) && !['kind', 'mode', 'type'].some((t) => t in cur && t in v && cur[t] !== v[t])) out[k] = deepMerge(cur, v); + else out[k] = v; + } + return out; +} + +const TO_SRGB = [ + [1.705051, -0.6217921, -0.08325887], + [-0.13025642, 1.1408047, -0.010548319], + [-0.024003357, -0.12896898, 1.1529723], +]; +const TO_ACESCG = [ + [0.6130974, 0.33952315, 0.04737945], + [0.07019372, 0.9163539, 0.0134524], + [0.020615593, 0.10956977, 0.8698146], +]; + +const mul = (m: number[][], c: Rgb): Rgb => [ + m[0][0] * c[0] + m[0][1] * c[1] + m[0][2] * c[2], + m[1][0] * c[0] + m[1][1] * c[1] + m[1][2] * c[2], + m[2][0] * c[0] + m[2][1] * c[1] + m[2][2] * c[2], +]; +const clamp01 = (x: number): number => Math.min(1, Math.max(0, x)); +const encode = (x: number): number => x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055; +const decode = (x: number): number => x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); + +export const acescgToLinearSrgb = (c: Rgb): Rgb => mul(TO_SRGB, c); + +export function linearToHex(c: Rgb): string { + return '#' + c.map((x) => Math.round(clamp01(encode(clamp01(x))) * 255).toString(16).padStart(2, '0')).join(''); +} + +export function acescgToHex(c: Rgb): string { + return linearToHex(mul(TO_SRGB, c)); +} + +export function hexToAcescg(hex: string): Rgb | null { + const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex.trim()); + if (!m) return null; + const lin: Rgb = [decode(parseInt(m[1], 16) / 255), decode(parseInt(m[2], 16) / 255), decode(parseInt(m[3], 16) / 255)]; + return mul(TO_ACESCG, lin).map((x) => +clamp01(x).toFixed(6)) as Rgb; +} + +export function uses(nodes: ReadonlyArray<{ kind: string; raw: Record<string, unknown> }>): Map<string, number> { + const out = new Map<string, number>(); + for (const n of nodes) { + if (n.kind !== 'part') continue; + const k = n.raw.material; + if (typeof k === 'string' || typeof k === 'number') out.set(String(k), (out.get(String(k)) ?? 0) + 1); + } + return out; +} + +export function keyArg(key: string): number | string { + const n = Number(key); + return Number.isSafeInteger(n) ? n : key; +} diff --git a/frontend/src/ui/material/params.ts b/frontend/src/ui/material/params.ts new file mode 100644 index 00000000..76ccd6d9 --- /dev/null +++ b/frontend/src/ui/material/params.ts @@ -0,0 +1,187 @@ +import { el, escapeHtml, patchList, q, setDisabled, setHidden, setHtml, setText, setTitle, setValue } from '../../shell/dom'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import type { Edits } from './edits'; +import type { Section } from './list'; +import { + acescgToHex, FIELD_ORDER, fieldLabel, hexToAcescg, keyArg, rgbOf, specFor, stepFor, unitText, + type FieldSpec, type MaterialDoc, type MaterialType, +} from './model'; +import { Popover } from './popover'; +import { colourRow, numberRow, toggleRow, type Control } from './rows'; +import { CMD, type MaterialStore } from './store'; + +export interface ParamsHost { + current(): string | null; + slotButton(field: string): HTMLElement | null; +} + +const CATEGORY_ORDER = ['Generic', 'Plastic', 'Metal', 'Paint', 'Glass', 'Liquid', 'Gem', 'Rubber', 'Fabric', 'Ceramic', 'Wood', 'Stone', 'Emissive']; + +interface Row { field: string; root: HTMLElement; update(d: MaterialDoc | null): void } + +export function mountParams(host: HTMLElement, ws: Workspace, store: MaterialStore, edits: Edits, page: ParamsHost): Section { + const root = el(`<div class="fsh-mat-params-wrap"> +<div class="fsh-mat-prow is-select fsh-mat-typerow"><label class="fsh-mat-pctl fsh-mat-selectrow"><span class="fsh-mat-plabel">Type</span><select class="fsh-input fsh-mat-select fsh-mat-type-select"></select></label></div> +<div class="fsh-mat-params"></div> +<p class="fsh-mat-params-note" hidden></p> +<details class="fsh-mat-all"><summary class="fsh-mat-all-head">All parameters</summary><div class="fsh-mat-params fsh-mat-all-list"></div></details> +</div>`); + host.appendChild(root); + const typeSelect = q<HTMLSelectElement>(root, '.fsh-mat-type-select'); + const list = q(root, '.fsh-mat-params'); + const note = q(root, '.fsh-mat-params-note'); + const all = q<HTMLDetailsElement>(root, '.fsh-mat-all'); + const allList = q(root, '.fsh-mat-all-list'); + const allRows: Row[] = []; + let pendingType: string | null = null; + + const choice = new Popover('fsh-mat-typechoice', t('Change the material type')); + choice.root.appendChild(el(`<div class="fsh-mat-choice"> +<p class="fsh-mat-choice-text"></p> +<button type="button" class="fsh-btn is-sm is-primary" data-keep="1">Keep values</button> +<button type="button" class="fsh-btn is-sm" data-keep="0">Reset to type</button> +</div>`)); + choice.root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest<HTMLButtonElement>('button[data-keep]'); + const key = page.current(); + if (!b || !key || !pendingType) return; + const type_id = pendingType; + pendingType = null; + choice.close(); + void edits.once(CMD.setType, { key: keyArg(key), type_id, keep: b.dataset.keep === '1' }); + }); + + const send = (field: string, value: unknown, final: boolean): void => { + const key = page.current(); + if (!key) return; + store.patchParams(key, { [field]: value }); + const args = { key: keyArg(key), values: { [field]: value } }; + const target = `params:${key}`; + if (final) void edits.commit(target, CMD.setParams, args); + else edits.live(target, CMD.setParams, args); + }; + + const makeRow = (field: string, spec: FieldSpec, withSlot: boolean): Row => { + const extra = withSlot ? page.slotButton(field) ?? undefined : undefined; + let control: Control<number> | Control<string> | Control<boolean>; + let paint: (d: MaterialDoc) => void; + if (spec.kind === 'colour') { + const c = colourRow({ + label: fieldLabel(field), + onLive: (hex) => { const v = hexToAcescg(hex); if (v) send(field, v, false); }, + onCommit: (hex) => { const v = hexToAcescg(hex); if (v) send(field, v, true); }, + }, extra); + control = c; + paint = (d) => { const v = rgbOf(d.params[field]); if (v) c.set(acescgToHex(v)); }; + } else if (spec.kind === 'bool') { + const b = toggleRow(fieldLabel(field), (on) => { + const key = page.current(); + if (!key) return; + store.patchParams(key, { [field]: on }); + void edits.once(CMD.setParams, { key: keyArg(key), values: { [field]: on } }); + }, extra); + control = b; + paint = (d) => b.set(d.params[field] === true); + } else { + const n = numberRow({ + label: fieldLabel(field), min: spec.min, max: spec.max, step: stepFor(spec), unit: unitText(spec.unit), + onLive: (v) => send(field, v, false), + onCommit: (v) => send(field, v, true), + }, extra); + control = n; + paint = (d) => { const v = d.params[field]; if (typeof v === 'number') n.set(v); }; + } + control.root.dataset.field = field; + return { + field, + root: control.root, + update: (d) => { + if (d) paint(d); + const driven = !!d?.graph?.outputs.includes(field); + const slot = d?.slots[field]; + const can = ws.canRun(CMD.setParams); + const why = !d ? t('Reading the material') : !can ? ws.why(CMD.setParams) : driven ? t('Driven by the graph. Edit the graph to change it.') : ''; + control.setDisabled(!d || !can || driven, why); + if (driven) control.setTag(t('Graph'), t('Driven by the graph. Edit the graph to change it.')); + else if (slot) control.setTag(slot.multiply === true ? t('Texture ×') : t('Texture'), slot.multiply === true ? t('The texture multiplies this value') : t('A texture drives this value; the value is its fallback')); + else control.setTag(''); + }, + }; + }; + + const shownRows = new Map<string, Row>(); + + const typeOptions = (): void => { + const groups = new Map<string, MaterialType[]>(); + for (const ty of store.types) groups.set(ty.category, [...(groups.get(ty.category) ?? []), ty]); + const cats = [...groups.keys()].sort((a, b) => { + const ia = CATEGORY_ORDER.indexOf(a), ib = CATEGORY_ORDER.indexOf(b); + return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || a.localeCompare(b); + }); + const html = cats.map((c) => `<optgroup label="${escapeHtml(t(c))}">${(groups.get(c) ?? []).map((ty) => `<option value="${escapeHtml(ty.id)}">${escapeHtml(t(ty.name))}</option>`).join('')}</optgroup>`).join(''); + setHtml(typeSelect, html, store.types.map((x) => x.id).join(',')); + }; + + const buildAll = (): void => { + if (allRows.length) return; + for (const field of FIELD_ORDER) { + const row = makeRow(field, specFor(field, null), false); + allRows.push(row); + allList.appendChild(row.root); + } + }; + + const update = (): void => { + typeOptions(); + const key = page.current(); + const row = store.row(key); + const d = store.doc(key); + const typeId = d?.typeId ?? row?.typeId ?? ''; + const type = store.type(typeId); + if (!typeSelect.querySelector(`option[value="${CSS.escape(typeId)}"]`) && typeId) { + typeSelect.appendChild(el(`<option value="${escapeHtml(typeId)}" data-no-i18n>${escapeHtml(typeId)}</option>`)); + } + if (!choice.isOpen) setValue(typeSelect, typeId); + const canType = !!row && ws.canRun(CMD.setType); + setDisabled(typeSelect, !canType); + setTitle(typeSelect, !row ? '' : canType ? '' : ws.why(CMD.setType)); + setHidden(root, !row); + const specs = type?.shown ?? (d ? FIELD_ORDER.slice(0, 6).map((f) => specFor(f, null)) : []); + patchList(list, specs, { + key: (s) => `${s.field}:${s.kind}`, + create: (s) => { + const r = makeRow(s.field, s, s.slot); + shownRows.set(`${s.field}:${s.kind}`, r); + r.update(d); + return r.root; + }, + update: (_node, s) => { shownRows.get(`${s.field}:${s.kind}`)?.update(d); }, + }); + for (const k of [...shownRows.keys()]) if (!specs.some((s) => `${s.field}:${s.kind}` === k)) shownRows.delete(k); + const msg = !row ? '' : !store.types.length ? t('Waiting for the material types') : type ? '' : t('The engine does not know the type {id}; showing the main values.', { id: typeId }); + setText(note, msg); + setHidden(note, msg === ''); + if (all.open) for (const r of allRows) r.update(d); + }; + + typeSelect.addEventListener('change', () => { + const key = page.current(); + const d = store.doc(key); + if (!key) return; + pendingType = typeSelect.value; + const from = store.type(d?.typeId ?? store.row(key)?.typeId ?? ''); + const to = store.type(pendingType); + setText(q(choice.root, '.fsh-mat-choice-text'), t('Change {from} to {to}. Keep the current values, or reset them to the new type?', { from: t(from?.name ?? ''), to: t(to?.name ?? pendingType) })); + choice.open(typeSelect); + }); + all.addEventListener('toggle', () => { if (all.open) { buildAll(); update(); } }); + const closeChoice = new MutationObserver(() => { + if (choice.root.hidden && pendingType !== null) { pendingType = null; update(); } + }); + closeChoice.observe(choice.root, { attributes: true, attributeFilter: ['hidden'] }); + + update(); + const offs = [store.onChange(update), ws.client.onState(update), ws.client.onCatalogue(update)]; + return { update, dispose: () => { closeChoice.disconnect(); choice.root.remove(); for (const off of offs) off(); } }; +} diff --git a/frontend/src/ui/material/popover.ts b/frontend/src/ui/material/popover.ts new file mode 100644 index 00000000..c4ecc123 --- /dev/null +++ b/frontend/src/ui/material/popover.ts @@ -0,0 +1,42 @@ +import { el, setHidden } from '../../shell/dom'; + +export class Popover { + readonly root: HTMLElement; + private anchor: HTMLElement | null = null; + private readonly outside = (e: PointerEvent): void => { + const t = e.target as Node; + if (!this.root.contains(t) && !this.anchor?.contains(t)) this.close(); + }; + + constructor(className: string, label: string) { + this.root = el(`<div class="fsh-mat-pop ${className}" role="dialog" hidden></div>`); + this.root.setAttribute('aria-label', label); + this.root.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { e.stopPropagation(); this.close(); this.anchor?.focus(); } + }); + (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); + } + + get isOpen(): boolean { return !this.root.hidden; } + + open(anchor: HTMLElement): void { + this.anchor = anchor; + setHidden(this.root, false); + const r = anchor.getBoundingClientRect(); + const w = this.root.offsetWidth; + const h = this.root.offsetHeight; + const left = Math.max(8, Math.min(window.innerWidth - w - 8, r.left)); + const below = r.bottom + 4; + const top = below + h > window.innerHeight - 8 ? Math.max(8, r.top - h - 4) : below; + this.root.style.setProperty('--fsh-mat-pop-x', `${Math.round(left)}px`); + this.root.style.setProperty('--fsh-mat-pop-y', `${Math.round(top)}px`); + document.addEventListener('pointerdown', this.outside, true); + this.root.querySelector<HTMLElement>('button:not([disabled])')?.focus(); + } + + close(): void { + if (this.root.hidden) return; + setHidden(this.root, true); + document.removeEventListener('pointerdown', this.outside, true); + } +} diff --git a/frontend/src/ui/material/rows.ts b/frontend/src/ui/material/rows.ts new file mode 100644 index 00000000..b0c7e718 --- /dev/null +++ b/frontend/src/ui/material/rows.ts @@ -0,0 +1,102 @@ +import { el, escapeHtml, q, setAttr, setChecked, setClass, setDisabled, setHidden, setText, setTitle, setValue } from '../../shell/dom'; +import { t } from '../../i18n'; +import { NumberField } from '../number-field'; + +export interface Control<T> { + readonly root: HTMLElement; + set(value: T): void; + setDisabled(disabled: boolean, why?: string): void; + setTag(text: string, why?: string): void; +} + +function tagged(root: HTMLElement): (text: string, why?: string) => void { + const tag = q(root, '.fsh-mat-tag'); + return (text, why = '') => { + setText(tag, text); + setTitle(tag, why); + setHidden(tag, text === ''); + setClass(root, 'is-tagged', text !== ''); + }; +} + +export interface NumberOptions { + label: string; + min?: number; + max?: number; + step: number; + unit?: string; + integer?: boolean; + onLive: (v: number) => void; + onCommit: (v: number) => void; +} + +export function numberRow(o: NumberOptions, extra?: HTMLElement): Control<number> { + const root = el('<div class="fsh-mat-prow is-number"><div class="fsh-mat-pctl"></div><span class="fsh-mat-tag" hidden></span><span class="fsh-mat-pextra"></span></div>'); + const field = new NumberField({ + label: o.label, min: o.min, max: o.max, step: o.step, unit: o.unit, integer: o.integer, + onInput: o.onLive, onCommit: o.onCommit, + }); + q(root, '.fsh-mat-pctl').appendChild(field.root); + if (extra) q(root, '.fsh-mat-pextra').appendChild(extra); + return { + root, + set: (v) => field.set(v), + setDisabled: (d, why = '') => { field.setDisabled(d, why); setClass(root, 'is-disabled', d); }, + setTag: tagged(root), + }; +} + +export interface ColourOptions { + label: string; + onLive: (hex: string) => void; + onCommit: (hex: string) => void; +} + +export function colourRow(o: ColourOptions, extra?: HTMLElement): Control<string> { + const root = el(`<div class="fsh-mat-prow is-colour"><label class="fsh-mat-pctl fsh-mat-colour"><span class="fsh-mat-plabel">${escapeHtml(t(o.label))}</span><span class="fsh-mat-hex fsh-tabular" data-no-i18n></span><input class="fsh-mat-colour-input" type="color"></label><span class="fsh-mat-tag" hidden></span><span class="fsh-mat-pextra"></span></div>`); + const input = q<HTMLInputElement>(root, 'input'); + const hex = q(root, '.fsh-mat-hex'); + let editing = false; + input.addEventListener('input', () => { editing = true; setText(hex, input.value.toUpperCase()); o.onLive(input.value); }); + input.addEventListener('change', () => { editing = false; setText(hex, input.value.toUpperCase()); o.onCommit(input.value); }); + input.addEventListener('blur', () => { editing = false; }); + if (extra) q(root, '.fsh-mat-pextra').appendChild(extra); + return { + root, + set: (v) => { + if (editing) return; + if (input.value !== v) input.value = v; + setText(hex, v.toUpperCase()); + }, + setDisabled: (d, why = '') => { setDisabled(input, d); setTitle(input, why); setClass(root, 'is-disabled', d); }, + setTag: tagged(root), + }; +} + +export function toggleRow(label: string, onChange: (on: boolean) => void, extra?: HTMLElement): Control<boolean> { + const root = el(`<div class="fsh-mat-prow is-toggle"><label class="fsh-mat-pctl fsh-mat-toggle"><span class="fsh-mat-plabel">${escapeHtml(t(label))}</span><input type="checkbox" role="switch"></label><span class="fsh-mat-tag" hidden></span><span class="fsh-mat-pextra"></span></div>`); + const input = q<HTMLInputElement>(root, 'input'); + input.addEventListener('change', () => onChange(input.checked)); + if (extra) q(root, '.fsh-mat-pextra').appendChild(extra); + return { + root, + set: (v) => setChecked(input, v), + setDisabled: (d, why = '') => { setDisabled(input, d); setTitle(input, why); setClass(root, 'is-disabled', d); }, + setTag: tagged(root), + }; +} + +export function selectRow(label: string, options: ReadonlyArray<readonly [string, string]>, onChange: (v: string) => void): Control<string> { + const opts = options.map(([v, l]) => `<option value="${escapeHtml(v)}">${escapeHtml(t(l))}</option>`).join(''); + const root = el(`<div class="fsh-mat-prow is-select"><label class="fsh-mat-pctl fsh-mat-selectrow"><span class="fsh-mat-plabel">${escapeHtml(t(label))}</span><select class="fsh-input fsh-mat-select">${opts}</select></label><span class="fsh-mat-tag" hidden></span><span class="fsh-mat-pextra"></span></div>`); + const select = q<HTMLSelectElement>(root, 'select'); + select.addEventListener('change', () => onChange(select.value)); + return { + root, + set: (v) => setValue(select, v), + setDisabled: (d, why = '') => { setDisabled(select, d); setTitle(select, why); setClass(root, 'is-disabled', d); }, + setTag: tagged(root), + }; +} + +export function setAria(node: HTMLElement, label: string): void { setAttr(node, 'aria-label', label); } diff --git a/frontend/src/ui/material/slots.ts b/frontend/src/ui/material/slots.ts new file mode 100644 index 00000000..26153050 --- /dev/null +++ b/frontend/src/ui/material/slots.ts @@ -0,0 +1,284 @@ +import { el, escapeHtml, patchList, pendingClass, q, setAttr, setClass, setDisabled, setHidden, setHtml, setText, setTitle } from '../../shell/dom'; +import { icon } from '../../shell/icons'; +import { toastError } from '../../shell/toast'; +import { t } from '../../i18n'; +import type { Workspace } from '../context'; +import type { Edits } from './edits'; +import { glyph } from './glyphs'; +import { baseName, chooseImage, discardUpload } from './image'; +import type { Section } from './list'; +import { COLOUR_INPUTS, fieldLabel, isObj, keyArg, SLOTTABLE, type MaterialDoc } from './model'; +import { colourRow, numberRow, selectRow, toggleRow, type Control } from './rows'; +import { CMD, type MaterialStore } from './store'; + +export interface SlotsHost { current(): string | null } + +type Slot = Record<string, unknown>; + +const PROJECTIONS = [['uv', 'UV set'], ['box', 'Box'], ['planar', 'Planar'], ['cylindrical', 'Cylindrical'], ['spherical', 'Spherical']] as const; +const SPACES = [['object', 'Object space'], ['world', 'World space']] as const; +const WRAPS = [['repeat', 'Repeat'], ['clamp', 'Clamp'], ['mirror', 'Mirror']] as const; +const FILTERS = [['trilinear', 'Trilinear'], ['bilinear', 'Bilinear'], ['nearest', 'Nearest']] as const; +const SPACES_COLOUR = [['auto', 'Automatic'], ['srgb', 'sRGB'], ['linear', 'Linear sRGB'], ['acescg', 'ACEScg'], ['data', 'Data (raw)']] as const; +const CHANNELS = [['rgb', 'RGB'], ['r', 'Red'], ['g', 'Green'], ['b', 'Blue'], ['a', 'Alpha'], ['luminance', 'Luminance']] as const; +const FALLBACKS = [['auto', 'Automatic'], ['custom', 'Custom colour']] as const; + +const n = (v: unknown, d: number): number => typeof v === 'number' && Number.isFinite(v) ? v : d; +const pair = (v: unknown, d: [number, number]): [number, number] => Array.isArray(v) && v.length >= 2 ? [n(v[0], d[0]), n(v[1], d[1])] : d; +const RAD = Math.PI / 180; + +function hexOf(c: unknown): string { + const a = Array.isArray(c) ? c : [0, 0, 0]; + return '#' + [0, 1, 2].map((i) => Math.round(Math.min(1, Math.max(0, n(a[i], 0))) * 255).toString(16).padStart(2, '0')).join(''); +} + +function rgbaOf(hex: string, alpha: number): [number, number, number, number] { + const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex) ?? ['', '00', '00', '00']; + return [parseInt(m[1], 16) / 255, parseInt(m[2], 16) / 255, parseInt(m[3], 16) / 255, alpha]; +} + +interface Editor { input: string; root: HTMLElement; update(d: MaterialDoc): void; setOpen(open: boolean): void } + +export interface SlotsSection extends Section { + button(field: string): HTMLElement; + open(input: string): void; +} + +export function mountSlots(host: HTMLElement, ws: Workspace, store: MaterialStore, edits: Edits, page: SlotsHost): SlotsSection { + const root = el(`<div class="fsh-mat-slots"> +<div class="fsh-mat-slot-list"></div> +<p class="fsh-mat-slots-empty">No textures. Use the texture button beside a value, or add a map here.</p> +<div class="fsh-mat-prow is-select fsh-mat-addmap"><label class="fsh-mat-pctl fsh-mat-selectrow"><span class="fsh-mat-plabel">Add a map</span><select class="fsh-input fsh-mat-select"></select></label></div> +</div>`); + host.appendChild(root); + const list = q(root, '.fsh-mat-slot-list'); + const empty = q(root, '.fsh-mat-slots-empty'); + const add = q<HTMLSelectElement>(root, '.fsh-mat-addmap select'); + const buttons = new Map<string, Set<HTMLButtonElement>>(); + const editors = new Map<string, Editor>(); + const opened = new Set<string>(); + + const send = (input: string, slot: Slot, final: boolean): void => { + const key = page.current(); + if (!key) return; + store.patchSlot(key, input, slot); + const args = { key: keyArg(key), input, slot }; + const target = `slot:${key}:${input}`; + if (final) void edits.commit(target, CMD.setSlot, args); + else edits.live(target, CMD.setSlot, args); + }; + + const pick = async (input: string, busyNode: HTMLElement): Promise<void> => { + const key = page.current(); + if (!key || !ws.canRun(CMD.setSlot)) return; + let stop: (() => void) | null = null; + let image; + try { + image = await chooseImage((busy) => { + if (busy) stop = pendingClass(busyNode); + else { stop?.(); stop = null; } + }); + } catch (err) { + toastError(err); + return; + } + if (!image) return; + const reply = await edits.once(CMD.setSlot, { key: keyArg(key), input, slot: {}, path: image.path }); + if (reply === undefined) { void discardUpload(image.upload); return; } + opened.add(input); + update(); + }; + + const clear = (input: string): void => { + const key = page.current(); + if (!key) return; + store.patchSlot(key, input, null); + opened.delete(input); + void edits.once(CMD.clearSlot, { key: keyArg(key), input }); + }; + + const makeEditor = (input: string): Editor => { + const colour = COLOUR_INPUTS.has(input); + const geometry = input === 'normal' || input === 'bump' || input === 'displacement'; + const node = el(`<div class="fsh-mat-slot" data-input="${escapeHtml(input)}"> +<div class="fsh-mat-slot-head"> +<button type="button" class="fsh-mat-slot-toggle" aria-expanded="false">${icon('chevronRight', 12)}<span class="fsh-mat-slot-input"></span><span class="fsh-mat-slot-file" data-no-i18n></span></button> +<button type="button" class="fsh-icon-btn fsh-mat-slot-replace">${glyph('texture')}</button> +<button type="button" class="fsh-icon-btn fsh-mat-slot-clear">${glyph('unlink')}</button> +</div> +<div class="fsh-mat-slot-body" hidden></div> +</div>`); + setText(q(node, '.fsh-mat-slot-input'), t(fieldLabel(input))); + const replace = q<HTMLButtonElement>(node, '.fsh-mat-slot-replace'); + const clearBtn = q<HTMLButtonElement>(node, '.fsh-mat-slot-clear'); + setTitle(replace, t('Replace the image')); + setAttr(replace, 'aria-label', t('Replace the image')); + setTitle(clearBtn, t('Clear the texture slot')); + setAttr(clearBtn, 'aria-label', t('Clear the texture slot')); + replace.addEventListener('click', () => { void pick(input, replace); }); + clearBtn.addEventListener('click', () => clear(input)); + const toggle = q<HTMLButtonElement>(node, '.fsh-mat-slot-toggle'); + const body = q(node, '.fsh-mat-slot-body'); + toggle.addEventListener('click', () => { + if (opened.has(input)) opened.delete(input); else opened.add(input); + setOpen(opened.has(input)); + }); + + let cur: Slot = {}; + const get = (): Slot => cur; + const proj = (): Slot => isObj(get().projection) ? get().projection as Slot : { kind: 'uv', set: 0 }; + const xf = (): Slot => isObj(get().transform) ? get().transform as Slot : {}; + + const controls: Array<{ c: Control<never> | Control<number> | Control<string> | Control<boolean>; paint: () => void; show?: () => boolean }> = []; + const addRow = <T>(c: Control<T>, paint: (c: Control<T>) => void, show?: () => boolean): void => { + body.appendChild(c.root); + controls.push({ c: c as unknown as Control<never>, paint: () => paint(c), show }); + }; + + addRow(selectRow('Projection', PROJECTIONS, (v) => { + const p = v === 'uv' ? { kind: 'uv', set: n(proj().set, 0) } : v === 'box' ? { kind: 'box', blend: n(proj().blend, 0.5) } : { kind: v }; + send(input, { projection: p }, true); + }), (c) => c.set(String(proj().kind ?? 'uv'))); + addRow(numberRow({ label: 'UV set', min: 0, max: 3, step: 1, integer: true, onLive: (v) => send(input, { projection: { kind: 'uv', set: v } }, false), onCommit: (v) => send(input, { projection: { kind: 'uv', set: v } }, true) }), + (c) => c.set(n(proj().set, 0)), () => proj().kind === 'uv'); + addRow(numberRow({ label: 'Blend', min: 0, max: 1, step: 0.01, onLive: (v) => send(input, { projection: { kind: 'box', blend: v } }, false), onCommit: (v) => send(input, { projection: { kind: 'box', blend: v } }, true) }), + (c) => c.set(n(proj().blend, 0.5)), () => proj().kind === 'box'); + addRow(selectRow('Space', SPACES, (v) => send(input, { transform: { space: v } }, true)), + (c) => c.set(String(xf().space ?? 'object')), () => proj().kind !== 'uv'); + const vec = (field: 'offset' | 'scale', i: 0 | 1, label: string, d: [number, number]): void => { + const value = (v: number): Slot => { const p = pair(xf()[field], d); p[i] = v; return { transform: { [field]: p } }; }; + addRow(numberRow({ label, step: 0.01, onLive: (v) => send(input, value(v), false), onCommit: (v) => send(input, value(v), true) }), + (c) => c.set(pair(xf()[field], d)[i])); + }; + vec('offset', 0, 'Offset U', [0, 0]); + vec('offset', 1, 'Offset V', [0, 0]); + vec('scale', 0, 'Scale U', [1, 1]); + vec('scale', 1, 'Scale V', [1, 1]); + addRow(numberRow({ label: 'Rotation', min: -180, max: 180, step: 1, unit: '°', onLive: (v) => send(input, { transform: { rotation: v * RAD } }, false), onCommit: (v) => send(input, { transform: { rotation: v * RAD } }, true) }), + (c) => c.set(Math.round(n(xf().rotation, 0) / RAD * 100) / 100)); + addRow(selectRow('Wrap', WRAPS, (v) => send(input, { wrap: v }, true)), (c) => c.set(String(get().wrap ?? 'repeat'))); + addRow(selectRow('Filter', FILTERS, (v) => send(input, { filter: v }, true)), (c) => c.set(String(get().filter ?? 'trilinear'))); + addRow(selectRow('Colour space', SPACES_COLOUR, (v) => send(input, { colour_space: v === 'auto' ? null : v }, true)), + (c) => c.set(typeof get().colour_space === 'string' ? String(get().colour_space) : 'auto')); + addRow(selectRow('Channel', CHANNELS, (v) => send(input, { channel: v }, true)), (c) => c.set(String(get().channel ?? 'rgb'))); + if (!colour && !geometry) { + const range = (i: 0 | 1, label: string): void => { + const value = (v: number): Slot => { const r = pair(get().range, [0, 1]); r[i] = v; return { range: r }; }; + addRow(numberRow({ label, step: 0.01, onLive: (v) => send(input, value(v), false), onCommit: (v) => send(input, value(v), true) }), + (c) => c.set(pair(get().range, [0, 1])[i])); + }; + range(0, 'Range from'); + range(1, 'Range to'); + addRow(toggleRow('Invert', (on) => send(input, { invert: on }, true)), (c) => c.set(get().invert === true)); + } + if (!geometry) addRow(toggleRow('Multiply by the value', (on) => send(input, { multiply: on }, true)), (c) => c.set(get().multiply === true)); + if (geometry) { + const unit = input === 'normal' ? '' : 'm'; + const step = input === 'normal' ? 0.01 : 0.0001; + addRow(numberRow({ label: 'Strength', min: 0, max: input === 'normal' ? 4 : input === 'bump' ? 0.01 : 0.1, step, unit, onLive: (v) => send(input, { strength: v }, false), onCommit: (v) => send(input, { strength: v }, true) }), + (c) => c.set(n(get().strength, input === 'normal' ? 1 : input === 'bump' ? 0.001 : 0.01))); + } + if (input === 'normal') addRow(toggleRow('Flip green (DirectX)', (on) => send(input, { flip_y: on }, true)), (c) => c.set(get().flip_y === true)); + addRow(selectRow('Fallback', FALLBACKS, (v) => send(input, { fallback: v === 'auto' ? null : rgbaOf(hexOf(get().fallback), 1) }, true)), + (c) => c.set(Array.isArray(get().fallback) ? 'custom' : 'auto')); + addRow(colourRow({ label: 'Fallback colour', onLive: (hex) => send(input, { fallback: rgbaOf(hex, 1) }, false), onCommit: (hex) => send(input, { fallback: rgbaOf(hex, 1) }, true) }), + (c) => c.set(hexOf(get().fallback)), () => Array.isArray(get().fallback)); + + const setOpen = (open: boolean): void => { + setHidden(body, !open); + setAttr(toggle, 'aria-expanded', open ? 'true' : 'false'); + setClass(node, 'is-open', open); + }; + + return { + input, + root: node, + setOpen, + update: (d) => { + cur = d.slots[input] ?? {}; + const tex = store.textures.get(String(cur.texture ?? '')); + const file = tex ? baseName(tex.path) : t('Texture {key}', { key: String(cur.texture ?? '') }); + setText(q(node, '.fsh-mat-slot-file'), file); + setTitle(toggle, tex?.path ?? ''); + const can = ws.canRun(CMD.setSlot); + const driven = !!d.graph?.outputs.includes(input); + setDisabled(replace, !can); + setDisabled(clearBtn, !ws.canRun(CMD.clearSlot)); + setClass(node, 'is-driven', driven); + for (const x of controls) { + x.paint(); + x.c.setDisabled(!can, can ? '' : ws.why(CMD.setSlot)); + if (x.show) setHidden(x.c.root, !x.show()); + } + setOpen(opened.has(input)); + }, + }; + }; + + const update = (): void => { + const key = page.current(); + const d = store.doc(key); + const inputs = d ? Object.keys(d.slots) : []; + setHidden(root, !store.row(key)); + patchList(list, inputs, { + key: (i) => i, + create: (i) => { + const ed = makeEditor(i); + editors.set(i, ed); + if (d) ed.update(d); + return ed.root; + }, + update: (_node, i) => { if (d) editors.get(i)?.update(d); }, + }); + for (const k of [...editors.keys()]) if (!inputs.includes(k)) editors.delete(k); + setHidden(empty, inputs.length > 0); + const free = (SLOTTABLE as readonly string[]).filter((i) => !inputs.includes(i)); + const opts = `<option value="">${escapeHtml(t('Choose an input'))}</option>` + free.map((i) => `<option value="${i}">${escapeHtml(t(fieldLabel(i)))}</option>`).join(''); + setHtml(add, opts, free.join(',')); + const can = !!d && ws.canRun(CMD.setSlot); + setDisabled(add, !can || !free.length); + setTitle(add, !d ? t('Reading the material') : ws.canRun(CMD.setSlot) ? '' : ws.why(CMD.setSlot)); + for (const [field, set] of buttons) { + for (const b of [...set]) { + if (!b.isConnected) { set.delete(b); continue; } + const has = !!d?.slots[field]; + const label = has ? t('Edit the texture of {input}', { input: t(fieldLabel(field)) }) : t('Drive {input} with a texture', { input: t(fieldLabel(field)) }); + setAttr(b, 'aria-pressed', has ? 'true' : 'false'); + setTitle(b, can ? label : !d ? t('Reading the material') : ws.why(CMD.setSlot)); + setAttr(b, 'aria-label', label); + setDisabled(b, !can); + } + } + }; + + add.addEventListener('change', () => { + const input = add.value; + add.value = ''; + if (input) void pick(input, add.closest('.fsh-mat-addmap') as HTMLElement); + }); + + const open = (input: string): void => { + opened.add(input); + const ed = editors.get(input); + if (!ed) return; + ed.setOpen(true); + ed.root.scrollIntoView({ block: 'nearest' }); + }; + + const button = (field: string): HTMLElement => { + const b = el<HTMLButtonElement>(`<button type="button" class="fsh-icon-btn fsh-mat-slotbtn" aria-pressed="false">${glyph('texture', 14)}</button>`); + b.addEventListener('click', () => { + const d = store.doc(page.current()); + if (d?.slots[field]) open(field); + else void pick(field, b); + }); + let set = buttons.get(field); + if (!set) { set = new Set(); buttons.set(field, set); } + set.add(b); + return b; + }; + + update(); + const offs = [store.onChange(update), ws.client.onState(update), ws.client.onCatalogue(update)]; + return { update, button, open, dispose: () => { for (const off of offs) off(); } }; +} diff --git a/frontend/src/ui/material/store.ts b/frontend/src/ui/material/store.ts new file mode 100644 index 00000000..e9734975 --- /dev/null +++ b/frontend/src/ui/material/store.ts @@ -0,0 +1,212 @@ +import type { Workspace } from '../context'; +import { + deepMerge, parseMaterial, parseTextures, parseTypes, signature, uses, + type MaterialDoc, type MaterialRow, type MaterialType, type Metal, type TextureInfo, +} from './model'; + +export const CMD = { + types: 'material.types', + get: 'material.get', + create: 'material.create', + rename: 'material.rename', + remove: 'material.remove', + assign: 'material.assign', + setParams: 'material.set_params', + setType: 'material.set_type', + setSlot: 'material.set_slot', + clearSlot: 'material.clear_slot', + setGraph: 'material.set_graph', + preview: 'material.preview_maps', + barrier: 'history.barrier', + librarySave: 'library.save', +} as const; + +const QUIET = /^(scene\.(summary|meshes|mesh_data)|render\.|view\.|camera\.|selection\.|app\.|history\.(barrier|begin_group)|file\.(snapshot|export_image|export_model|save|recover_list)|material\.(types|node_kinds|program|preview_maps|get)|import\.(probe|status))/; +const CHANGE_EVENTS = ['scene.changed', 'document.changed', 'history.changed', 'hello', 'resync', 'ui.workspace.loaded']; +const READ_DELAY_MS = 90; + +export class MaterialStore { + types: MaterialType[] = []; + metals: Metal[] = []; + rows: MaterialRow[] = []; + textures = new Map<string, TextureInfo>(); + error = ''; + private docs = new Map<string, MaterialDoc>(); + private sigs = new Map<string, string>(); + private fns = new Set<() => void>(); + private holds = 0; + private epoch = 0; + private stale = true; + private visible = false; + private reading = false; + private again = false; + private timer: number | undefined; + private typesFor: unknown = null; + private rowsKey = ''; + + constructor(private readonly ws: Workspace) { + const { client, ctx } = ws; + client.onSummary(() => this.summaryChanged()); + client.onCatalogue(() => { void this.loadTypes(); this.markStale(); }); + client.onState(() => { if (client.state === 'ready') { void this.loadTypes(); this.markStale(); } }); + client.onDispatch((n) => { + if (QUIET.test(n.name) || client.entry(n.name)?.mutates === false) return; + this.markStale(); + }); + for (const type of CHANGE_EVENTS) ctx.events.on(type, () => this.markStale()); + void this.loadTypes(); + this.summaryChanged(); + } + + onChange(fn: () => void): () => void { this.fns.add(fn); return () => { this.fns.delete(fn); }; } + + type(id: string): MaterialType | null { return this.types.find((t) => t.id === id) ?? null; } + doc(key: string | null): MaterialDoc | null { return key === null ? null : this.docs.get(key) ?? null; } + sig(key: string): string { return this.sigs.get(key) ?? ''; } + row(key: string | null): MaterialRow | null { return this.rows.find((r) => r.key === key) ?? null; } + hasDocs(): boolean { return this.docs.size > 0 || this.rows.length === 0; } + + setVisible(on: boolean): void { + this.visible = on; + if (on && this.stale) this.schedule(); + } + + markStale(): void { + this.stale = true; + this.schedule(); + } + + hold(): () => void { + this.holds++; + this.epoch++; + let released = false; + return () => { + if (released) return; + released = true; + this.holds--; + this.markStale(); + }; + } + + patchParams(key: string, values: Record<string, unknown>): void { + const d = this.docs.get(key); + if (!d) return; + this.epoch++; + d.params = { ...d.params, ...values }; + this.commit(d); + } + + patchSlot(key: string, input: string, slot: Record<string, unknown> | null): void { + const d = this.docs.get(key); + if (!d) return; + this.epoch++; + const next = { ...d.slots }; + if (slot === null) delete next[input]; + else next[input] = deepMerge(next[input] ?? {}, slot); + d.slots = next; + this.commit(d); + } + + private commit(d: MaterialDoc): void { + this.sigs.set(d.key, signature(d)); + this.emit(); + } + + private emit(): void { for (const fn of this.fns) fn(); } + + private summaryChanged(): void { + const s = this.ws.client.summary; + const counts = uses(s?.nodes ?? []); + const rows: MaterialRow[] = (s?.materials ?? []).map((m) => { + const key = String(m.key ?? ''); + return { key, name: typeof m.name === 'string' ? m.name : key, typeId: typeof m.type_id === 'string' ? m.type_id : 'generic', uses: counts.get(key) ?? 0 }; + }).filter((r) => r.key !== ''); + const rowsKey = JSON.stringify(rows); + if (rowsKey === this.rowsKey) { this.emit(); return; } + const keysBefore = this.rows.map((r) => r.key).join(','); + this.rowsKey = rowsKey; + this.rows = rows; + for (const r of rows) { + const d = this.docs.get(r.key); + if (d && (d.name !== r.name || d.typeId !== r.typeId)) this.stale = true; + } + if (keysBefore !== rows.map((r) => r.key).join(',')) this.stale = true; + this.emit(); + if (this.stale) this.schedule(); + } + + private async loadTypes(): Promise<void> { + const { client } = this.ws; + if (client.state !== 'ready' || !client.has(CMD.types)) return; + const token = client.entry(CMD.types); + if (token === this.typesFor && this.types.length) return; + this.typesFor = token; + try { + const parsed = parseTypes(await client.dispatch(CMD.types, {})); + this.types = parsed.types; + this.metals = parsed.metals; + this.emit(); + } catch (err) { + this.typesFor = null; + this.error = err instanceof Error ? err.message : String(err); + this.emit(); + } + } + + private schedule(): void { + if (!this.visible || this.holds > 0) return; + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => { void this.read(); }, READ_DELAY_MS); + } + + private async read(): Promise<void> { + if (!this.stale || !this.visible || this.holds > 0) return; + if (this.reading) { this.again = true; return; } + const { client } = this.ws; + if (client.state !== 'ready') return; + this.reading = true; + this.stale = false; + const epoch = this.epoch; + try { + if (!client.has(CMD.get)) throw new Error(`The engine has no command ${CMD.get}`); + const got = await this.readByCommand(); + if (epoch === this.epoch && this.holds === 0) this.apply(got.docs, got.textures); + else this.stale = true; + if (this.error) { this.error = ''; this.emit(); } + } catch (err) { + this.error = err instanceof Error ? err.message : String(err); + this.emit(); + } finally { + this.reading = false; + if (this.again || this.stale) { this.again = false; this.schedule(); } + } + } + + private async readByCommand(): Promise<{ docs: Map<string, MaterialDoc>; textures: Map<string, TextureInfo> }> { + const docs = new Map<string, MaterialDoc>(); + const textures = new Map<string, TextureInfo>(); + for (const r of this.rows) { + const raw = await this.ws.client.dispatch<Record<string, unknown>>(CMD.get, { key: Number(r.key) }); + const d = parseMaterial(r.key, raw); + if (d) docs.set(r.key, d); + if (textures.size === 0) for (const [k, v] of parseTextures(raw?.textures)) textures.set(k, v); + } + return { docs, textures }; + } + + private apply(docs: Map<string, MaterialDoc>, textures: Map<string, TextureInfo>): void { + let changed = false; + for (const key of [...this.docs.keys()]) if (!docs.has(key)) { this.docs.delete(key); this.sigs.delete(key); changed = true; } + for (const [key, d] of docs) { + const sig = signature(d); + const old = this.docs.get(key); + if (old && this.sigs.get(key) === sig && old.name === d.name) continue; + this.docs.set(key, d); + this.sigs.set(key, sig); + changed = true; + } + const texKey = JSON.stringify([...textures.values()]); + if (texKey !== JSON.stringify([...this.textures.values()])) { this.textures = textures; changed = true; } + if (changed) this.emit(); + } +} diff --git a/frontend/src/ui/material/swatch.ts b/frontend/src/ui/material/swatch.ts new file mode 100644 index 00000000..736e7be5 --- /dev/null +++ b/frontend/src/ui/material/swatch.ts @@ -0,0 +1,175 @@ +import type { Workspace } from '../context'; +import { acescgToLinearSrgb, isObj, keyArg, rgbOf, type MaterialDoc, type Rgb } from './model'; +import { CMD, type MaterialStore } from './store'; + +export const SWATCH_PX = 56; +const PREVIEW_SIZE = 64; +const PARALLEL = 2; +const CACHE_LIMIT = 256; +const DELAY_MS = 160; + +interface Look { albedo: Rgb; roughness: number; metalness: number; opacity: number; map: Uint8ClampedArray | null; mapSize: number } + +const decode = (x: number): number => x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +const encode = (x: number): number => x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055; +const num = (v: unknown, d: number): number => typeof v === 'number' && Number.isFinite(v) ? v : d; + +function shade(look: Look, size: number): ImageData { + const img = new ImageData(size, size); + const px = img.data; + const L = [-0.45, 0.62, 0.64]; + const H = [L[0], L[1], L[2] + 1]; + const hl = Math.hypot(H[0], H[1], H[2]); + const r = Math.min(1, Math.max(0.02, look.roughness)); + const exponent = 2 / (r * r * r * r + 1e-3); + const specScale = Math.min(6, (exponent + 2) / 8); + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + const u = ((x + 0.5) / size) * 2 - 1; + const v = 1 - ((y + 0.5) / size) * 2; + const d2 = u * u + v * v; + const i = (y * size + x) * 4; + if (d2 > 1) { px[i + 3] = 0; continue; } + const z = Math.sqrt(1 - d2); + let a: Rgb = look.albedo; + if (look.map) { + const mx = Math.min(look.mapSize - 1, Math.floor(((u + 1) / 2) * look.mapSize)); + const my = Math.min(look.mapSize - 1, Math.floor(((1 - v) / 2) * look.mapSize)); + const j = (my * look.mapSize + mx) * 4; + a = [decode(look.map[j] / 255), decode(look.map[j + 1] / 255), decode(look.map[j + 2] / 255)]; + } + const ndl = Math.max(0, u * L[0] + v * L[1] + z * L[2]); + const ndh = Math.max(0, (u * H[0] + v * H[1] + z * H[2]) / hl); + const fres = Math.pow(1 - z, 5); + const spec = Math.pow(ndh, exponent) * specScale * ndl; + const out = [0, 0, 0]; + for (let c = 0; c < 3; c++) { + const f0 = look.metalness * a[c] + (1 - look.metalness) * 0.04; + const f = f0 + (1 - f0) * fres * (1 - r) * 0.6; + const diffuse = a[c] * (1 - look.metalness) * (0.12 + 0.88 * ndl); + const env = f * (0.35 + 0.25 * v); + out[c] = diffuse + spec * f + env; + } + px[i] = Math.round(Math.min(1, encode(Math.max(0, out[0]))) * 255); + px[i + 1] = Math.round(Math.min(1, encode(Math.max(0, out[1]))) * 255); + px[i + 2] = Math.round(Math.min(1, encode(Math.max(0, out[2]))) * 255); + const edge = Math.min(1, (1 - Math.sqrt(d2)) * size * 0.5); + px[i + 3] = Math.round(255 * edge * (0.35 + 0.65 * Math.min(1, Math.max(0, look.opacity)))); + } + } + return img; +} + +function localLook(d: MaterialDoc): Look | null { + if (d.graph || Object.keys(d.slots).length) return null; + const base = rgbOf(d.params.base_color) ?? [0.8, 0.8, 0.8]; + return { + albedo: acescgToLinearSrgb(base).map((x) => Math.max(0, x)) as Rgb, + roughness: num(d.params.specular_roughness, 0.3), + metalness: num(d.params.base_metalness, 0), + opacity: num(d.params.geometry_opacity, 1) * (1 - 0.6 * num(d.params.transmission_weight, 0)), + map: null, + mapSize: 0, + }; +} + +async function pixelsOf(b64: string): Promise<{ data: Uint8ClampedArray; size: number } | null> { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + const bmp = await createImageBitmap(new Blob([bytes], { type: 'image/png' })); + const c = document.createElement('canvas'); + c.width = bmp.width; + c.height = bmp.height; + const g = c.getContext('2d'); + if (!g) return null; + g.drawImage(bmp, 0, 0); + bmp.close(); + return { data: g.getImageData(0, 0, c.width, c.height).data, size: c.width }; +} + +export class Swatches { + private readonly cache = new Map<string, ImageData>(); + private readonly wanted = new Map<HTMLCanvasElement, string>(); + private readonly queue = new Map<string, string>(); + private running = 0; + private timer: number | undefined; + + constructor(private readonly ws: Workspace, private readonly store: MaterialStore) {} + + paint(canvas: HTMLCanvasElement, key: string): void { + const sig = this.store.sig(key); + const id = `${key}|${sig}`; + if (this.wanted.get(canvas) === id && canvas.dataset.drawn === id) return; + this.wanted.set(canvas, id); + const hit = this.cache.get(id); + if (hit) { this.draw(canvas, hit, id); return; } + const d = this.store.doc(key); + const look = d ? localLook(d) : null; + if (look) { + const img = shade(look, SWATCH_PX); + this.remember(id, img); + this.draw(canvas, img, id); + return; + } + this.queue.set(key, id); + window.clearTimeout(this.timer); + this.timer = window.setTimeout(() => this.pump(), DELAY_MS); + } + + private draw(canvas: HTMLCanvasElement, img: ImageData, id: string): void { + const g = canvas.getContext('2d'); + if (!g) return; + g.putImageData(img, 0, 0); + canvas.dataset.drawn = id; + } + + private remember(id: string, img: ImageData): void { + this.cache.set(id, img); + if (this.cache.size > CACHE_LIMIT) { + const first = this.cache.keys().next().value; + if (first !== undefined) this.cache.delete(first); + } + } + + private pump(): void { + while (this.running < PARALLEL && this.queue.size) { + const [key, id] = this.queue.entries().next().value as [string, string]; + this.queue.delete(key); + this.running++; + void this.fetch(key, id).finally(() => { this.running--; this.pump(); }); + } + } + + private async fetch(key: string, id: string): Promise<void> { + const { client } = this.ws; + let look: Look | null = null; + if (client.state === 'ready' && client.has(CMD.preview)) { + try { + const raw = await client.dispatch<Record<string, unknown>>(CMD.preview, { key: keyArg(key), size: PREVIEW_SIZE }); + const values = isObj(raw?.values) ? raw.values : {}; + const maps = isObj(raw?.maps) ? raw.maps : {}; + const base = rgbOf(values.base_color) ?? [0.8, 0.8, 0.8]; + let map: { data: Uint8ClampedArray; size: number } | null = null; + if (raw?.constant !== true && typeof maps.base_color === 'string') map = await pixelsOf(maps.base_color); + look = { + albedo: base, roughness: num(values.roughness, 0.3), metalness: num(values.metalness, 0), opacity: num(values.opacity, 1), + map: map?.data ?? null, mapSize: map?.size ?? 0, + }; + } catch { + look = null; + } + } + if (!look) { + const d = this.store.doc(key); + const base = d ? rgbOf(d.params.base_color) : null; + look = { albedo: base ? acescgToLinearSrgb(base) : [0.5, 0.5, 0.5], roughness: 0.5, metalness: 0, opacity: 1, map: null, mapSize: 0 }; + } + const img = shade(look, SWATCH_PX); + this.remember(id, img); + for (const [canvas, want] of this.wanted) { + if (!canvas.isConnected) { this.wanted.delete(canvas); continue; } + if (want === id) this.draw(canvas, img, id); + } + } +} diff --git a/frontend/src/ui/pages/material.ts b/frontend/src/ui/pages/material.ts new file mode 100644 index 00000000..25ef2ee2 --- /dev/null +++ b/frontend/src/ui/pages/material.ts @@ -0,0 +1,138 @@ +import '../../styles/material.css'; +import { el, setHidden, setText } from '../../shell/dom'; +import type { NodeSummary } from '../../engine/types'; +import type { Workspace } from '../context'; +import { Edits } from '../material/edits'; +import { mountLabels } from '../labels'; +import { mountGraph } from '../material/graph'; +import { mountLibraryHook } from '../material/library'; +import { mountList, type ListHost } from '../material/list'; +import { mountParams } from '../material/params'; +import { mountSlots } from '../material/slots'; +import { MaterialStore } from '../material/store'; +import { Swatches } from '../material/swatch'; +import { engineNote, pageHead, section, type PageMount } from './page'; + +function partsUnder(nodes: readonly NodeSummary[], ids: ReadonlyArray<string | number>): string[] { + const kids = new Map<string, NodeSummary[]>(); + for (const n of nodes) { + if (n.parent === null) continue; + const p = String(n.parent); + const list = kids.get(p) ?? []; + list.push(n); + kids.set(p, list); + } + const byId = new Map(nodes.map((n) => [String(n.id), n])); + const out: string[] = []; + const seen = new Set<string>(); + const walk = (n: NodeSummary): void => { + const k = String(n.id); + if (seen.has(k)) return; + seen.add(k); + if (n.kind === 'part') out.push(k); + for (const c of kids.get(k) ?? []) walk(c); + }; + for (const id of ids) { const n = byId.get(String(id)); if (n) walk(n); } + return out; +} + +const AWAIT_MS = 4000; + +export const mountMaterialPage: PageMount = (host, ws) => { + const store = new MaterialStore(ws); + const edits = new Edits(ws, store); + const swatches = new Swatches(ws, store); + pageHead(host, 'Material'); + const offNote = engineNote(host, ws); + const status = el('<p class="fsh-ws-note fsh-mat-status" role="status" hidden></p>'); + host.appendChild(status); + + let current: string | null = null; + let selectionKey = ''; + let parts: string[] = []; + let selected = new Set<string>(); + const listeners = new Set<() => void>(); + + let awaiting: { key: string; until: number } | null = null; + const page: ListHost = { + current: () => current, + pick: (key) => { + if (key !== null && !store.row(key)) awaiting = { key, until: performance.now() + AWAIT_MS }; + if (key === current) return; + current = key; + for (const fn of listeners) fn(); + }, + selectionParts: () => parts, + selectionMaterials: () => selected, + }; + + const listHost = section(host, 'Materials'); + const list = mountList(listHost, ws, store, edits, swatches, page); + listeners.add(list.update); + + const paramsHost = section(host, 'Parameters'); + const none = el('<p class="fsh-mat-none">Pick or create a material to edit it.</p>'); + paramsHost.appendChild(none); + const texHost = section(host, 'Textures'); + const slots = mountSlots(texHost, ws, store, edits, { current: () => current }); + const params = mountParams(paramsHost, ws, store, edits, { current: () => current, slotButton: (f) => slots.button(f) }); + listeners.add(params.update); + listeners.add(slots.update); + + const graph = mountGraph(section(host, 'Graph'), ws, store, { current: () => current }); + listeners.add(graph.update); + + const labelsHost = el('<div class="fsh-mat-labels"></div>'); + section(host, 'Labels').appendChild(labelsHost); + const labels = mountLabels(labelsHost, ws); + let labelsFor: string | null | undefined; + const showLabels = (): void => { + const key = current !== null && store.row(current) ? current : null; + if (key === labelsFor) return; + labelsFor = key; + labels.show(key); + }; + listeners.add(showLabels); + + const library = mountLibraryHook(section(host, 'Library'), ws, store, { current: () => current }); + listeners.add(library.update); + const paintNone = (): void => setHidden(none, current !== null && store.row(current) !== null); + listeners.add(paintNone); + + const follow = (): void => { + const s = ws.client.summary; + const nodes = s?.nodes ?? []; + const key = (s?.selection ?? []).map(String).join(','); + parts = partsUnder(nodes, s?.selection ?? []); + const byId = new Map(nodes.map((n) => [String(n.id), n])); + selected = new Set(parts.map((p) => byId.get(p)?.raw.material).filter((m): m is string | number => typeof m === 'string' || typeof m === 'number').map(String)); + if (awaiting && (store.row(awaiting.key) || performance.now() > awaiting.until)) awaiting = null; + if (current !== null && !store.row(current) && awaiting?.key !== current) page.pick(store.rows[0]?.key ?? null); + if (current === null && store.rows.length) page.pick(store.rows[0].key); + if (key !== selectionKey) { + selectionKey = key; + const active = s?.active !== null && s?.active !== undefined ? String(s.active) : null; + const first = active && parts.includes(active) ? active : parts[0]; + const m = first ? byId.get(first)?.raw.material : undefined; + if (typeof m === 'string' || typeof m === 'number') page.pick(String(m)); + } + }; + + const paintStatus = (): void => { + setText(status, store.error); + setHidden(status, store.error === ''); + }; + + const visible = (): void => store.setVisible(!host.hidden && ws.ctx.shell.isOpen('inspector')); + const watch = new MutationObserver(visible); + watch.observe(host, { attributes: true, attributeFilter: ['hidden'] }); + const offLayout = ws.ctx.shell.onLayout(visible); + visible(); + + follow(); + paintStatus(); + paintNone(); + showLabels(); + const offs = [store.onChange(follow), store.onChange(paintStatus), store.onChange(paintNone), ws.client.onSummary(follow)]; + return () => { watch.disconnect(); offLayout(); offNote(); list.dispose(); params.dispose(); slots.dispose(); graph.dispose(); library.dispose(); for (const off of offs) off(); }; +}; diff --git a/frontend/src/ui/raster-view.ts b/frontend/src/ui/raster-view.ts index be793d89..3175e037 100644 --- a/frontend/src/ui/raster-view.ts +++ b/frontend/src/ui/raster-view.ts @@ -1,5 +1,7 @@ +import { parseEngineView, STATUS_COMMAND, VIEWPORT_COMMAND } from '../engine/devices'; +import { closePreview, MaterialSource, PREVIEW_DEFAULT, PREVIEW_SIZES } from '../engine/raster/materials'; import { RasterRenderer, type RasterMode } from '../engine/raster/renderer'; -import { MeshSource, type RasterInstance } from '../engine/raster/scene-data'; +import { MeshSource, type MaterialInfo, type RasterInstance } from '../engine/raster/scene-data'; import { SceneGraph } from '../engine/scene-graph'; import type { Vec3 } from '../engine/types'; import { onTheme } from '../shell/themes'; @@ -29,6 +31,19 @@ export function cssColor(host: Element, name: string, fallback: Vec3): Vec3 { return p.length >= 3 && p.slice(0, 3).every(Number.isFinite) ? [p[0] / 255, p[1] / 255, p[2] / 255] : fallback; } +const STUDIO_AVERAGE = 0.55; +const SKY_AVERAGE: Vec3 = [0.5, 0.54, 0.6]; + +export function environmentTint(env: unknown): Vec3 { + const e = env && typeof env === 'object' ? env as Record<string, unknown> : {}; + const k = typeof e.intensity === 'number' && Number.isFinite(e.intensity) && e.intensity >= 0 ? e.intensity : 1; + let c: Vec3 = [STUDIO_AVERAGE, STUDIO_AVERAGE, STUDIO_AVERAGE]; + const u = e.uniform_colour; + if (e.source === 'uniform' && Array.isArray(u) && u.length >= 3 && u.slice(0, 3).every((x) => typeof x === 'number' && Number.isFinite(x))) c = [u[0], u[1], u[2]]; + else if (e.source === 'sky') c = SKY_AVERAGE; + return c.map((x) => Math.min(4, Math.max(0, (x * k) / STUDIO_AVERAGE))) as Vec3; +} + export class RasterView { readonly renderer: RasterRenderer; readonly source: MeshSource; @@ -44,11 +59,28 @@ export class RasterView { private holding = false; private outlineSig = ''; lightsMissing = 0; + readonly materials: MaterialSource; + pendingMaterials = 0; + previewSize = PREVIEW_DEFAULT; + private mode: RasterMode = 'solid'; + private materialList: MaterialInfo[] = []; + private readonly busyMaterials = new Set<string>(); + private qualityAt = 0; private readonly fns = new Set<() => void>(); constructor(private readonly ws: Workspace, readonly canvas: HTMLCanvasElement, private readonly camera: ViewCamera) { this.renderer = new RasterRenderer(canvas); this.source = new MeshSource((name, args) => ws.client.dispatch(name, args), (name) => ws.client.has(name)); + this.materials = new MaterialSource((name, args) => ws.client.dispatch(name, args), (name) => ws.client.has(name)); + this.renderer.onRestore(() => { void this.syncMaterials(); }); + ws.client.onDispatch((n) => { + if (n.name !== VIEWPORT_COMMAND) return; + const q = parseEngineView(n.result).quality; + if (!q) return; + this.qualityAt = performance.now(); + this.setPreviewSize(PREVIEW_SIZES[q]); + }); + if (new URLSearchParams(window.location.search).has('raster-debug')) (window as unknown as Record<string, unknown>).__formshotRaster = this; if (!this.renderer.gl || this.renderer.error) { this.state = 'unsupported'; this.message = this.renderer.error; } camera.onChange(() => this.renderer.setCamera(camera.raster())); this.renderer.setCamera(camera.raster()); @@ -60,7 +92,58 @@ export class RasterView { get usable(): boolean { return this.state === 'ready' || (this.state === 'loading' && this.instances.length > 0); } - setMode(mode: RasterMode): void { this.renderer.setMode(mode); } + setMode(mode: RasterMode): void { + this.mode = mode; + this.renderer.setMode(mode); + if (mode === 'material') void this.syncMaterials(); + } + + setPreviewSize(size: number): void { + const s = Math.min(512, Math.max(16, Math.round(size))); + if (s === this.previewSize) return; + this.previewSize = s; + if (this.mode === 'material') void this.syncMaterials(); + } + + private async refreshQuality(): Promise<void> { + const client = this.ws.client; + if (!client.has(STATUS_COMMAND) || performance.now() - this.qualityAt < 5000) return; + this.qualityAt = performance.now(); + try { + const q = parseEngineView(await client.dispatch(STATUS_COMMAND, {})).quality; + this.previewSize = q ? PREVIEW_SIZES[q] : PREVIEW_DEFAULT; + } catch { + this.previewSize = PREVIEW_DEFAULT; + } + } + + private async syncMaterials(): Promise<void> { + if (this.mode !== 'material' || !this.materials.available() || !this.renderer.ready) return; + this.renderer.setEnvironmentTint(environmentTint(this.ws.client.summary?.environment)); + await this.refreshQuality(); + const used = new Set(this.instances.filter((i) => i.visible).map((i) => i.material).filter((k): k is string => k !== null)); + const size = this.previewSize; + const wanted = this.materialList.filter((m) => used.has(m.key) && !this.busyMaterials.has(m.key) + && !this.renderer.hasMaterial(m.key, m.revision, size) && !this.materials.failure(m.key, m.revision, size)); + if (!wanted.length) return; + for (const m of wanted) this.busyMaterials.add(m.key); + this.pendingMaterials += wanted.length; + this.emit(); + await Promise.all(wanted.map(async (m) => { + try { + const maps = await this.materials.maps(m.key, m.revision, size); + if (this.materialList.some((x) => x.key === m.key)) this.renderer.setMaterial(maps); + else closePreview(maps); + } catch { + this.renderer.invalidate(); + } finally { + this.busyMaterials.delete(m.key); + this.pendingMaterials--; + this.emit(); + } + })); + void this.syncMaterials(); + } setSize(width: number, height: number, dpr: number): void { this.renderer.setSize(width * dpr, height * dpr); @@ -107,6 +190,11 @@ export class RasterView { this.renderer.setInstances(this.instances); this.renderer.keepMeshes(new Set(scene.meshes.map((m) => m.key))); this.source.forget(new Set(scene.meshes.map((m) => m.key))); + this.materialList = scene.materials ?? []; + const materialKeys = new Set(this.materialList.map((m) => m.key)); + this.renderer.keepMaterials(materialKeys); + this.materials.forget(materialKeys); + void this.syncMaterials(); this.select(); const wanted = scene.meshes.filter((m) => !this.renderer.hasMesh(m.key, m.revision)); this.pendingMeshes = wanted.length; diff --git a/frontend/src/ui/viewport.ts b/frontend/src/ui/viewport.ts index 4efffe7b..bb591f53 100644 --- a/frontend/src/ui/viewport.ts +++ b/frontend/src/ui/viewport.ts @@ -17,6 +17,7 @@ import { DEFAULT_POSE } from '../engine/camera-nav'; const VIEW_FRAME = 'view.frame'; import { createPicker } from './picking'; import { attachInput } from './viewport-input'; +import { attachPresetDrop } from './library/drop'; import { GizmoControl } from './gizmo-control'; import { Overlay } from './overlay'; import { hud, hudTitle } from './hud'; @@ -483,6 +484,7 @@ export function mountViewport(ws: Workspace): ViewportControls { sendRegion({ x: x0 / w, y: y0 / h, width: (x1 - x0) / w, height: (y1 - y0) / h }); }, }); + attachPresetDrop(ws, { frame: () => frame.getBoundingClientRect(), size: () => fitted, raster: () => raster, dpr }); } return api; diff --git a/frontend/src/version.ts b/frontend/src/version.ts index 465e390c..cc337735 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.4.0'; +export const VERSION = '0.6.0'; diff --git a/native/Cargo.lock b/native/Cargo.lock index 6f8735a3..a92726a9 100644 --- a/native/Cargo.lock +++ b/native/Cargo.lock @@ -38,6 +38,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "bevy_mikktspace" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bff34eb29ff4b8a8688bc7299f14fb6b597461ca80fec03ed7d22939ab33e48f" + [[package]] name = "bit-set" version = "0.10.0" @@ -94,6 +100,16 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -188,6 +204,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + [[package]] name = "foldhash" version = "0.2.0" @@ -196,15 +218,24 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "fsh-accel" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fsh-core", "rayon", ] +[[package]] +name = "fsh-cad" +version = "0.6.0" +dependencies = [ + "fsh-core", + "fsh-io", + "serde_json", +] + [[package]] name = "fsh-cli" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fsh-commands", "fsh-io", @@ -213,9 +244,10 @@ dependencies = [ [[package]] name = "fsh-commands" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fsh-accel", + "fsh-cad", "fsh-core", "fsh-format", "fsh-io", @@ -228,11 +260,11 @@ dependencies = [ [[package]] name = "fsh-core" -version = "0.4.0" +version = "0.6.0" [[package]] name = "fsh-format" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fsh-core", "fsh-scene", @@ -242,23 +274,28 @@ dependencies = [ [[package]] name = "fsh-io" -version = "0.4.0" +version = "0.6.0" dependencies = [ + "bevy_mikktspace", "fsh-core", "fsh-scene", + "roxmltree", "serde_json", + "ufbx", + "zune-jpeg", ] [[package]] name = "fsh-materials" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fsh-core", + "serde", ] [[package]] name = "fsh-py" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fsh-commands", "pyo3", @@ -266,7 +303,7 @@ dependencies = [ [[package]] name = "fsh-render-cpu" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fsh-accel", "fsh-core", @@ -277,7 +314,7 @@ dependencies = [ [[package]] name = "fsh-render-gpu" -version = "0.4.0" +version = "0.6.0" dependencies = [ "bytemuck", "fsh-accel", @@ -292,16 +329,17 @@ dependencies = [ [[package]] name = "fsh-scene" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fsh-core", + "fsh-materials", "serde", "serde_json", ] [[package]] name = "fsh-wasm" -version = "0.4.0" +version = "0.6.0" dependencies = [ "bytemuck", "fsh-commands", @@ -932,6 +970,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -993,6 +1040,12 @@ dependencies = [ "zmij", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "slab" version = "0.4.12" @@ -1095,6 +1148,15 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "ufbx" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "260522f1eb74139f0e78b29dd82a58e5437d728c5498024a39e5af7282694240" +dependencies = [ + "cc", +] + [[package]] name = "unicode-ident" version = "1.0.27" @@ -1528,3 +1590,18 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/native/Cargo.toml b/native/Cargo.toml index 3602ad2c..eb2cf32c 100644 --- a/native/Cargo.toml +++ b/native/Cargo.toml @@ -6,6 +6,7 @@ members = [ "crates/fsh-accel", "crates/fsh-materials", "crates/fsh-io", + "crates/fsh-cad", "crates/fsh-format", "crates/fsh-render-cpu", "crates/fsh-render-gpu", @@ -20,6 +21,7 @@ default-members = [ "crates/fsh-accel", "crates/fsh-materials", "crates/fsh-io", + "crates/fsh-cad", "crates/fsh-format", "crates/fsh-render-cpu", "crates/fsh-render-gpu", diff --git a/native/HASHOUT_LOG.md b/native/HASHOUT_LOG.md index b667e054..277525db 100644 --- a/native/HASHOUT_LOG.md +++ b/native/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # native HASHOUT_LOG -Living log for the Rust engine side, _v0.4.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. Entries are appended to their crate's section as each part lands; the GPU engine's entries (fsh-render-gpu, last) carry the buffer layout contract, the WGSL module map and the recipe for running it on software Vulkan, GL and WebGPU, and docs/GPU-ENGINE.md restates them as tables. +Living log for the Rust engine side, _v0.6.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. Entries are appended to their crate's section as each part lands; the GPU engine's entries (fsh-render-gpu, last) carry the buffer layout contract, the WGSL module map and the recipe for running it on software Vulkan, GL and WebGPU, and docs/GPU-ENGINE.md restates them as tables. ## Org-navi-map @@ -28,6 +28,13 @@ native/ crates/fsh-materials/src/lobes.rs EON diffuse, fuzz crates/fsh-materials/src/tables.rs directional-albedo tables built at first use, warm_up crates/fsh-materials/src/bsdf.rs Bsdf, BsdfSample, LobeFlags, ShadingFrame + crates/fsh-materials/src/program.rs Program, Instr, Op (25 opcodes with 24 Label), Field (22), NEED_* bits, encode, encode_f32, decode, check, disassemble + crates/fsh-materials/src/interp.rs HitContext, Shaded, Program::evaluate, fold (the pure-op evaluator the compiler shares) + crates/fsh-materials/src/texture.rs ColourSpace, srgb8_table, TextureSet, TextureImage, TextureLevel, Texels, TextureSampler, NoTextures + crates/fsh-materials/src/sample.rs mip builder, impl TextureSampler for TextureSet, wrap_index + crates/fsh-materials/src/film.rs Airy thin-film reflectance (Belcour and Barla), s/p Fresnel with phases, Gulbrandsen, FilmLayer + crates/fsh-materials/src/optics.rs Optics (film and Cauchy dispersion), dispersion_channel, thin_film_dielectric, thin_film_conductor + crates/fsh-materials/src/procedural.rs ProcKind, ProcOutput, procedural(); procedural/common.rs, noise.rs, cells.rs, patterns.rs hold the ten kinds crates/fsh-scene/src/error.rs SceneError with code() crates/fsh-scene/src/ser.rs serde with-helpers for fsh-core types crates/fsh-scene/src/mesh.rs Mesh, validation, compute_normals @@ -43,13 +50,43 @@ native/ crates/fsh-scene/src/editor.rs Editor: execute, dispatch, undo, redo, groups, barrier crates/fsh-scene/src/selection.rs Selection, SelectionLevel, SelectMode crates/fsh-scene/src/snapshot.rs RenderSnapshot, flatten, SCENE_UNITS_PER_NIT + crates/fsh-scene/src/slots.rs MaterialInput, TextureSlot, MapProjection, UvTransform, CoordSpace, Channel + crates/fsh-scene/src/graph.rs MaterialGraph, GraphNode, GraphOp (18 kinds), Link, SocketRef, SocketValue, kind catalogue, validation, order + crates/fsh-scene/src/types.rs the 18 material types, ParamSpec, METALS, preset graphs (wood, stone, paint_metallic) and the optional brushed bump + crates/fsh-scene/src/compile.rs TextureTable, base_inputs, compile_material (folding, dead code, register allocation) + crates/fsh-scene/src/labels.rs Label (projected image labels), frame, consts for opcode 24, validation, the label command arguments + crates/fsh-scene/src/preview.rs bake_preview, preview_hit, PreviewMaps for the window's raster material view crates/fsh-io/src/ raw scene, glTF/GLB, OBJ+MTL, STL, PLY readers, clean-up, convert, GLB writer, deflate, PNG, HDR, EXR + crates/fsh-io/src/zip.rs in-memory ZIP reader for 3MF packages (stored and deflated, ZIP64 sizes, CRC and bomb checks) + crates/fsh-io/src/threemf.rs 3MF reader: units, build items, components, materials, colour and texture groups + crates/fsh-io/src/fbx.rs FBX reader on ufbx (native only): nodes, meshes, materials, texture slots, embedded images + crates/fsh-io/src/triangulate.rs ear clipping in the Newell plane, fan fallback (OBJ and PLY polygons) + crates/fsh-io/src/tangents.rs MikkTSpace tangents through bevy_mikktspace + crates/fsh-io/src/jpeg.rs read_jpeg on zune-jpeg (baseline and progressive), is_jpeg, JPEG_MAX_SIDE + crates/fsh-io/src/picture.rs decode_image, detect_image, DecodedImage, ImagePixels; the OpenEXR reader (NONE, RLE, ZIPS, ZIP, PIZ, PXR24) + crates/fsh-io/src/watch.rs Watch (progress, stage, cancel flag) shared by readers, the clean-up, fsh-cad and import jobs + crates/fsh-io/src/family/ hand-offs from the Form family: app.rs (who wrote a file), gof.rs (GoF folders), maps.rs (FormSurface map names), surface.rs (FormSurface export folders), handoff.rs (inspect and read) + crates/fsh-cad/src/lib.rs the CAD crate root: STEP and IGES through FormCAD's kernel worker into a RawScene + crates/fsh-cad/src/locate.rs, client.rs worker search (env, beside the app, user cache) and the JSON-lines client with kill on cancel and timeout + crates/fsh-cad/src/mesh.rs, quality.rs the worker's .mesh tessellation file, quality presets and custom chord and angle + crates/fsh-cad/src/read.rs, probe.rs read(): bodies to nodes, colours to materials, shared shapes to instances; probe() without tessellation + crates/fsh-cad/src/scan.rs, error.rs STEP and IGES headers, IGES solid colours, STEP face colours read from the file; CadError with code() crates/fsh-format/src/ zip, canonical json, meshbin, version, project save/load, journal, session and recovery, platform (wall clock, process id, file-system guard) + crates/fsh-format/src/sha256.rs FIPS 180-4 SHA-256 for texture member names crates/fsh-render-cpu/src/ geometry, env, sky, lights, emissive, camera, film, integrator, denoise, develop, renderer, clock, spec (the GPU port's specification) crates/fsh-commands/src/ engine session, dispatch, catalogue, alias table, background render, summary, samples, GLB export crates/fsh-commands/src/view.rs, meshes.rs view.pick, view.frame, view.bounds, scene.meshes, scene.mesh_data crates/fsh-commands/src/device.rs, gpu.rs PreviewRenderer, device list and choice, GpuPreview, the fallback ladder crates/fsh-commands/src/journal.rs CrashJournal over fsh-format's Session; clock.rs, the one time source + crates/fsh-commands/src/textures.rs texture_image, TextureCache (load, lookup), LoadedTextures, texture_location: snapshot textures to a TextureSet + crates/fsh-commands/src/ext/mod.rs ExtCommand, commands(), dispatch(): the command groups added from 0.5.0 on, one module each + crates/fsh-commands/src/ext/import.rs import.probe, import.start, import.status, import.cancel, file.reimport, file.import and file.open schemas + crates/fsh-commands/src/ext/import/ options.rs, run.rs (prepare and apply), probe.rs, jobs.rs, source.rs, reimport.rs, textures.rs (embedding) + crates/fsh-commands/src/ext/cad.rs cad.status, scene.retessellate, the CAD branch of file.import and import jobs + crates/fsh-commands/src/ext/handoff.rs handoff.inspect, handoff.open + crates/fsh-commands/src/ext/materials.rs material.types, material.node_kinds, material.program, material.preview_maps + crates/fsh-commands/src/ext/library.rs library.list, get, favorite, recent, apply, save, remove, thumbnail, thumbnails + crates/fsh-commands/src/ext/library/ locate.rs, preset.rs, store.rs, search.rs, state.rs, ball.rs, thumbs.rs, apply.rs, sha256.rs crates/fsh-cli/src/main.rs formshot-engine: render (--device), info, convert, devices, bench, catalogue, dispatch (--journal), version, help crates/fsh-py/src/lib.rs pyo3 binding fsh_py (python feature, Session(journal=...)), pyproject.toml for maturin crates/fsh-wasm/src/lib.rs, session.rs, mirror.rs wasm-bindgen binding: catalogue, Session, Scene, the service mirror, the host clock @@ -70,7 +107,12 @@ native/ crates/fsh-render-gpu/src/hwaccel.rs HwAccel: BLAS per mesh, TLAS, group 2 (native only) crates/fsh-render-gpu/src/traversal.rs TraversalMode, Traversal, TraversalReport, GpuStats, AccelReport crates/fsh-render-gpu/src/validate.rs naga validation and the layout comparison (feature validate) - crates/fsh-render-gpu/src/shaders/ 21 WGSL modules (see the module map below) + crates/fsh-render-gpu/src/shaders/ 24 WGSL modules (see the module map below and docs/GPU-ENGINE.md) + crates/fsh-render-gpu/src/shaders/procedural.wgsl the WGSL port of the ten procedural kinds (self-contained) + crates/fsh-render-gpu/src/shaders/texture.wgsl tex_sample: the texture directory, nearest, bilinear, trilinear, wraps, sRGB LUT, primaries + crates/fsh-render-gpu/src/shaders/program.wgsl HitCtx, run_program: the material program interpreter (opcodes 0 to 24), sanitize_inputs + crates/fsh-render-gpu/src/texpack.rs append, block_len: a TextureSet packed into the tables block + crates/fsh-wasm/src/textures.rs Ident, TextureStore, SceneTextures, decode, pack and unpack for the window's texture worker ``` ## Contents @@ -81,6 +123,7 @@ native/ - [fsh-scene](#fsh-scene) - [fsh-io](#fsh-io) - [fsh-format](#fsh-format) +- [fsh-cad](#fsh-cad) - [fsh-render-cpu](#fsh-render-cpu) - [fsh-commands](#fsh-commands) - [fsh-cli](#fsh-cli) @@ -214,6 +257,54 @@ Scratch program in /home/claude/targets/materials/scratch (release). White furna - logged: v0.3.0 · 2026-12-02 `energy_tables() -> EnergyTables` hands out the dimensions, axes and `&'static` slices of the cached tables so the GPU engine uploads the very same numbers instead of rebuilding or copying them. Layouts, row-major with the last index fastest: cond `[32 rough][32 mu]`, cond_avg `[32]`, diel `[2 side][16 eta][32 rough][32 mu][E_R, E_T]`, sheen `[16 rough][32 mu]`. The dielectric build keeps its scoped threads natively and runs serially on wasm32, where `std::thread::scope` panics. Verified: a program compiling the previous tables.rs beside the new one found all 34,336 values bit-identical (native); clippy on native and wasm32 shows only the warnings that were there before. The wasm32 serial path was compiled; it ran in the browser engine only as part of the WebAssembly package. +### crates/fsh-materials/src/program.rs · the material program and its encoding +- refers-to: src/program.rs :: Program, Instr, Op, Field, Output, Wrap, Filter, REGISTERS, NEED_UV0..NEED_BUMP, Program::encode, encode_f32, decode, check, disassemble, is_constant +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Texture slots and material graphs compile to one flat register bytecode that both the CPU interpreter (`Program::evaluate`, called per hit by fsh-render-cpu) and the GPU interpreter (`program.wgsl`) run (this entry was first written before either tracer ran programs; see the fsh-render-cpu and fsh-render-gpu entries of the texture work), rather than to generated shader code: a material edit then never compiles a shader, and the CPU stays the specification. A `Program` holds `base` (the constant `SurfaceInputs`), `code` (instructions `{op, dst, flags, a, b, c}`), a constant pool, an output table applied in order after the code, the registers used (at most 32 vec4), `needs` bits (uv sets 0 to 3, tangent, textures, procedural, normal, bump) and the snapshot texture indices it samples. A constant program (`code` and `outputs` empty) is the zero-cost path: the renderer uses `base` and never calls the interpreter, and `base` equals 0.4.0's per-instance inputs bit for bit. 24 opcodes (Nop, Const, Input, Swizzle, Combine, Add to Pow, Lerp, Clamp, Invert, Luminance, Ramp, Xform2, Project, Tex, TexBox, NormalMap, Bump, Proc) and 22 fields; the table is in docs/MATERIALS.md. `encode()` writes words `0x4d50` magic, version 1, counts, registers, needs, then 4 words per instruction (`op | dst << 8 | flags << 16, a, b, c`, each below 2^24), constants, outputs `field | reg << 8`; `encode_f32()` is the same with every integer stored as an exact float, for the GPU `tables` buffer (the 8-storage-buffer budget is full, so no new binding). + +### crates/fsh-materials/src/interp.rs · the interpreter +- refers-to: src/interp.rs :: HitContext, Shaded, Program::evaluate, fold +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`Program::evaluate(&HitContext, &dyn TextureSampler) -> Shaded` is a flat loop with no recursion (GPU friendly): registers start at zero, each instruction writes `dst`, then each output writes its field (floats take x, colours xyz, `Normal` xyz normalised with the incoming shading normal when not finite, `Displacement` x), then the inputs are sanitised. Bump is compiled as the height cone emitted three times at offset inputs (`Input` flags >> 4: 0 none, 1 along u, 2 along v) and the Mikkelsen 2010 surface gradient: `eps = clamp(0.5 * footprint, 1e-6, 1e-2)` metres, `dhdu = (h_u - h) / du`, `R1 = cross(dpdv, N)`, `R2 = cross(N, dpdu)`, `n' = normalize(|det| N - sign(det) (dhdu R1 + dhdv R2))`. `fold` is the pure-op evaluator the compiler's constant folding shares, so folded and run values agree exactly. `HitContext::default()` is a flat frame (+Z normal, +X dpdu, +Y dpdv). Displacement is compiled and stored, not applied per hit. + +### crates/fsh-materials/src/texture.rs · texture pixels, colour spaces, the sampler seam +- refers-to: src/texture.rs :: ColourSpace, ColourSpace::to_shading, srgb8_table, TextureSet, TextureImage, TextureLevel, Texels, TextureSampler, NoTextures +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The pixel types live in fsh-materials (which has no fsh-scene dependency) so both renderers and the preview bake share them: `TextureSet {images: Vec<Option<Arc<TextureImage>>>}` in snapshot order (None samples the fallback), `TextureImage {colour_space, levels}`, `TextureLevel {width, height, texels}`, `Texels::Rgba8` or `RgbaF32`, row 0 at v = 1. `TextureSampler::sample(texture, uv, footprint, wrap, filter, fallback)` is the seam; `NoTextures` returns the fallback and was what `material.preview_maps` passed until the QA pass, which gave the bake the engine's cached `TextureSet` (logged under fsh-commands); both path tracers now sample real images (the `impl TextureSampler for TextureSet` in sample.rs, logged below). Mips, bilinear, nearest and trilinear filtering and the sRGB table are specified once for both engines in docs/MATERIALS.md. + +### crates/fsh-materials/src/procedural.rs, procedural/ · the ten procedural kinds +- refers-to: src/procedural.rs :: ProcKind, ProcOutput, procedural; src/procedural/common.rs :: pcg3d, aa; src/procedural/noise.rs; src/procedural/cells.rs; src/procedural/patterns.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`procedural(kind, output, args)` dispatches to noise 0, fbm 1, voronoi 2, checker 3, gradient 4, wave 5, brushed 6, flakes 7, wood 8, marble 9. `args[0]` is the coordinate (xyz metres, footprint w), then the kind's inputs in table order, then a settings vector (seed, mode 1, mode 2, 0) read at its fixed index; missing arguments read as zero, non-finite inputs as 0, coordinates are clamped to 1e9 before floor. Hashing is integer pcg3d (Jarzynski and Olano, JCGT 9(3), 2020) on u32 in Rust and WGSL alike, so patterns agree bit for bit in their integer parts; unit floats are `(h >> 8) * 2^-24`. Noise is Perlin's improved noise (SIGGRAPH 2002); fbm follows Musgrave; voronoi is Worley's 27-cell search; marble uses Perlin's 1985 turbulence. Anti-aliasing is frequency clamping: `aa(r) = 1 - smoothstep(0.5, 1, r)` with r the footprint over the feature length, each kind fading its detail to its measured mean (for example voronoi euclidean F1 0.4801 at randomness 0, 0.5205 at 1; marble veins 0.1309; wood rings 1/4). Flakes output 0 is a tangent-space normal and output 2 its normal-map colour, because a procedural sees no frame; the presets route the colour through a normal_map node. Formulas per kind are in docs/MATERIALS.md. + +### crates/fsh-materials · program and procedural verification +- refers-to: crates/fsh-materials :: (crate) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +mat-core's throwaway program (/home/claude/t3/targets/mat-core/check, 40 checks, 0 failures): constant graphs fold into `base`; noise to ramp and bump graphs run; slot uv transform, channel and range and box projection match hand values on a grid; missing images fall back to the constants; bump of a linear height gives the analytic normal (-0.0995, 0, 0.995); a normal map with flip_y matches. Procedurals (/home/claude/t3/targets/procedurals/check): 45 cases (every kind, mode and output) written as panels at four extents and looked at; the same cases run in procedural.wgsl in a wgpu compute shader on lavapipe over 8192 points each, largest difference per kind noise, fbm, voronoi, checker and wood 0, gradient 5.4e-7, marble 2.4e-7, wave 1.2e-7, flakes 8.9e-8, brushed 6.0e-8; preset base colours averaged over 256 by 256 planes the same near and at 4 m (wood 0.400 against 0.399). `cargo clippy -p fsh-materials -p fsh-scene --all-targets -- -D warnings` clean. GPU work ran only on a software driver. + +### crates/fsh-materials/src/sample.rs, texture.rs · the texture sampler +- refers-to: src/sample.rs :: impl TextureSampler for TextureSet, wrap_index; src/texture.rs :: TextureImage::from_rgba8, from_rgba16, from_rgba_f32, from_level, build_mips, stores_srgb, sample; TextureLevel::is_valid, texel, half, bilinear, nearest +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The sampler of docs/MATERIALS.md, which the GPU's `texture.wgsl` follows exactly. Choices the contract left open: `Rgba8` in srgb decodes rgb through `srgb8_table()` and alpha as i / 255, other spaces i / 255; mips of 8-bit sRGB rgb are `round(srgb_encode(mean of decoded) * 255)`, other 8-bit channels the exact integer mean `(a + b + c + d + 2) / 4` (a float formula rounds x.5 ties differently in f32 and f64), float levels the plain mean; odd sizes follow the contract literally (`w/2` floored, indices clamped); trilinear blends only when the fraction is above 0; a non-finite uv returns the fallback. Float storage is always linear: 16-bit PNGs become floats with `srgb_decode(i / 65535)` on rgb in srgb space, HDR and EXR floats are stored as read with NaN and infinities set to 0 (also when building from any float texels). A cached image without mips gets them when a later user wants trilinear. Verification: 26 hand checks (wraps, orientation, sRGB and primaries, mips, level choice, fallbacks); 800 random lookups against an independent numpy implementation within 1.2e-6 with identical mip bytes; 600 lookups on a texture seeded with NaN and infinities stay finite. + +### crates/fsh-materials/src/film.rs, optics.rs, bsdf.rs · thin-film iridescence +- refers-to: src/film.rs :: airy, film_dielectric, film_conductor, gulbrandsen, FilmLayer; src/optics.rs :: Optics, thin_film_dielectric, thin_film_conductor; src/bsdf.rs :: Bsdf::new_optics, Ctx.film_n2 +- kind: decision +- logged: v0.6.0 · 2026-12-02 +OpenPBR 1.1's `thin_film_*` parameters, which the 0.4.0 BSDF ignored, follow Belcour and Barla (ACM TOG 36(4), 2017): the Airy sum of a film of ior n2 and thickness d (micrometres) over a dielectric or conductor base, three orders with Belcour's Gaussian sensitivity fits per XYZ component (phase folded into the fits; checked against direct integration of the Wyman CMF fit), unpolarised as the mean of s and p, then to ACEScg through rows of the XYZ-to-AP1 matrix (Bradford from equal energy to the ACES white) normalised so a flat reflectance maps to grey, with the DC term added directly and the result clamped to 0..1. Below 0.03 um the film fades to nothing (Belcour's thin limit). In the BSDF the film sits on the base below the coat (medium above = the coat mix); dielectric reflection is `lerp(F, Airy, weight)` per channel for the opaque and transmissive parts and transmission is 1 - F (lossless; a thin wall with specular_ior 1 is a soap bubble); metals blend F82 with the conductor Airy, the metal's n and k from Gulbrandsen with r = base colour and g = specular colour (an approximation OpenPBR suggests). Lobe albedos use the film at the exact angle for delta lobes and the F = 1 GGX table times the mean film change over four fixed visible-normal samples for rough ones. Optics are per material and constant: programs and textures never change them; `Bsdf::new` is unchanged (film inert), `Bsdf::new_optics` adds it. Verification: against an f64 spectral reference (exact per-wavelength Airy, 0.5 nm), dielectric bases mean 0.0030 per channel (max 0.117 at grazing), conductor bases mean 0.0118; the film Fresnel never exceeds 1 over 0 to 10 um; sampled white furnace 0.986 to 1.008 over seven angles for bubbles, filmed glass, metal, plastic and pearl; anodised titanium thicknesses give bronze, violet, blue, light blue, gold and magenta as the library names them. + +### crates/fsh-materials/src/optics.rs · dispersion as one hero channel +- refers-to: src/optics.rs :: Optics::new, Optics::channel_ior, is_dispersive, dispersion_channel, ABBE_SPAN, CHANNEL_WAVELENGTHS, CHANNEL_DISPERSION +- kind: decision +- logged: v0.6.0 · 2026-12-02 +OpenPBR 1.1: V_d = abbe / scale, a Cauchy law through n_d with that Abbe number, stored as the slope k = scale / (abbe (lambda_F^-2 - lambda_C^-2)), so `n_c = n_d + (n_d - 1) k D_c` with D_c = lambda_c^-2 - lambda_d^-2 = (-0.0062823046, 0.5049531, 1.9850688) um^-2 for ACEScg R, G, B. The channel wavelengths (588.2, 542.2, 452.6 nm) are those whose Cauchy ior equals each channel's sensitivity-weighted mean ior, the first-order exact choice; red sits near the d line and close to green, blue far away, so a prism shows three slit images. The renderer (both tracers, identically) picks c = floor(3u) from sampler dimension 5 (`DIM_WAVELENGTH`, reserved by fsh-core and unused until now, so no other draw moves) at a dispersive, transmissive, not thin-walled hit, sets specular_ior to n_c, and the first transmission sample multiplies the throughput by 3 on channel c and 0 elsewhere; next-event estimation before that point takes the same weight. Diamond (n_d 2.4175, V 55.3) gives 2.41742, 2.42428, 2.44415. Not done: dispersion inside a channel, on thin walls, in the catcher mirror, transparent shadows through dispersive glass. + ## fsh-scene ### crates/fsh-scene/src/command.rs · ids and resolve @@ -270,6 +361,54 @@ Not implemented: unit rescale, model sets, multi-materials, studios, measurement - logged: v0.2.0 · 2026-12-02 `cargo check -p fsh-scene` clean; clippy reports nothing in this crate. The scratch program /home/claude/targets/scene/scratch built a document through `Editor::dispatch` only, undid everything, redid everything, round-tripped the JSON and every journalled command, and flattened: `commands=39 journal=24 depth=19 undos=19 nodes_after_undo=0 redos=19 redo_identical=true json_roundtrip=true cmd_roundtrip=true | snapshot: meshes=4 instances=8 materials=4 lights=1 cutaways=1 tris=9049 | catalogue=39 schema_bytes=38980 | mesh_arc_shared=true | changes=63 dirty=true`, with the expected refusals (locked node, specular_ior 0.5 out of 1..4, unknown command `scene.fly`). Three `material.set_params` calls merged as false, true, true. After reparenting under a part at y=0.25 the local translation was y=-0.25 and the world origin unchanged. +### crates/fsh-scene/src/types.rs · material types are presets of one model +- refers-to: src/types.rs :: MaterialType, ParamSpec, ParamKind, material_types, material_type, types_json, METALS, metal_colour, MaterialType::material, MaterialType::optional_graph +- kind: decision +- logged: v0.6.0 · 2026-12-02 +There is one surface model (`SurfaceParams`, OpenPBR Surface names); a material type is only a preset of it: defaults, the parameters its page shows (`ParamSpec {field, kind, min, max, unit}`, `slot()` when a texture may drive it) and an optional preset graph. The 18 ids are final (the library and SEAMS use them): generic, plastic, plastic_clear, metal, metal_brushed, paint, paint_metallic, glass, glass_thin, liquid, gem, rubber, fabric, ceramic, diffuse, emissive, wood, stone. Defaults come from published values (PMMA 1.49, soda-lime 1.52, water 1.333 at 20 C and 589 nm, diamond 2.417 with Abbe 55) and are converted from linear sRGB to ACEScg. `METALS` lists ten textbook F0 values (Real-Time Rendering 4th ed. table 9.2) with a white edge tint. Preset graphs: wood (a wood node, 250 rings per metre, colours (0.48, 0.30, 0.15) and (0.20, 0.10, 0.04) to base_color), stone (a marble node, 8 veins per metre), paint_metallic (flakes at 2000 per metre, density 0.5, spread 0.25; the mask lerps roughness 0.35 to 0.12, metalness 0.5 to 0.9 and mixes two blues into base_color; the flake colour goes through normal_map into normal: 18 instructions, 9 registers). `optional_graph` (JSON `optional_graph`, null except metal_brushed) holds a brushed bump (1000 lines per metre, 2 cm streaks, 3e-5 m) that new materials do not get by default: 17 instructions, 8 registers. Because paint_metallic's base colour now comes from its graph, the page's base colour field changes nothing until the mix node is edited. + +### crates/fsh-scene/src/slots.rs, material.rs · texture slots on materials +- refers-to: src/slots.rs :: MaterialInput, MaterialInput::slottable, TextureSlot, TextureSlot::for_input, MapProjection, UvTransform, CoordSpace, Channel; src/material.rs :: Material::slots, Material::graph, MATERIAL_FIELDS, texture_keys, validate_refs, map_textures +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`Material` gains `slots: BTreeMap<MaterialInput, TextureSlot>` and `graph: Option<Box<MaterialGraph>>`, both left out of the JSON when empty so older documents encode to the very same bytes and crash-journal fingerprints of older sessions still match. `MATERIAL_FIELDS` names every material field (`name, type_id, params, textures, slots, graph`) and is what fsh-format uses to tell known from preserved fields; a new material field is added there. Slots are allowed on base_color, specular_roughness, base_metalness, specular_weight, coat_weight, coat_roughness, emission_color, geometry_opacity, normal, bump and displacement. A slot names a document texture and carries projection (uv set, box, planar, cylindrical, spherical), transform, wrap, filter, colour space, channel, range, invert, multiply (glTF factor semantics), strength, flip_y and fallback; defaults reproduce the input's constant when the image is missing. Number inputs read rgb as ACEScg luminance, which is exact on grey maps. `map_textures` drops slots whose texture maps to None and nulls graph texture nodes, which is how `texture.remove` follows textures. Document validation (document.rs) checks slot and graph references through `validate_refs`, so a file naming a missing texture is refused on load. + +### crates/fsh-scene/src/graph.rs · the material graph +- refers-to: src/graph.rs :: MaterialGraph, GraphNode, GraphOp, Link, SocketRef, SocketValue, SocketType, graph_kinds, graph_kind, graph_kinds_json, MaterialGraph::validate, order +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Nodes are a `BTreeMap<u32, GraphNode>` serialised as an object keyed by decimal strings and parsed back by a helper, because command arguments pass through serde's buffered content, which does not turn "1" into a number; links are kept sorted by (to, from); outputs map a material input to a node socket. Everything is stable (BTreeMaps, sorted links, no hashed floats), so a graph saves to the same bytes every time. 18 node kinds (constant, texture, mapping, mix, math, colour_ramp, normal_map, bump and the ten procedurals). Validation: non-zero ids, links naming existing sockets of the right direction, at most one link per input, no cycles, types that convert (float and colour by splat and luminance, vector and colour componentwise, float to vector by splat, normal only into normal or vector inputs), setting values in range, texture keys present, at most 256 nodes, and the material must compile within 32 registers. Graph outputs drive every input except bump (a graph bumps with a Bump node into normal). + +### crates/fsh-scene/src/compile.rs, snapshot.rs, preview.rs · compiling, the snapshot and the preview bake +- refers-to: src/compile.rs :: compile_material, TextureTable, base_inputs; src/snapshot.rs :: RenderMaterial::program, RenderTexture, RenderSnapshot::textures; src/preview.rs :: bake_preview, preview_hit, PreviewMaps +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`compile_material` emits per input (graph output over slot over constant), folds pure ops through `fsh_materials::fold`, drops dead code and allocates registers by liveness, refusing past 32 (then `material.set_graph` fails). A slot or graph whose value does not vary folds into `base`. `base_inputs` is bit-identical to fsh-render-cpu's `surface_inputs(p, None)`. A material that fails to compile falls back to its constant program. The snapshot gives each `RenderMaterial` an `Arc<Program>` and lists `RenderTexture {key, path, colour_space, mipmaps}`, deduplicated by (path, colour space), so one image used for colour and for a number appears twice. `bake_preview` evaluates the program on a 1 m square in the object XY plane facing +Z (pixel (x, y) at uv `((x + 0.5) / size, 1 - (y + 0.5) / size)`, footprint 1 / size) into base colour, roughness, metalness and normal maps, which the window's raster material view samples by mesh uv0. + +### crates/fsh-scene/src/command.rs, catalogue.rs · material and part-mesh commands +- refers-to: src/command.rs :: MaterialCreate, MaterialSetType, MaterialSetSlot, MaterialClearSlot, MaterialSetGraph, SetPartMesh; src/catalogue.rs :: MERGEABLE +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`material.create` takes `type` and `name` and starts from the type's preset (params and graph); resolve stores the full material and drops `type` and `name`, so journals replay exactly even if a preset changes. `material.set_type` gains `keep` (default true, the old behaviour, so old journals replay the same); `keep: false` resets params and graph, slots stay. `material.set_slot {key, input, slot, path?, colour_space?, texture_key?}` deep-merges a partial slot (with `path` a texture reference is added in the same step) and merges per (material, input) while dragging when no path is given. `material.clear_slot` and `material.set_graph` complete the set; the level is Region when parts wear the material, else None. `texture.remove` and `scene.import` follow textures into slots and graph nodes. `scene.set_part_mesh {id, mesh, remove_unused = true}` points a part at another existing mesh (added with `mesh.add` first, so journal lines stay small and shared meshes can be targeted): id, name, material, transform, metadata, children, selection and outside references stay, the old mesh is removed when unused, level Full, never merges; refusals `wrong_kind`, `unknown_mesh`, `locked`. It lets re-import and retessellation keep part ids. The scene table now has 43 commands (39 in 0.4.0). + +### crates/fsh-scene · materials verification +- refers-to: crates/fsh-scene :: (crate) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +mat-core's check against a program built from the 0.4.0 tree: sample, spheres and product-white renders (160 by 90, 8 spp, 2 threads) byte-identical; every snapshot material constant with `base` equal to `surface_inputs` bit for bit; old `.fshot` files load and resave to identical bytes; 0.4.0 commands replay and a crashed 0.4.0 session recovers by its journal to the same document; all 18 types create, compile and round-trip; set_type keep and reset with undo; set_slot merges; document JSON keeps slots and graph. Procedurals' four preset graphs pass `validate_refs` and compile. `scene.set_part_mesh`: swapping a cube part to a sphere mesh kept its id and removed the unused cube mesh, undo brought both back, and the three refusals answered. `cargo clippy -p fsh-scene --all-targets -- -D warnings` clean, also for wasm32. + +### crates/fsh-scene/src/labels.rs, material.rs, command.rs, catalogue.rs, compile.rs · labels +- refers-to: src/labels.rs :: Label, Label::active, Label::frame, Label::consts, validate_labels, LABEL_FIELDS, check_label_fields, MaterialLabelAdd, MaterialLabelSet, MaterialLabelRef, MaterialLabelMove; src/material.rs :: Material::labels, MATERIAL_FIELDS; src/command.rs; src/catalogue.rs :: MERGEABLE, label_schema; src/compile.rs :: label_layers; fsh-materials/src/program.rs :: Op::Label, LABEL_ONE_SIDED; fsh-materials/src/interp.rs :: fold +- kind: decision +- logged: v0.6.0 · 2026-12-02 +A label is an image projected onto the part wearing the material, in that part's object space: `Label {id, name, texture, colour_space, origin, normal, up, size [w, h] m, rotation (radians about the normal), depth m, opacity, two_sided, visible, roughness?, metalness?}`. `Material.labels` is an ordered list left out of the JSON when empty (`MATERIAL_FIELDS` now has 7 entries), so older files encode to the same bytes; `texture_keys` and `map_textures` include label images, so `texture.remove` and `scene.import` follow labels with no further code; a type reset keeps labels like slots. Commands (undoable, Region level when parts wear the material): `material.label_add {key, label, index?, path?, colour_space?}` (ids are max + 1 within the material; `path` adds a texture reference), `material.label_set {key, id, label, path?}` (merges while dragging without `path`, merge key `key << 24 | id`), `material.label_remove`, `material.label_move {key, id, index}` (clamped); command partials refuse unknown fields, files stay lenient. Compiling: after slots and graph, each visible label with an image becomes opcode 24 `Label` on `Input 1` (object position) and `Input 4` (object normal), a `Tex` with clamp, trilinear and fallback (0, 0, 0, 0), and lerps: `a = tex.w * mask * opacity`, `base_color = lerp(base_color, tex, a)`, and roughness and metalness when the label sets them; later labels print over earlier ones; a material with no active label stays constant. The frame: right = up x normal so the image reads unmirrored from the front, rotation counter-clockwise seen from the front; consts are origin, right / width, up / height, normal / half depth. `MaterialCreate.material` became `Box<Material>` to keep the command enum within clippy's large-variant limit (JSON unchanged), and the library's apply boxes it too. Verification (labels): 86 checks, 0 failures: byte-identical files without labels, reload of labels, refusals, merge of four drags into one undo step, `texture.remove` and undo, `scene.import` remapping, opcode hand values (centre, edges, depth, one-sided facing, rotation, footprint), fold and evaluate agreeing; a labelled cube evaluated per face read upright on the front, nothing on the one-sided back, mirrored through on a two-sided back. The scene table now has 47 commands. + +### crates/fsh-scene/src/compile.rs, command.rs, catalogue.rs, primitives.rs · procedural normals, merging graphs, the cylinder cap +- refers-to: src/compile.rs (procedural arm); src/command.rs :: MaterialSetGraph::merge; src/catalogue.rs :: MERGEABLE; src/primitives.rs :: cylinder +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Procedural normal outputs: a procedural sees no frame, so linking flakes `normal` straight to a material normal gave a wrong normal. Any procedural output typed Normal is now encoded as `0.5 n + 0.5` and passed through `NormalMap` at strength 1 (two extra instructions, opcodes the GPU already runs), so it is right in every frame; checked on 64 by 64 grids in three tangent frames against the colour-through-normal_map route, maximum difference 0. Merging graphs: `material.set_graph {key, graph, merge?}` (`merge` defaults to false and is left out of the JSON when false): consecutive merging calls on one material are one undo step until `history.barrier` or any other command; undo restores the first graph, redo replays the last. It is opt-in because always merging would fold separate structural edits (add, link, delete) into one step; the graph editor now uses it for value drags instead of a history group. Primitives: measuring the uv frames showed plane and sphere (which write `1 - v`) right-handed like the box and the cylinder's sides, and only the cylinder's top cap mirrored (24 of 96 triangles), so that cap's v now runs the other way; flipping plane and sphere, as suggested earlier, would have mirrored them. The seven templates rendered byte-identically before and after; only the cylinder's uv0 changed. + ## fsh-io ### crates/fsh-io/src/gltf.rs, obj.rs, stl.rs, ply.rs · readers into the raw scene @@ -296,6 +435,96 @@ PNG, zlib/deflate, CRC-32, Adler-32 and base64 are written in-house (no png or f - logged: v0.2.0 · 2026-12-02 Not done: EXR reader, tangents, glTF texture transform, KHR_materials_volume values, variants; `write_glb` writes no textures and keeps scene units. `cargo check -p fsh-io` and clippy clean. The scratch program (/home/claude/targets/io/scratch) round-tripped a 3-mesh, 4-node scene through GLB, .gltf, OBJ+MTL, STL (binary and ASCII) and PLY (binary and ASCII) into `Editor::execute` and undo; escape.gltf gave `outside_folder`; about 2100 damage cases per model file and 1800 per picture format gave 0 panics. PNG decoded identically by PIL and libpng; HDR agreed with an independent decoder; EXR checked only by an independent parser. +### crates/fsh-io/src/lib.rs · nine formats, detect, probe +- refers-to: src/lib.rs :: ModelFormat (Gltf, Glb, Obj, Stl, Ply, ThreeMf, Fbx, Step, Iges), ModelFormat::ALL, from_extension, read_here, Format, detect, read_any, read_model_bytes, probe, Probe; src/clean.rs :: guess_unit, UnitGuess +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`ModelFormat` grew from five to nine members; `from_extension` knows gltf glb obj stl ply 3mf fbx step stp iges igs, and `detect(name, bytes)` (alias of `detect_model`) checks content first: 3MF is a ZIP holding a `.model` part, FBX the binary magic or `FBXHeaderExtension`, STEP `ISO-10303-21;`, IGES an `S` in column 73. `read_here()` is false for Step and Iges: `read_any` and `read_model_bytes` answer `IoError::Unsupported("STEP files are read by the CAD worker (fsh-cad), not by the mesh readers")` (code `unsupported`) and the engine sends those files to fsh-cad instead. On wasm32 FBX answers `Unsupported("FBX files are read by the desktop engine, not in the browser")`. `probe(path, &Watch) -> Probe {format, units_declared, units_guess, unit_guessed, up_axis, bounds (file units and axes), triangles, meshes, nodes, materials, warnings}` reads and cleans nothing into a document and is what `import.probe` answers for mesh formats. `guess_unit(diagonal) -> UnitGuess {unit, confidence, candidates}` keeps the 0.2.0 thresholds (diagonal under 0.5 metres, under 50 centimetres, else millimetres) and adds a confidence of 0.5 at a threshold rising to 0.95 one decade away, with candidate units that give a 5 mm to 20 m object, nearest to 25 cm first; a declared or given unit has confidence 1 and is never guessed. + +### crates/fsh-io/src/zip.rs, threemf.rs · the 3MF reader +- refers-to: src/zip.rs :: (module); src/threemf.rs :: read_3mf +- kind: decision +- logged: v0.6.0 · 2026-12-02 +XML goes through roxmltree 0.21 (MIT OR Apache-2.0) because a strict reader of our own (entities, namespaces, attribute normalisation) would be several hundred lines; DTDs are refused, and a model part that uses an undeclared namespace prefix (two of the consortium's own samples do) is parsed again with the prefix declared on the model element, with a warning. The ZIP reader is our own and in memory: end record search, ZIP64 sizes, stored and deflated members through the crate's inflate, sizes and offsets checked against the bytes, inflated size capped by the declared size and by 1032 times the compressed size, CRC-32 checked, encrypted members refused. Units come from the model's `unit` attribute (micron is read as millimetres with positions and translations scaled by 0.001; the default millimetre is always declared, so 3MF is never guessed); Z up. Build items and components (also across parts through the production extension's path) become nodes with their transforms; a component cycle, more than 64 levels or more than 2^20 nodes are refused; support and solidsupport objects are skipped with a warning. Each object is split per property bucket: a base material each (pbmetallic, pbspecular and translucent display properties map to metalness, roughness, transmission and IOR), a colour group as one flat material per colour when every corner agrees, otherwise one shared "Vertex colours" material, composite materials blended to vertex colours, texture groups with their UVs, multiproperties by their first layer with a warning. Objects used by several items share one mesh. Required extensions other than materials and production give a warning. Not read: slice, beam lattice, volumetric and boolean extensions. + +### crates/fsh-io/src/fbx.rs · the FBX reader on ufbx +- refers-to: src/fbx.rs :: read_fbx; native/crates/fsh-io/Cargo.toml :: ufbx (cfg(not(target_arch = "wasm32"))) +- kind: decision +- logged: v0.6.0 · 2026-12-02 +ufbx 0.11 (MIT OR Unlicense; a C library compiled by `cc`, linked into native builds only) loads with target axes right-handed Y up and space conversion ModifyGeometry, geometry transforms baked (helper nodes when instanced), memory limit 3 GiB, and an open callback that refuses every external file. The file's unit is kept and declared (mm, cm, m, in, ft; any other scale is converted to metres). One raw mesh per (mesh, material part, material), reused across nodes; corners deduplicated by attribute index; colours taken as sRGB and linearised. Lambert and Phong materials come from the classic maps (Phong exponent through `roughness_from_phong`, Lambert roughness 0.9), every other shader type from ufbx's PBR maps (roughness inverted when the file stores glossiness). Cameras, lights, skins, blend shapes and NURBS are reported in warnings, animation ignored. Not done: NURBS tessellation, skin and blend-shape evaluation, a real left-handed file was never tried. The ufbx crate package carries no licence file; its Cargo.toml says MIT OR Unlicense and the upstream repository's LICENSE gives MIT or public domain. + +### crates/fsh-io/src/triangulate.rs, obj.rs, ply.rs, stl.rs · polygons, groups and STL colours +- refers-to: src/triangulate.rs :: (module); src/obj.rs; src/ply.rs; src/stl.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Faces with more than three corners (OBJ, and PLY faces with in-range indices) are ear-clipped in the Newell best-fit plane with a fan as fallback; above 512 corners a fan is used outright, because ear clipping is cubic in the worst case. This replaces 0.2.0's fans, which could come out wrong on concave polygons. OBJ `o` and `g` groups now become child nodes with one part per `usemtl` material. Binary STL facet colours (VisCAM/SolidView and Materialise conventions) become vertex colours. Every reader polls the cancel flag (`Watch::poll(i)`). + +### crates/fsh-io/src/tangents.rs, raw.rs, convert.rs, glb_write.rs · tangents beside the meshes +- refers-to: src/tangents.rs :: (module); src/raw.rs :: RawScene::tangents, RawMesh::instance_of; src/convert.rs; src/glb_write.rs; src/clean.rs :: CleanOptions::generate_tangents +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Tangents are stored in `RawScene::tangents: Vec<Vec<Vec4>>`, indexed like the meshes, rather than as a new `RawMesh` field, because fsh-commands/src/export.rs builds `RawMesh` with a full struct literal. MikkTSpace through bevy_mikktspace 1 (Zlib AND (MIT OR Apache-2.0), pure Rust) runs only where a mesh has UVs and normals and no tangents of its own (`CleanOptions::generate_tangents`, default true), splitting vertices whose corners disagree; glTF TANGENT values are kept. `convert` copies them into `Mesh::tangents`. `RawMesh::instance_of` changed from `Option<(usize, Vec3)>` (a translation) to `Option<(usize, Mat4)>`, so instances may be rotated or mirrored; `write_glb` writes those children with a matrix. A producer that builds `RawMesh` by literal (fsh-cad) sets `instance_of: None`. + +### crates/fsh-io/src/clean.rs, convert.rs, watch.rs · instancing under rotation, vertex colours, report fields +- refers-to: src/clean.rs :: clean, CleanReport; src/convert.rs :: VERTEX_COLOURS_KEY, VERTEX_COLOURS_MULTIPLY; src/watch.rs :: Stage::Tangents, Watch::poll +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Instancing: meshes are relabelled to first-appearance vertex order; a candidate with the same triangle list, or with every triangle's winding reversed (a mirrored copy), is aligned by the centroid and an orthonormal frame built from three far-apart corresponding vertices, then every vertex must agree within 1e-5 of the size plus 2e-6 of the distance from the origin and every normal within 1e-3. The correspondence comes from the shared triangle list, so no principal-axis sign has to be guessed. Translation-only copies keep the old exact test; scaled copies are not instanced. Bounds stay exact under rotation. Normal smoothing clusters the faces around any vertex with more than 256 faces into at most 64 normal clusters (dot 0.9999). Vertex colours that are white everywhere are dropped; a part whose mesh keeps colours gets node metadata `material.vertex_colours = multiply`, because the document's `Material` has no field for it (a material field would replace the key). `CleanReport` gains `meshes_given_tangents`, `white_colours_dropped`, `meshes_with_vertex_colours`, `instances_turned`, `unit_declared`, `unit_confidence`, `unit_candidates`. `Stage::Tangents` is stage value 9, "tangents". + +### crates/fsh-io · reader verification +- refers-to: crates/fsh-io :: (crate) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +A throwaway program (/home/claude/t3/targets/imp-readers/check, outside the repo) ran detect, read, clean, conversion to `scene.import`, `Editor::execute` on a new document and a document JSON round trip on 94 files: 22 3MF Consortium samples (BSD 2-Clause), 8 Khronos glTF samples (CC0 and CC BY 4.0), 40 ufbx test files (MIT or Unlicense) and 24 own generated 3MF, FBX (ASCII, binary, zlib), OBJ, PLY and STL files, up to 977,202 triangles (grid.stl read 0.098 s, clean 0.670 s). Every file read except the deliberately broken ones, which failed with `malformed` or `invalid_data` (three ufbx NaN files, `badindex.3mf`, `cycle.3mf`). Fuzzing: 400 truncations, 1500 multi-bit flips and 375 four-byte stomps per file, over 40,000 cases plus 300 re-zipped packages with mutated model XML: 0 panics, no crash of the C library. Tangents were checked at every corner against dP/du, orthogonality, unit length and bitangent sign; instancing against an instancing-off run as point sets and through a GLB write and read back; normals of a 3000-segment sphere within 0.5 degrees; cancel at 100, 600 and 1500 ms on four large files. `cargo clippy -p fsh-io --all-targets -- -D warnings` clean; `cargo check -p fsh-io` and `-p fsh-wasm` for wasm32 pass. Cancel latency: there is no check inside ZIP inflate and roxmltree parsing (up to about 0.45 s on a 5 MB package) or inside one MikkTSpace call (about 0.2 s on 100k triangles). Not run: a real left-handed or very large FBX, any render of imported files. + +### crates/fsh-io/src/raw.rs, convert.rs, clean.rs · texture slots from the readers +- refers-to: src/raw.rs :: RawScene::extras, RawScene::images, RawMaterialExtra, RawSlot, RawImage, EMBEDDED_PREFIX, extra_mut, add_image, image_of; src/convert.rs :: ALPHA_CUTOFF_KEY; src/clean.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Readers now say how each texture drives a material input. `RawScene::extras: Vec<RawMaterialExtra>` (indexed like materials: `slots`, `specular_colour`, `coat_ior`, `sheen`, `attenuation`, `thin_walled`, `thin_film`, `abbe`, `anisotropy`, `alpha_cutoff`) and `RawScene::images: Vec<RawImage>` (images inside the file, named `#embedded:<i>`) are side tables rather than new fields on `RawMaterial` and `RawTexture`, because fsh-commands/src/export.rs and fsh-io/src/family/handoff.rs build those with full literals. A `RawSlot {input, texture, slot: TextureSlot}` carries fsh-scene's slot type. `convert` builds `Material.slots` (texture key filled in, the first slot per input wins, invalid slots dropped, slot textures added to `Material.textures`), applies the extension values to `SurfaceParams`, and marks parts with masked materials with `material.alpha_cutoff`. `clean` trims the extras to the material count and drops slots naming missing textures or inputs that take no slot. + +### crates/fsh-io · the v-up uv convention +- refers-to: src/gltf.rs :: TEXCOORD reading, gltf_texture_transform; src/glb_write.rs; src/ply.rs; src/obj.rs; src/tangents.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Every reader stores uvs with v pointing up: origin at the image's bottom left, row 0 of an image at v = 1, which is what the texture lookup of docs/MATERIALS.md reads. glTF TEXCOORD_n is stored as (u, 1 - v) and `write_glb` writes (u, 1 - v) back; OBJ, PLY, FBX and 3MF are v up in their files and are no longer flipped. Removed from the PLY reader: `uv.push(Vec2::new(g(tu), 1.0 - g(tv)));` became `uv.push(Vec2::new(g(tu), g(tv)));`, and from the OBJ reader `tex.push(Vec2::new(u, 1.0 - v));` became `tex.push(Vec2::new(u, v));`. glTF TANGENT w is kept as given: on NormalTangentMirrorTest (15,720 corners) and NormalTangentTest (23,322 corners) every file tangent lies along dP/du and every bitangent along dP/dv of the stored v-up uvs, and MikkTSpace on the stored uvs passes the same check on 100 % of corners. KHR_texture_transform is re-expressed on v-up uvs as F o T o F with F(u, v) = (u, 1 - v): rotation r, scale s, offset `(ox + sy sin r, 1 - oy - sy cos r)` (`gltf_texture_transform`), equal to glTF's lookup within 6e-8 on TextureTransformTest. Not changed here: fsh-scene's primitives (plane and sphere write 1 - v, box and cylinder write v as is; the polish pass measured these as all right-handed except the cylinder's top cap, which it fixed), and documents saved before this change hold imported uvs with v down. + +### crates/fsh-io/src/gltf.rs · glTF materials to slots and parameters +- refers-to: src/gltf.rs :: read_material, gltf_texture_transform +- kind: decision +- logged: v0.6.0 · 2026-12-02 +baseColorTexture to `base_color` (rgb, sRGB, multiply by the factor); metallicRoughnessTexture to `specular_roughness` (channel g) and `base_metalness` (channel b), data, multiply; normalTexture to `normal`, data, strength = `scale`; emissiveTexture to `emission_color`, sRGB, multiply, emissiveFactor times KHR_materials_emissive_strength giving colour and luminance (100 nits per unit); occlusionTexture recorded on the material only. BLEND and MASK add `geometry_opacity` from the base colour texture's alpha (multiply, sRGB space so one image entry serves both); MASK without a texture is 1 or 0 against the cutoff, and the cutoff is kept in `material.alpha_cutoff`; a textured MASK material now also gets a hard cutoff graph (convert.rs `cutoff_graph`, logged below). texCoord (and the transform's override) set the uv set; samplers map wrapS to repeat, clamp or mirror (a different wrapT gives a warning) and the filters to nearest, bilinear or trilinear. Extensions: clearcoat (weight, roughness, coat_ior 1.5, its two textures as slots; the clearcoat normal recorded only), transmission (thin walled unless KHR_materials_volume has thickness), ior, specular (weight, colour clamped to 1, the specular texture's alpha as a slot), sheen (fuzz weight from the colour's peak), volume (attenuation colour and distance to transmission colour and depth), iridescence (thin film; thickness the maximum, or the mean of minimum and maximum with a thickness texture, in micrometres), dispersion (Abbe 20 / d clamped 1..200, scale 1), anisotropy (strength only). Unmapped textures give one warning per material. Images without a PNG or JPEG fallback (KHR_texture_basisu, EXT_texture_webp) are skipped. + +### crates/fsh-io/src/obj.rs, threemf.rs, fbx.rs · MTL, 3MF and FBX maps to slots +- refers-to: src/obj.rs :: map_options, png_has_alpha, has_alpha; src/threemf.rs; src/fbx.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +MTL: map_Kd to `base_color` (replacing Kd, no multiply, since Blender writes Kd 0.8 beside its maps), map_Ks to `specular_weight`, map_Ns to `specular_roughness` inverted, map_Pr to `specular_roughness`, map_Pm to `base_metalness`, bump to `bump` (0.001 m times -bm), norm or map_Kn to `normal`, map_d to `geometry_opacity` (alpha when the PNG has an alpha channel, else luminance), map_Ke to `emission_color` (Ke set to 1 when black), disp to `displacement` (0.01 m); options -o, -s, -clamp, -bm and -imfchan are read, others skipped with their arguments, and the rest of the line is the file name with its spaces. 3MF: texture2d parts are read from the package (up to 256 MiB) as images; tilestyleu sets the wrap (none becomes clamp), the filter maps auto, linear and nearest to trilinear, bilinear and nearest; one `base_color` slot over the tex2coord uvs. FBX: base colour or diffuse, roughness or glossiness (inverted), metalness, normal map, emission, specular to `specular_weight`, bump only without a normal map (0.001 m times BumpFactor), displacement (0.01 m times DisplacementFactor), opacity (transparency inverted unless the PNG carries alpha); UV sets by name (an unknown name falls back to set 0 with a warning, sets above 3 are clamped), `uv_to_texture` decomposed into rotation, scale and offset (a sheared matrix gives a warning); embedded content becomes an image once per texture element (`ignore_embedded: false`). Inputs that take no slot (transmission, specular colour, sheen, clearcoat normal, thickness, iridescence, anisotropy) keep their textures on the material without driving anything. + +### crates/fsh-io/src/family/ · hand-offs from the other Form apps +- refers-to: src/family/mod.rs; src/family/app.rs :: FamilyApp, Origin, origin_of; src/family/gof.rs :: read_gof, is_gof_folder, GofManifest, GofEntry, GOF_MANIFEST, GOF_TARGETS; src/family/maps.rs :: read_maps, MapRef, texture_sets, template_of, set_name, role_name, MAP_EXTENSIONS; src/family/surface.rs :: read_surface, is_formsurface_obj, SurfaceExport; src/family/handoff.rs :: inspect, Inspection +- kind: decision +- logged: v0.6.0 · 2026-12-02 +No family app sends anything to FormShot by name; the family's one hand-off format is GoF, FormSculpt's watched folder (`FORMSCULPT_GOF`, else `Formsculpt/GoF` in the home folder) with a manifest `gof.json` (`gof` 1, `app`, `up_axis`, `mm_per_unit`, `objects` each with `id, name, file, format, target, revision, vertices, triangles, sent, returns, units, scale`), which FormFabric also writes into. FormSurface writes map folders `<data>/exports/<stem>/<stem>_<map>.<ext>` (its own names and twelve templates, texture sets as `<material>_`, UDIM tiles as `.<udim>`) and an OBJ whose first line is `# FormSurface`. FormCAD writes GLB with `asset.generator` "FormCAD" and `extras` `{title, sourceUnit: "mm"}`, and 3MF with `Application` metadata. So the module reads, without any new association or URL scheme: `origin_of(path, bytes)` (the writer from the glTF generator and extras, the OBJ first comment, the 3MF metadata through a small central-directory reader), `read_gof` (entries whose target is `any` or `formshot`; `newest()` prefers those with the file present), `read_maps` (FormSurface's own names and every built-in template's suffixes to `MapRef {path, file, map, source, role, colour_space, uv_set, texture_set, udim, format}`), `read_surface` (maps named after the folder, the OBJ beside them, else `<data>/meshes/<stem>.{glb,gltf,obj,fbx}`) and `inspect(path, item) -> Inspection` with kinds `model`, `map_folder` and `gof_folder`, `read(watch) -> RawScene`, `metadata()`, `declared_unit()`, `materials_only()`, `maps()`, `to_json()`. Map roles: base colour, diffuse, albedo and BaseMap to `base_colour` (sRGB; linear in EXR and HDR), roughness, metallic to `metalness`, height and displacement to `bump`, normal, glTF, Unreal and Godot ORM to `occlusion_roughness_metalness`, opacity, emissive to `emission`; AO, curvature, thickness, position, world normal, MaskMap, MetallicSmoothness, Specular and Glossiness to `other`. What `other` and DirectX normals are is kept in node metadata `source.maps` (`source: "normal_dx"` and so on) because `TextureRef` has no field for it. FormFabric's percent-encoded absolute image URIs are decoded. Not done: 32-bit TIFF and PSD maps are marked sRGB (the bit depth is not read); custom FormSurface file-name templates are matched by known suffixes only; several UDIM tiles become separate textures of one role; FormSurface's OBJ carries no unit, so the clean-up guesses. + +### crates/fsh-io/src/family/ · verification +- refers-to: crates/fsh-io/src/family :: (module) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +Real exports in /home/claude/t3/targets/handoff/corpus (outside the repo): FormSculpt's own engine wrote a GoF folder (Quad_sphere.glb for formsurface, Quad_sphere.obj for any, Torus.glb for blender, gof.json); FormFabric's own `formfabric.gof.send` merged Wrap_dress.glb (app formfabric, id 2000000), with a stand-in client writing a GLB shaped like ffb-io's writer; FormCAD's own `write_glb` and `write_3mf` wrote bracket.glb and bracket.3mf; three FormSurface folders were written by hand from the evidence (own names with the OBJ, the unreal template with two texture sets and UDIM 1001 and 1002, EXR glTF-template maps without a mesh). Through the release CLI `handoff.inspect` named the right app, kind, title, template, texture sets, roles and counts for all seven, and `handoff.open` of six succeeded with 21 texture references carrying roles and colour spaces. `cargo clippy -p fsh-io -p fsh-commands --all-targets -- -D warnings` clean. No family app ran as a live sender to a live FormShot desktop build. + +### crates/fsh-io/src/jpeg.rs, picture.rs · one image decoder for textures +- refers-to: src/jpeg.rs :: read_jpeg, is_jpeg, JPEG_MAX_SIDE; src/picture.rs :: decode_image, detect_image, DecodedImage, ImageFormat, ImagePixels, half_to_f32; native/crates/fsh-io/Cargo.toml :: zune-jpeg +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Textures arrive as PNG (8 and 16 bit), JPEG, Radiance HDR and OpenEXR, and every decode goes through `decode_image(name, bytes) -> DecodedImage {width, height, format, channels, pixels: Rgba8 | Rgba16 | RgbaF32}`: the engine's loader, the window's texture worker (fsh-wasm) and the checks all call it. JPEG uses zune-jpeg 0.5 (resolved 0.5.15 with zune-core 0.5.4, `MIT OR Apache-2.0 OR Zlib`; builds for wasm32), the one dependency the texture work added, because a baseline and progressive decoder of our own would be large; greyscale stays one channel, YCbCr, RGB, CMYK and YCCK come out RGB, EXIF orientation is ignored, sides above 16384 are refused (`JPEG_MAX_SIDE`). OpenEXR is read in-house: single-part scanline files, compression NONE, RLE, ZIPS, ZIP, PIZ and PXR24, HALF, FLOAT and UINT channels, R G B A or Y, also `layer.R` names; tiled, deep, multi-part, B44 and DWA files answer `unsupported`. Verification (tex-cpu): JPEG against libjpeg through PIL, baseline, progressive, 4:2:0, grey and CMYK within 4 levels (mean under 0.45); EXR against the OpenEXR 3.5.5 library for every supported compression in half and float, and three of the library's sample images, bit-identical; B44 reports unsupported; 2000 damaged JPEGs and 1500 damaged files per EXR compression gave 0 panics. The environment loader in engine.rs read Radiance only at first; it now goes through `textures::environment_image` and reads EXR too (QA pass). + +### crates/fsh-io/src/convert.rs · a hard alpha cutoff for glTF MASK materials +- refers-to: src/convert.rs :: cutoff_graph, ALPHA_CUTOFF_KEY +- kind: decision +- logged: v0.6.0 · 2026-12-02 +glTF MASK materials whose alpha comes from a texture rendered as soft coverage. `convert` now gives such a material a graph that drives `geometry_opacity` with `clamp((alpha * factor - cutoff + 1e-4) * 1e4, 0, 1)` from a texture node built from the slot (same texture, projection, transform and wrap), so coverage is 0 or 1 at the cutoff in both tracers without a new opcode; `material.alpha_cutoff` stays on the parts. On AlphaBlendModeTest the cutoff panels now cut exactly at their arrows in CPU and GPU pictures (QA pass). + ## fsh-format ### crates/fsh-format/src/project.rs, zip.rs · the .fshot file 1.0.0 @@ -322,6 +551,80 @@ One directory per session with a held lock, the origin document, journal.jsonl a - logged: v0.3.0 · 2026-12-02 `std::process::id()` and `SystemTime::now()` trap on wasm32, and `atomic_write` and the session journal called them. Both now go through platform.rs: `process_id()` (0 on wasm32), `now_ms()` (the host's wall clock once `set_wall_clock(fn() -> u64)` installs one, else 0 on wasm32). On wasm32 `atomic_write`, `load_file`, `Session::start` and `recover` answer "this build has no file system" instead of panicking; in-memory `save_bytes` and `load_bytes` work unchanged. Verified with `cargo check --target wasm32-unknown-unknown -p fsh-format` and `-p fsh-wasm`, and a Node probe of a wasm32 build: the four calls returned that error, a save and load round trip of 1,752 bytes matched, and the control `std::process::id()` trapped. Natively a killed engine's session was listed by `recover_list` with its real start time and pid. `lib.rs` allows `clippy::drop_non_drop` on wasm32 only (File has no Drop there). +### crates/fsh-format/src/project.rs, lib.rs · kept CAD sources under sources/ +- refers-to: src/project.rs :: Project::keep_source, source_bytes, prune_sources, source_member, check_source_member, SOURCES_PREFIX, MAX_SOURCE_BYTES, Preserved::sources +- kind: decision +- logged: v0.6.0 · 2026-12-02 +A STEP or IGES file imported through fsh-cad is kept inside the project so `scene.retessellate` works after the original is moved or deleted: `Project::keep_source(bytes, ext)` answers `fshot:sources/<16 hex digits of FNV-1a 64>.<ext>` and refuses files above 64 MiB (`MAX_SOURCE_BYTES`; such a file stays referenced by its path). Storage is the new field `Preserved::sources`, not a `Project` field, because every `Project {..}` literal in fsh-commands' engine.rs would have broken and engine.rs already carries `preserved` through `file.save` and `file.snapshot`. The manifest gains a `sources` list, written only when non-empty, and the members are written after the textures and before `preview.png`; loading checks the name, the size and that the content hash matches the name. No format version change: saves without sources are byte-identical to 0.4.0's, and the 0.4.0 reader keeps a source member through its own resave as an unknown member. Kept sources are not dropped from the session when an import is undone, since undo could bring the nodes back; since the polish pass a save writes only the sources some node names (`referenced_sources`, logged below). + +### crates/fsh-format/src/project.rs, sha256.rs · texture members named by SHA-256 +- refers-to: src/sha256.rs :: sha256, sha256_hex; src/project.rs :: texture_member, TEXTURES_PREFIX, MAX_EMBED_TEXTURE_BYTES, Project::embed_texture +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Embedded textures are now written as `textures/<first 32 hex digits of SHA-256>.<ext>` (`texture_member(bytes, ext)`); `embed_texture` uses that name and refuses images above 256 MiB (`MAX_EMBED_TEXTURE_BYTES`). Loading accepts both the new name, checked by SHA-256, and the 0.2.0 name `<fnv64>-<length>`, checked as before, so older projects open and resave byte-identical. SHA-256 is written in-house (FIPS 180-4) rather than adding a hashing crate; it equals `sha256sum` on 13 files of 0 to 100,000 bytes. Engines older than this change refuse a file holding the new member names ("is not named <hash>-<length>"); files without textures are unaffected. The material member's known fields come from `fsh_scene::MATERIAL_FIELDS` (`let mat_known = ... MATERIAL_FIELDS ...` replaced `keys_of(&Material::default())`, which no longer named `slots` and `graph`), so slots and graphs reload as live fields instead of preserved unknowns. + +### crates/fsh-format/src/session.rs · sources in the crash journal +- refers-to: src/session.rs :: Session::keep_sources, Session::start, Recovered::sources +- kind: decision +- logged: v0.6.0 · 2026-12-02 +A session folder holds kept CAD sources as files `sources/<hash>.<ext>`, written once each with the same name and hash check as project members; origins and snapshots are unchanged. `Session::start` copies the project's sources in, `keep_sources` adds new ones, and recovery reads the folder into `Recovered::sources` (a damaged copy is left out with a note), which fsh-commands puts back into `Preserved::sources`. Embedded textures reach the journal the existing way: the import code hands the session the textures and writes a snapshot when a new member arrived and no history group is open (restarting the journal instead left a zero-command session that recovery deletes, losing the import). + +### crates/fsh-format · verification of sources and texture names +- refers-to: crates/fsh-format :: (crate) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +Against the 0.4.0 writer copied out of git: saves without sources were byte-identical; base files resaved identically; the 0.4.0 reader kept a source member through its own resave; a 65 MiB source and a damaged member were refused. A gearbox STEP import saved, reopened and resaved byte-identically with the source member equal to the STEP. Texture names: projects with glTF (11 models), OBJ, 3MF and FBX textures saved, were copied to a fresh folder, reopened by a new engine with every `fshot:` texture present, and resaved identically; an old-style project with a `<fnv>-<len>` member and a slot loaded and resaved byte-identically. Crash journal: an engine killed after a CAD import and a rename recovered by journal (5 entries, undo depth 2) with the STEP deleted, and retessellation worked from the recovered source; an engine killed after importing a textured GLB and an OBJ recovered with every member. `cargo check --target wasm32-unknown-unknown -p fsh-format` passes. + +### crates/fsh-format/src/project.rs · a save writes only referenced sources and keeps the environment's member +- refers-to: src/project.rs :: referenced_sources, encode, prune_sources +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`referenced_sources(&Document)` collects the `fshot:sources/...` names that some node's `source.cad` metadata holds, and `encode` writes only those `sources/` members (and lists only those in the manifest). Pruning happens in the writer rather than on the kept project, so the session can still bring a source back when an undo restores its parts (imp-cad's reason for never pruning); `prune_sources` uses the same helper and is still unused. Run (polish): saves after an import, its removal, undo and redo held 1, 0, 1 and 0 source members, and the reopened undo save re-tessellated. `encode` also keeps the `textures/` member that an embedded environment image names (`environment.source.path = "fshot:textures/..."`), which is not a material texture and would otherwise be dropped (QA pass). + +## fsh-cad + +### crates/fsh-cad · a client of FormCAD's kernel worker +- refers-to: native/Cargo.toml :: members; crates/fsh-cad/Cargo.toml; src/lib.rs; src/error.rs :: CadError, CadError::code +- kind: decision +- logged: v0.6.0 · 2026-12-02 +STEP and IGES are read by FormCAD's kernel worker (OpenCascade 8.0.1 behind a JSON-lines protocol), run as a child process, rather than by a CAD kernel linked into the engine. The crate depends on fsh-core, fsh-io and serde_json only (no new external dependency), produces an `fsh_io::RawScene` so the clean-up pass and `scene.import` are shared with every other format, reports progress and honours cancel through `fsh_io::Watch`, and is a native-only dependency of fsh-commands (it is not in the wasm32 tree). Errors are `CadError` (Missing, Start, Exited, Timeout, Protocol, Worker, File, Cancelled) with `code()` and `From<CadError> for fsh_io::IoError`. The engine never downloads the worker: the service or `./formshot cad fetch` does, and checks it. + +### crates/fsh-cad/src/locate.rs, client.rs · finding and talking to the worker +- refers-to: src/locate.rs :: locate, Located, cache_dir, workers_dir, installed; src/client.rs :: Worker::start, Worker::call, Worker::hello, Worker::shutdown, PROTOCOL +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Search order: `FORMSHOT_CAD_WORKER` (a program, or a `.py` script run with the `venv` python beside it, else python3), then `formcad-kernel[.exe]` beside the running executable, then the newest tag folder (numeric sort) under `<cache>/formshot/workers/<tag>/formcad-kernel`. The cache is `FORMSHOT_CACHE`, else `$XDG_CACHE_HOME` or `~/.cache` (Linux), `~/Library/Caches` (macOS), `%LOCALAPPDATA%` (Windows); the service and the script use the same rules. The client writes `{"id", "method", "params"}` lines and reads `{"id", "result"}` or `{"id", "error": {"message"}}`; replies with another id and lines that are not JSON are skipped, as FormCAD does. `hello` must answer `protocol: 2` (`PROTOCOL`; a missing number is accepted as an older worker). Timeouts: `FORMSHOT_CAD_TIMEOUT` seconds per request (default 600) and for hello `FORMSHOT_CAD_HELLO_TIMEOUT` (default 120 s since the polish pass; it was a fixed 90 s, which cold starts on a loaded machine passed). On cancel or timeout the child is killed; its stderr tail is quoted in errors. The worker sends no progress, so progress is reading 0 at start, 0.02 after hello, 0.1 after the open, then 0.1 + 0.9 * body / bodies. + +### crates/fsh-cad/src/mesh.rs, quality.rs · tessellation files and quality +- refers-to: src/mesh.rs :: parse; src/quality.rs :: Quality, from_json, to_json, to_text, from_text, deflection, custom +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`tessellate {id, linear, angular, path}` writes a `.mesh` file: an 18-word header (magic FCBM 0x4D424346, version 1, vertex, triangle, face, edge and edge-point and snap counts, 8 section offsets, total bytes, CRC-32 of the body), a 6-float bounding box (96 bytes in all), then float32 positions and normals, u32 indices, a face index per triangle and a face table `{face, first, count, kind}`; edges and snaps are not read. Above 4M triangles the worker answers "too fine" and fsh-cad retries with the linear deflection times 4, at most twice, with a warning. Quality presets are our own choices from measured results; chord is the largest triangle-to-surface distance as a fraction of the model's bounding-box diagonal, sent as `linear` in mm with a floor of 1e-4 mm, and angle is in degrees, sent in radians: draft 0.002 and 30, medium (default) 0.0005 and 20, high 0.00015 and 12, ultra 0.00005 and 6, custom `{chord, angle}` with 0 < chord <= 0.1 and angle 1..90. Node metadata stores the quality as text: the preset name or `chord,angle`. + +### crates/fsh-cad/src/read.rs · bodies, colours and shared shapes +- refers-to: src/read.rs :: read, ReadOptions, CadRead, MeshTag, Body, CadFormat::detect, is_cad_path +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`read(path, &ReadOptions{quality, timeout, hello_timeout, worker}, &Watch)` opens the file with `xde_read {path, unit: "mm", pmi: false}` (older workers: `open_step`, `open_iges`), tessellates each body, and answers `CadRead {scene, tags, node_body, bodies, shared, format, diagonal_mm, linear_mm, angular_rad, occt, tag}`: a RawScene in metres, `unit = Metre`, `up_axis = Z`, assembly groups with identity transforms, body nodes carrying world placement, one RawMaterial per colour (the worker's `rgb` is linear), and one `MeshTag {body, slot}` per mesh. Bodies sharing a `def` label are tested for sharing: the affine map from four well-spread corresponding vertices of the two tessellations is solved and every vertex checked within a tolerance; if it holds the second body becomes the first body's mesh plus a node transform (the gearbox's four bolts share one mesh). A per-body `face_rgb` list, when a worker sends one, splits a body into one mesh per colour. Instancing in the clean pass stays off for CAD so the tags remain one per mesh. + +### crates/fsh-cad/src/scan.rs, probe.rs · what the file says without the worker +- refers-to: src/scan.rs :: step, iges, step_face_colours, Header, IgesSolid, StepSolid; src/probe.rs :: probe +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The worker (formcad_kernel.py and kernel_xde.py in FormCAD) reports no progress, no face colours, no colours or names for IGES bodies (they come back as "<root> N" with `rgb: null`) and no instance matrices; these are asks for FormCAD's owner, and FormCAD was not edited. fsh-cad fills two gaps from the file itself. IGES: manifold solids (entity 186) in directory order with their colour (standard numbers 1 to 8 or a 314 definition, percent sRGB, linearised) and name (406 form 15, else the directory label), applied only when the solid count equals the body count, else a warning. STEP: STYLED_ITEM and OVER_RIDING_STYLED_ITEM on ADVANCED_FACE and FACE_SURFACE followed to COLOUR_RGB (sRGB, linearised) or a pre-defined colour name, listed per MANIFOLD_SOLID_BREP outer shell in shell order (the order the worker numbers faces); each body takes the face colours of the one solid with its face count, otherwise keeps its body colour with a warning; files above 256 MiB are not scanned; inner shells are not read. `probe(path, &ReadOptions, use_worker, &Watch)` reads the header (schema, name, writing system, declared unit, entity counts) and, with the worker, `xde_read` only (no tessellation): bodies, groups, faces, distinct shapes, colours in the file and the OCCT version; without the worker it answers the header with `worker: false` and the reason. + +### crates/fsh-cad · verification +- refers-to: crates/fsh-cad :: (crate) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +With the real worker occt-8.0.1 for x86_64 Linux (7061 files, 1002 MB unpacked, fetched and verified by `setup/cad_worker fetch`; hello in 1.9 s): a gearbox STEP written by the worker's own `xde_write` gave 11 nodes, 4 colours and 4 bolts on 1 mesh, at 1802, 5388, 16192 and 53090 triangles for draft, medium, high and ultra (2 to 3 s each, mostly worker start); its IGES twin gave 8 flat bodies with no colour before scan.rs existed; afterwards a second sample, gearbox_a.iges, imported as Housing, Shaft, Bolt 1 to 4 and Knob with materials #7C95CB, #DADADD, #595959 and #E75959, 3 parts shared. MIT samples from mikedh/trimesh at 28802bd: featuretype.STEP 2276 to 17158 triangles; box_sides.STEP 10 bodies, 4 shared; two_color_cube.STEP read as two meshes, red and blue, after scan.rs; two_color_lines.STEP refused ("its one body is curves or points only"). A fine read (68,348 triangles, 5.4 s) cancelled at 1.8 s ended in 2.2 s with no worker process left; `FORMSHOT_CAD_TIMEOUT=1` gave `cad_worker_timeout` and killed the worker. A stand-in worker produced garbage lines, wrong ids, a damaged mesh, a crash, a missing result, a non-list of bodies, protocol 3, a slow answer and a cancel, each refused by name. `cargo clippy -p fsh-cad --all-targets -- -D warnings` clean. Not run: macOS and Windows (the `.exe` and `%LOCALAPPDATA%` paths are untested); progress inside one body's tessellation does not exist. + +### crates/fsh-cad/src/read.rs, lib.rs · FORMSHOT_CAD_HELLO_TIMEOUT +- refers-to: src/read.rs :: HELLO_TIMEOUT_ENV, HELLO_TIMEOUT_SECS, hello_timeout, ReadOptions::default +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Cold worker starts on a loaded machine passed the fixed 90 s hello wait several times (cad-ui's runs). `hello_timeout()` reads `FORMSHOT_CAD_HELLO_TIMEOUT` (positive integer seconds) and defaults to 120 (`HELLO_TIMEOUT_SECS`); every worker start uses it: reads, probes and the `cad.status` probe. Run with a silent fake worker: with 3 and 7 the import and `cad.status` stopped after 3 s and 7 s, and the real worker still answered. The 120 s default itself was not timed. + ## fsh-render-cpu ### crates/fsh-render-cpu/src/integrator.rs, lights.rs · the path tracer @@ -372,6 +675,24 @@ Instances whose emission times opacity is not black and which every indirect ray - logged: v0.3.0 · 2026-12-02 Release program outside the repo, 2-core shared box. Sample scene 240x160 at 8 spp: float buffers bit-identical for `Pooled(1)`, `Pooled(2)` and `Inline`, denoised develop identical too, sample-scene hash 103ecc3c0cc449f3 unchanged across every commit. Adaptive at 64 requested spp: 58.3% of pixels retired, mean 38.9 spp, mean absolute difference to a 512 spp reference 0.00653 against 0.00781 for uniform 39 spp. Region reset: 35094 of 35094 outside pixels kept their bits and 3306 of 3306 inside were cleared; `update_materials` took 0.003 ms. Emissive scene (962 emitting triangles): NEE with MIS and BSDF-only references agree on mean luminance (0.08538 against 0.08525); variance over 8 seeds at 16 spp 3.36e-3 with MIS against 1.08e-2 without. Interaction at 480x320: a 1-spp pass 629 ms at scale 1, 176 ms at 0.5, 54 ms at 0.25. wasm32: `cargo check` and clippy pass; a cdylib probe under node 22 trapped in fsh-materials' threaded table build until that loop was made serial, then rendered 60x40 at 2 spp in 1.56 s with bits differing from native (libm differs). Clippy: 0 warnings for the crate (19 before). Not in the CPU path either: textures, IES, light tree, volumes, cutaways, caustics through the catcher. +### crates/fsh-render-cpu/src/geometry.rs, integrator.rs, emissive.rs, renderer.rs · material programs at hits +- refers-to: src/geometry.rs :: instance_inputs, instance_program, InstanceData::program, Geometry::hit_context, Geometry::shade, uv_derivatives; src/integrator.rs :: CONE_MIN_COS, cone_widening; src/emissive.rs; src/camera.rs; src/renderer.rs :: Renderer::set_textures, Renderer::textures +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Constant materials take their inputs from `program.base` and then the part tint (replace `base_color`, sanitise again), as the GPU builds them (commit b902a15 moved this from `surface_inputs(params)`; they differ only when a slot or graph folds into the base, and the contract says base); renders of every template are byte-identical to the 0.4.0 engine with and without tints. A non-constant material keeps its `Arc<Program>` on the instance; at a hit `Geometry::hit_context` builds the `HitContext`: object position from the mesh corners, object normal from interpolated normals or the triangle normal, uv sets with one entry per vertex (contiguous from set 0, up to 4) read as stored, dP/du and dP/dv from uv set 0 by the triangle solve (an orthonormal frame around ns when the mapping is missing or `|det| < 1e-12`), the mesh tangent interpolated, transformed and made orthogonal to ns, its sign negated on mirroring instances. `Geometry::shade` runs `Program::evaluate` with the renderer's `TextureSet` and then the tint; its normal is the BSDF frame's and the first-hit normal AOV's; eta is `Bsdf::relative_ior` of the evaluated inputs. The anisotropy tangent of the frame stays zero, as before. Emissive light selection still weighs triangles by the constant emission, but a sampled point on a programmed emitter evaluates the program (footprint 0), so textured emission agrees between light samples and hits. Footprints are ray cones (Akenine-Moller et al., Ray Tracing Gems ch. 20): perspective spread `atan(2 tan_y / film_h)`, orthographic width `2 half_h / film_h`, width grows by spread times distance per segment (opacity pass-through and the catcher mirror included), footprint `|width + spread * distance| / max(|ng . dir|, 0.05)`, and after a bounce spread grows by `2 r^2` with r = 1 for diffuse lobes, the specular roughness for glossy ones and 0 for delta lobes; no curvature term. `Renderer::set_textures(Option<TextureSet>)` resets accumulation. Verification (tex-cpu): eight template renders and a five-tint sample byte-identical to the 0.4.0 engine; BoxTextured, TextureCoordinateTest, TextureTransformTest, AlphaBlendModeTest and NormalTangentMirrorTest pictures looked at and in place; bump from a height map and a normal map computed from the same heights shade alike (mean 0.03 of 255). A tilted normal map on flat geometry can send mirror reflections below the geometric surface, which the BSDF rejects, so smooth metals show a dark rim there. + +### crates/fsh-render-cpu/src/geometry.rs, integrator.rs, spec.rs · thin film and dispersion, and where they meet programs +- refers-to: src/geometry.rs :: surface_optics, instance_optics, InstanceData::optics; src/integrator.rs; src/spec.rs :: DRAW_ORDER; fsh-materials :: Bsdf::new_optics, dispersion_channel +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Each instance carries `optics: Optics` from its material's `params` (`surface_optics`) beside its program; optics are never driven by programs. The integration of the texture and optics work fixed the order at a hit: first the shaded inputs (the program's when the instance has one, with the cone footprint, else the constant inputs) and its eta; then roughness regularisation and the opacity pass-through; then, for a dispersive, transmissive, not thin-walled instance, the hero channel from `DIM_WAVELENGTH` shifts the evaluated `specular_ior` to `n_c` (so a textured ior still disperses) and sets eta; then the BSDF is built with `Bsdf::new_optics` when the instance has a film, else `Bsdf::new`. `spec::DRAW_ORDER` lists the dispersion channel draw. Verification (optics): every template and a scene of four library glass, water and acrylic presets render byte-identically to the 0.4.0 engine at each step (12 of 12 files); pictures of soap bubbles, the six anodised titanium and two pearl presets, an SF11 prism (three slit images) and a diamond (coloured fire) looked at. + +### crates/fsh-render-cpu/src/integrator.rs · clamping bent normals +- refers-to: src/integrator.rs :: clamp_bent_normal +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Steep normal or bump maps sent mirror directions below the geometric surface, which the BSDF rejects, so polished metals showed black rims (NormalTangentMirrorTest's gold columns). A normal that a material program changed is now bent towards the geometric normal (facing the viewer) just enough that the mirror reflection of the view direction stays 0.01 above the horizon, after Keller et al. 2017 (the technique used in Iray). Normals no program touched are left alone, so the templates stay byte-identical. The GPU integrator has the same function. + ## fsh-commands ### crates/fsh-commands/src/catalogue.rs, alias.rs · one catalogue, one alias table @@ -452,6 +773,211 @@ Release CLI. `devices` without an ICD: cpu and gpu:0 (GL, llvmpipe); with lavapi - logged: v0.3.0 · 2026-12-02 Render jobs: the session numbers each full restart (a new renderer, a full-film reset from an edit or camera move, a new preview size; not region resets or display changes), tags frames with the job, and resets the counters at once. `render.status` carries `job`; `render.frame` carries `job` and answers `png_base64: null` until the current job has a frame, so a client never shows the previous camera's picture (during an orbit on the CPU that is common, and the window keeps its last picture). `file.save` previews and `file.export_image` use the current job's frame only. `render.region {x, y, width, height}` (fractions 0..1) or `{clear: true}` answers render.status plus `ok`, `change: "none"` and `applied`; the region lives in the session and follows device and preview-size changes. The GPU preview applies it (and again after a snapshot changes the size); the CPU answers `applied: false` with `region_note` "render regions are not supported on this device yet (cpu)" and renders the whole image, because fsh-render-cpu has no public way to restrict passes to a rectangle. `render.status` gains `region {x, y, width, height, active} | null` and `region_note`. `Engine::revisions()` and `Engine::reply_meta()` give `{revision, content_revision}` for the dispatch transport, and the catalogue documents it in a top-level `envelope` section. The catalogue has 88 entries (render.region added). Verified through `formshot-engine dispatch`: after `render.start` 320x240, stop, `environment.set` and start, status read `job 2, samples 0` and frame null until the first new pass, on the CPU and on lavapipe (the old build reported the previous film's 5 samples and picture); with a region on gpu:0 the image converged to 32 samples in 0.8 s and the picture showed a clean band through the region, and after clear the whole film resumed and converged in 5.4 s. +### crates/fsh-commands/src/ext/mod.rs, engine.rs · command groups in their own modules +- refers-to: src/ext/mod.rs :: ExtCommand, commands, dispatch; src/engine.rs :: Engine::dispatch_value, State, Engine::changed, refresh_render, install_editor, import, clean_options, has_parts, title_from, frame_values; src/catalogue.rs :: catalogue_value +- kind: decision +- logged: v0.6.0 · 2026-12-02 +From 0.5.0 on, each new command group lives in one module under `src/ext/` (import, cad, handoff, materials, library), so several people could write groups at once without touching the same lines. A module lists `ExtCommand {name, description, level, mutates, read_only, schema}` entries in `pub(super) static COMMANDS` and answers its names in `dispatch`, returning `None` for any other. The modules were reserved as empty files before their owners started (the reserved-module pattern), so ownership was settled by path. `catalogue_value` appends `ext::commands()` after the engine commands. `dispatch_value` needed `|| crate::ext::commands().any(|c| c.name == name)` beside the `ENGINE_COMMANDS` test: without it every ext name answered `unknown_command`, because the `other => crate::ext::dispatch` arm was unreachable. engine.rs opened what the groups need as `pub(crate)`: `State` and its fields `editor`, `path`, `kept`, `revision`, `content`, `journal`, `jobs`; `State::note`, `note_begin`, `note_end`, `note_sources` (new); `Engine::changed`, `refresh_render`, `install_editor`, `import`; `clean_options`, `has_parts`, `title_from`, `frame_values`. `dispatch_value` also calls `crate::ext::import::pump(self, &mut st)` before every command, and `install_editor` calls `crate::ext::import::document_changed(st)`. The catalogue now holds 114 entries by count of the tables (43 document, 38 engine, 22 ext, 11 aliases); `./formshot agents sync` regenerates the tool reference. + +### crates/fsh-commands/src/engine.rs · Engine::import delegates +- refers-to: src/engine.rs :: Engine::import; src/ext/import.rs :: import_now; src/ext/import/run.rs :: prepare, apply +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`Engine::import` now sends CAD files to `crate::ext::cad::import` and everything else to `crate::ext::import::import_now`, whose `prepare` (read, clean, convert, merge, annotate, embed textures, without a document) and `apply` (one history group: the import, the root rename and framing, then `engine.changed`) split the old body so jobs can run `prepare` on a worker thread. The CAD branch must stay at the top. The `use fsh_io::{...}` line lost `ImportOptions` and `Watch`. The removed body, quoted in full: + +```rust + fn import(&self, st: &mut State, path: &Path, args: &Value, frame: Option<bool>) -> Result<Value> { + let empty = json!({}); + let opts = args.get("options").unwrap_or(&empty); + let clean = clean_options(opts)?; + let import = ImportOptions { parent: None, wrap_in_group: get_bool(opts, "wrap_in_group").unwrap_or(true) }; + let was_empty = !has_parts(st.editor.document()); + let (cmd, report) = fsh_io::import_file(path, st.editor.document(), &clean, &import, &Watch::new())?; + let label = format!("Import {}", get_str(args, "name").map(str::to_string).unwrap_or_else(|| title_from(path))); + st.editor.begin_group(&label); + st.note_begin(&label); + let result = (|| -> Result<Outcome> { + let out = st.editor.execute(cmd)?; + st.note(&out); + if let Some(name) = get_str(args, "name").filter(|n| !n.is_empty()) { + let stem = title_from(Path::new(name)); + let roots: Vec<u64> = out + .created + .iter() + .copied() + .filter(|k| st.editor.document().node(NodeId::from_raw(*k)).is_some_and(|n| n.parent.is_none() && n.name == title_from(path))) + .collect(); + for r in roots { + let renamed = st.editor.dispatch("scene.rename", json!({"id": r, "name": stem}))?; + st.note(&renamed); + } + } + if frame.unwrap_or(was_empty) { + if let Ok(values) = frame_values(st.editor.document(), 1.15) { + let index = st.editor.document().active_camera_index(); + let framed = st.editor.dispatch("camera.set", json!({"index": index, "values": values}))?; + st.note(&framed); + } + } + Ok(out) + })(); + let out = match result { + Ok(o) => { + st.editor.end_group()?; + st.note_end(); + o + } + Err(e) => { + if let Ok(back) = st.editor.abandon_group() { + st.note(&back); + } + return Err(e); + } + }; + let mut reply = self.changed(st, &Outcome { level: ChangeLevel::Full, ..out }, false); + reply["name"] = json!("file.import"); + reply["report"] = json!({ + "triangles_dropped": report.triangles_dropped, + "vertices_welded": report.vertices_welded, + "unused_vertices_removed": report.unused_vertices_removed, + "meshes_given_normals": report.meshes_given_normals, + "instances_found": report.instances_found, + "unit": report.unit.as_str(), + "unit_guessed": report.unit_guessed, + "up_axis": report.up_axis.as_str(), + "warnings": report.warnings, + }); + Ok(reply) + } +``` + +### crates/fsh-commands/src/ext/import.rs, import/options.rs, import/run.rs, import/source.rs · options and source tracking +- refers-to: src/ext/import.rs :: COMMANDS, file_import_schema, file_open_schema, import_now, pump, dispatch; src/ext/import/options.rs :: ImportArgs::parse, CadQuality, properties; src/ext/import/run.rs :: prepare, apply, merge_under_group, payload_max_key; src/ext/import/source.rs :: annotate, absolute, import_top, file_name +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`file.import` keeps its 0.4.0 arguments and takes new top-level ones: `units` (auto, mm, cm, m, in, ft), `up_axis` (auto, y, z), `stand_on_floor`, `center`, `frame`, `merge`, `cad_quality` (draft, medium, high, ultra or `{chord, angle}`). `ImportArgs::parse` reads the old `options` object first (through `clean_options`), then the top-level names, which win; "auto" leaves the old value. Old calls give byte-identical documents and replies apart from the new `source.*` metadata (checked on five calls). `merge: true` guarantees one top group; otherwise several roots get a wrap group as before. The reply adds `options` (the resolved options) and `source` (the absolute path). Imported nodes carry `source.path` (canonical absolute path) and `source.node` (names joined by `/`, empty for a group holding the whole file); the import's top nodes also carry `source.options` (the geometry options with the resolved units and up axis) so a re-read cannot flip a unit guess. `file.open` of a model takes the same options (`file_open_schema()`); the catalogue's `file.import` and `file.open` schemas come from this module. + +### crates/fsh-commands/src/ext/import/jobs.rs · import jobs +- refers-to: src/ext/import/jobs.rs :: Jobs, start, status, cancel, pump, document_changed +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`import.start` runs `prepare` (or fsh-cad's read for STEP and IGES, reading taking 90 % of `fraction`) on a worker thread against an empty document and answers `{job}` at once; the change is applied on the next dispatch by `pump`, because the worker cannot take the session lock (the Engine is not in an Arc). A result is never applied while a history group is open (stage `waiting`); jobs apply oldest first, one history group each, so an import is one undo step and one journal command. Cancel raises the Watch flag and drops the receiver, so a late result is discarded and the document stays untouched; a CAD cancel kills the worker. Jobs live in the engine's `State` (`Jobs {list, generation}`): they end with their engine (Drop cancels the running ones), another engine cannot see them, and `document_changed` (from `install_editor`: new, open, close, recover) cancels running jobs and marks them `stale`, with `error {code: "stale"}`; the pump also refuses any result from an older generation. Job ids come from one process-wide counter. On wasm32 the work runs inline. This replaced wave 1's process-wide table keyed by the engine's address, under which a dropped engine's job stayed until the process ended and another engine at the same address could apply it; removed: + +```rust +static JOBS: Mutex<BTreeMap<u64, Job>> = Mutex::new(BTreeMap::new()); +static NEXT: AtomicU64 = AtomicU64::new(1); + +fn jobs() -> MutexGuard<'static, BTreeMap<u64, Job>> { + JOBS.lock().unwrap_or_else(|p| p.into_inner()) +} + +fn owner(engine: &Engine) -> usize { + engine as *const Engine as usize +} +``` + +### crates/fsh-commands/src/ext/import/probe.rs, reimport.rs · probe and re-import +- refers-to: src/ext/import/probe.rs :: (module); src/ext/import/reimport.rs :: (module), replace_mesh +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`import.probe {path, worker?}` changes nothing and answers `{path, bytes, name, format, units_declared, units_guess, unit_guessed, up_axis, up_axis_declared, bounds {min, max, size, size_m}, triangles, meshes, nodes, materials, textures, images_in_file, texture_slots, warnings}`; STEP and IGES go to `cad::probe` (triangles and meshes null, plus a `cad` block). `file.reimport {nodes?}` reads each source file again with its stored options and matches parts by `source.node`, then by a name unique on both sides, then by a shape unique on both sides (so a renamed part keeps its material). Matched parts keep transform and material and take the file's name only if the person had not renamed them; reshaped parts get the new mesh through `mesh.add` plus `scene.set_part_mesh`, so they keep their ids (wave 1 rebuilt them with new ids before that command existed); new parts arrive; missing parts are hidden and marked `source.missing = "true"`, cleared when they return. A file whose top changes between a part and a group is split or wrapped so matching still works. CAD files are re-read through `cad::reread` at the quality the parts carry now, and matched parts take the file's `cad.*` and `source.cad` tags. One undo step. Re-import does not refresh a texture whose image changed in the source; new parts get the new images. The reply: `matched, added, hidden, updated, files: [{path, matched, added, hidden, updated, warnings, report, textures, error?}]`. + +### crates/fsh-commands/src/ext/import/textures.rs · embedding imported textures +- refers-to: src/ext/import/textures.rs :: embed, Embeds, keep, journal_textures; src/ext/import/run.rs :: Prepared::textures +- kind: decision +- logged: v0.6.0 · 2026-12-02 +After the clean-up, `prepare` reads each distinct texture uri (`#embedded:<i>` images and absolute files that exist), sniffs the content and embeds PNG, JPEG, Radiance HDR and OpenEXR as `fshot:textures/<sha256-32>.<ext>`, deduplicated by content; WebP, KTX2, DDS, GIF, BMP, TIFF and unknown content are skipped and their slots dropped. Files above 256 MiB keep their absolute path with a warning; missing files keep their reference, made absolute inside the model's folder, so the slot samples its fallback; textures outside the model's folder are reported missing. `apply` adds the members to `State.kept.textures` and hands the crash journal the textures with a snapshot. The reply carries `textures: {embedded, referenced, missing, skipped, members, bytes}`. Two one-line visibility changes outside the module: `State.journal` and `CrashJournal.session` are `pub(crate)`. + +### crates/fsh-commands/src/journal.rs, engine.rs · textures and sources reach the crash journal +- refers-to: src/journal.rs :: CrashJournal::start, CrashJournal::restart, CrashJournal::keep_sources, CrashJournal.session; src/engine.rs :: State::note_sources, file.recover +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`CrashJournal::start` and `restart` take the kept `&Project` instead of its textures map, so a new session starts with the project's embedded textures and its kept CAD sources; the four call sites in engine.rs pass `&st.kept`. `State::note_sources` hands newly kept sources to `CrashJournal::keep_sources` after a CAD import; textures go through `journal_textures` in ext/import/textures.rs (which needs `CrashJournal.session` as `pub(crate)`). `file.recover` puts `Recovered::sources` back into `Preserved::sources`, so retessellation works after a recovery even when the original STEP is gone (run: 498 to 4740 triangles from the recovered source). + +### crates/fsh-commands/src/ext/cad.rs · the CAD branch and retessellation +- refers-to: src/ext/cad.rs :: COMMANDS, is_cad, read_cad, prepare, apply, import, probe, reread, keep_source, Reread; native/crates/fsh-commands/Cargo.toml :: fsh-cad (native only) +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`cad.status {probe?}` answers `{available, path, tag, origin, cache, installed[], protocol, capabilities, reason?, code?}` (with probe also `occt`, `worker_protocol`, `methods`); `capabilities` lists progress, body_colours, face_colours, iges_colours, instance_transforms and pmi, each `{supported, reason}`; on wasm32 it answers `available: false`. CAD imports read options like `file.import` (the older top-level spellings `unit`, `centre` and `wrap_in_group` are no longer read; they were never in the schema), keep the source in the project, and tag nodes: every node `source.path` and `source.node`, parts also `source.cad` (`fshot:sources/...` when kept, else the path), `cad.mesh` (`body:slot`), `cad.quality`, `cad.unit`, `cad.up`; top nodes `source.options`. The reply adds `cad {format, bodies, shared, quality, linear_mm, angular_deg, diagonal_mm, occt, worker_tag, source, kept, triangles}`, `options` and `source`. `merge` also wraps a file whose single top node is a part. `scene.retessellate {nodes?, quality}` groups CAD parts by source, unit and up axis, re-reads from the kept bytes (else the path, else `source.path`) with floor, centre and instancing off so the frame matches, adds one mesh per changed mesh and calls `scene.set_part_mesh` per part with `cad.quality` updated, in one history group; ids, names, transforms, materials, visibility, selection and shared meshes stay; locked parts are skipped with a warning; it runs inline (no job, no cancel). Wave 1 rebuilt each part with `scene.add_part`, copied its settings, reparented its children and removed the old one, changing ids; that path is gone. + +### crates/fsh-commands/src/ext/handoff.rs · hand-off commands +- refers-to: src/ext/handoff.rs :: COMMANDS, dispatch +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`handoff.inspect {path, item?, read = true}` (read-only) answers the inspection (`kind, app, app_name, writer, title, model, format, design_unit, materials_only, gof, entry, mesh_from, template, texture_sets, maps[], roles, warnings`) plus `contents {meshes, triangles, nodes, materials[], textures, unit, up_axis, warnings}` when read; a read error lands in `contents.error`. `handoff.open {path, item?, as: add|new, frame?}` (Full): `new` installs a fresh empty-studio document titled after the hand-off outside the undo history, like `file.new`; either way the arrival is one history group labelled `Hand-off from <App>: <title>`, framed when the scene had no parts. Clean-up uses the `file.import` defaults with the GoF entry's `units`. Materials no mesh uses (maps without a mesh) arrive in the same `scene.import` payload. Every arriving node records `source.app`, `source.path`, `source.node` and `source.handoff`; roots also `source.title`, `source.writer`, `source.folder`, `source.design_unit`, `source.gof.*`, `source.template` and `source.maps`. Each map is a document texture with role and colour space, listed on its material (not yet as slots). Four engine.rs visibility lines were needed (`State::note`, `note_begin`, `note_end`, `frame_values`). + +### crates/fsh-commands/src/ext/materials.rs · read-only material commands +- refers-to: src/ext/materials.rs :: COMMANDS, dispatch +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`material.types` (the 18 types with params, shown specs, preset and optional graphs, and the ten measured metals in ACEScg), `material.node_kinds` (the 18 graph kinds with sockets, defaults and settings), `material.program {key}` (constant flag, instructions, registers, needs, constants, outputs, encoded words, disassembly, base, textures) and `material.preview_maps {key, size = 128 (16..512)}` (four base64 PNGs and flat `values`, baked at first with `NoTextures`, now with the engine's texture cache). `material.get` was missing at first, so the material page and the graph editor read the project snapshot; the polish pass added it (logged below) and both now use it. + +### crates/fsh-commands/src/ext/library.rs, library/ · the material library commands +- refers-to: src/ext/library.rs :: COMMANDS, dispatch; src/ext/library/locate.rs; preset.rs :: build_params, Preset::material, GraphMode, procedurals_live; store.rs; search.rs; state.rs; ball.rs; thumbs.rs; apply.rs; sha256.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Nine commands (shapes in docs/LIBRARY.md): `library.list`, `get`, `favorite`, `recent`, `apply`, `save`, `remove`, `thumbnail`, `thumbnails`. Root: `FORMSHOT_LIBRARY` (must hold `materials/index.json`), then the bundle places Tauri's `resource_dir` uses (`../Resources/library` on macOS, `library` or `resources/library` beside the program on Windows, `../lib/FormShot/library`, `$APPDIR/usr/lib/FormShot/library` and `/usr/lib/FormShot/library` on Linux), then `assets/library` in any folder above the program. Reading is strict (unknown top-level or `params` keys refused with the preset named, values checked, `SurfaceParams::validate()`), and the index is checked against every file: each problem is one warning in `library.list` and the preset is left out, never a crash. Apply builds `SurfaceParams::default()`, then the type's preset, then `params`, gives the material its type graph tuned to the preset (wood colour1 1.3 and colour2 0.55 times base_color, marble 1.08 and 0.45, the flake lerps around the preset's roughness and metalness, found through the graph's outputs), reuses an identical material already in the document, and is one undo step at Region level. Favourites and recent (24) are in `<user data>/formshot/library/state.json`, re-read on every call and written atomically, so the CLI and the service agree. User presets are `user/<slug>` files under `<user data>/formshot/library/materials/` with licence `NOASSERTION`. Thumbnails render on one background worker thread per process with its own document and renderer, so dispatch is never blocked (a `library.list` answered in 0.02 s with twelve renders queued). SHA-256 is in-house (no hashing crate in the workspace then). + +### crates/fsh-commands/src/ext/library/thumbs.rs, ball.rs · thumbnails +- refers-to: src/ext/library/thumbs.rs; src/ext/library/ball.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The scene is our own ball: a 0.5 m sphere with a 0.035 m inset band between polar angles 1.22 and 1.46 rad, tilted 0.42 rad about X and turned -0.5 rad about Y, on a lathed pedestal (foot 0.36 m, neck 0.17 m), about 21k triangles with UV set 0; the pedestal wears a near-black plastic. The built-in studio environment, the shadow-catcher ground, one 1.4 by 1.0 m area key light of 1500 lm at 5600 K up left, a 64 mm lens on a 36 mm sensor at (0, 1.0, 2.55) looking at (0, 0.57, 0), square, 48 samples, 10 bounces, seed 7, the denoiser at strength 1, all cores on the CPU tracer. An emitting preset lowers the exposure by log2(nits x 0.01 / 1.5) stops. Cache: `<user cache>/formshot/library/thumbs/<sha256>-<size>.png`; a `.look` marker holds the scene version and whether procedurals were live ("ball-2 flat" then; "ball-4" since the QA pass changed the preset graphs), and when it differs the PNGs are dropped once per process. Bump the "ball-N" string in thumbs.rs whenever the scene changes. `procedurals_live()` evaluates the wood procedural at four points; it was run only against the neutral stub (false, so `library.get` said `graph: "flat"`). With the procedurals and the CPU program wiring now in the tree it should answer true, so thumbnails render the tuned type graph and the look marker drops the old flat pictures; that was not run. About 9 to 14 s per 128 px picture on a loaded 2-core machine. + +### crates/fsh-commands/src/meshes.rs · uv0, tangents and material revisions for the raster view +- refers-to: src/meshes.rs :: scene.mesh_data, scene.meshes +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`scene.mesh_data` adds `uv0_b64` (f32 u, v per vertex) and `tangents_b64` (f32 xyz and a sign of exactly 1 or -1) only when the mesh carries them with one entry per vertex. `scene.meshes` adds `materials: [{key, revision}]` and per instance `tinted` (the part colour replaces the material's base colour, as in the tracers). A material's revision is a per-session counter that moves when its fingerprint changes: FNV of its JSON plus, for each texture it names, the path and, for absolute paths, the file's length and modified time; geometry, transform, assignment and selection changes do not move it. The catalogue descriptions of these two commands were not updated and do not mention the new fields. + +### crates/fsh-commands · import, CAD, hand-off and library verification +- refers-to: crates/fsh-commands :: (crate) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +All through the release `formshot-engine dispatch`. Import: probe leaves the document and content revision unchanged; a job and its undo behave like a synchronous import; a 1.8 million triangle OBJ (70 MB) cancelled at 23 % with the document unchanged; two parallel jobs applied in turn; a job started before `file.new` reported stale with nothing applied; a second engine saw no jobs. Re-import of renamed, added, removed and reshaped parts gave matched 3, added 1, hidden 1, updated 1 with undo exact; save and reopen identity on 10 models with 2 option sets, all equal. CAD: a gearbox STEP job finished in 1.2 to 5.4 s as one undo step; retessellation draft to ultra (498 to 13,640 triangles) kept every part id, the assigned material, a hidden bolt, the selection and the shared bolt mesh, with undo and redo exact; re-import of a changed STEP matched 10, updated 7, kept ids. Hand-offs: six opens succeeded, one undo removed a whole hand-off, save, reopen and save gave identical JSON members. Library: 249 presets in twelve categories with no warnings; searches ("gold" 15, "brushed steel" 1, "gÖLD Polished" finds gold-polished first); apply on the product-white template at part, group and same_material scope with reuse and four exact undos; save, remove, favourites and recent across processes; a corrupted library copy gave 247 presets and seven warnings; discovery in development, macOS, Linux and Windows folder layouts; twelve thumbnails looked at. Raster data: mesh blocks for a plane, a sphere and an imported cube with tangents read back with the right counts. `cargo clippy -p fsh-commands -p fsh-cli --all-targets -- -D warnings` clean; `cargo check --target wasm32-unknown-unknown -p fsh-commands` passes. Not run: macOS and Windows, a desktop bundle. + +### crates/fsh-commands/src/textures.rs, engine.rs, render.rs, device.rs, gpu.rs · loading textures and handing them to the renderers +- refers-to: src/textures.rs :: texture_image, texture_location, TextureCache::load, TextureCache::lookup, LoadedTextures; src/engine.rs :: State.textures, request_renderer, update_request, refresh_render, render_start, render.status, StillJob; src/render.rs :: Build.textures, Build::with_textures, RenderControl::update_request_textures; src/device.rs :: PreviewRenderer::set_textures, CpuPreview::set_textures; src/gpu.rs :: GpuPreview::set_textures +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The engine loads every `RenderTexture` of the snapshot into a `TextureSet` and hands it to whichever renderer runs, exactly like the environment image. One decode per (path, colour space, file length, modified time); embedded `fshot:` members use their length and time 0, since their names hold a content hash; relative paths resolve against the document's folder (the working folder when unsaved). `load` keeps only the current list's images, `lookup` keeps everything. The set is handed over when the texture list, the folder or a file's stamp changed, checked on every Region and Full refresh and on `render.start`, which resets the whole film and starts a new render job (reply `reset: "full"`); so a file repainted on disk shows at the next render start, and an unchanged file is not re-read. Missing or undecodable images are `None` (programs sample their fallbacks): their messages go to the reply's `warnings` when newly found and to `render.status.textures {count, loaded, missing, warnings}`; the render never fails. `PreviewRenderer::set_textures(Option<TextureSet>)` has a no-op default; the CPU preview calls `Renderer::set_textures`; `GpuPreview::set_textures` (lead commit 1cb3180) passes the set to `GpuRenderer::set_textures` and stops the device with the `texture_memory` refusal when the pixels do not fit, so the worker falls back to the CPU; still jobs carry the set too. Decoding happens on the dispatch thread under the session lock (a 4K image takes a fraction of a second); performance of programmed materials was not measured. `material.preview_maps` passed `NoTextures` until the QA pass gave it the cache's `lookup` set. Verified through dispatch: a missing file and a broken PNG gave warnings while rendering continued; a JPEG slot loaded; clearing a slot dropped its texture; save, reopen and a still kept it; a file overwritten on disk was picked up by the next `render.start`. + +### crates/fsh-commands/src/ext/materials.rs, ext/library/apply.rs · material.labels and the boxed material +- refers-to: src/ext/materials.rs :: material.labels; src/ext/library/apply.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`material.labels {key}` (read-only) answers `{key, labels: [Label JSON plus path and image_size [w, h] or null]}`, the image size read from PNG and JPEG headers (relative paths also tried beside the open project), for the Labels section. The library's apply builds its `material.create` payload with a boxed material since labels made `MaterialCreate.material` a `Box<Material>` (lead commit a665f28; JSON unchanged). The catalogue now counts 119 entries from the tables: 47 document, 38 engine, 23 ext and 11 aliases. + +### crates/fsh-commands/src/ext/materials.rs, ext/cad.rs · material.get and cad.parts +- refers-to: src/ext/materials.rs :: material.get; src/ext/cad.rs :: cad.parts +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Both window views that read the project snapshot (moving every mesh on each read) now ask the engine. `material.get {key | material}` (read-only) answers `{key, material: <Material JSON as stored>, used_textures: [keys], textures: {"<key>": TextureRef} for every document texture (the graph editor's chooser lists them all), program: {ok, constant, instructions, registers, needs, outputs, textures, encoded_words} or {ok: false, error}}`; a missing or unknown key is `invalid_arguments`. `cad.parts {nodes?}` (read-only, also in wasm builds) answers `{parts: [{id, name, source, path, quality, unit, up}]}` for parts carrying `source.cad`, nodes expanding to their subtrees. The catalogue now counts 121 entries by the tables: 47 document, 38 engine, 25 ext, 11 aliases. + +### crates/fsh-commands/src/textures.rs, engine.rs · images named by path in commands are embedded +- refers-to: src/textures.rs :: embed_command_path, lookup, environment_image, EnvImage; src/engine.rs :: load_env_image, hdri_path, journal_embedded, textures_unjournaled; src/ext/import.rs :: textures +- kind: decision +- logged: v0.6.0 · 2026-12-02 +An image chosen in the window stayed an absolute path, so a moved project lost it. Before a scene command runs, `embed_command_path` rewrites the image path of `material.set_slot {path}`, `material.label_add` and `label_set {path}`, `texture.add {texture.path}` and `environment.set` with an HDRI to `fshot:textures/<sha256-32>.<ext>` and keeps the bytes in `State.kept.textures`, when the content sniffs as PNG, JPEG, HDR or EXR and holds at most 256 MiB; missing files, other formats and larger files keep their path. Relative paths start at the document's folder (the working folder for an unsaved document). The resolved command (journal and redo) therefore names the member. New members reach the crash journal at once, or at `history.end_group` when a group is open (an embed inside a group used to reach no journal, and a recovered session could not even be saved); the import path shares `journal_textures`. Environments: `load_env_image` reads `fshot:` members and EXR as well as Radiance HDR through `environment_image` (shared with fsh-wasm). Run (QA): save, move the `.fshot`, delete the sources, reopen and render with every texture loaded; identical resave; crash recovery; HDR and EXR of the same Poly Haven environment within 0.0015 at 64 spp; an embedded HDRI rendered after the move. + +### crates/fsh-commands/src/ext/materials.rs, textures.rs · preview maps from the texture cache +- refers-to: src/ext/materials.rs :: preview; src/textures.rs :: lookup, TextureCache::lookup +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`material.preview_maps` compiles the preview's own texture table and samples it through the session's cache (`textures::lookup`, which keeps every image cached), so the window's Material preview shows image slots and labels instead of fallbacks. Checked: the base colour map shows a test image upright (red at the top left) and a label. + +### crates/fsh-commands/src/device.rs, gpu.rs, render.rs · region resets on both tracers, textures kept on fallback +- refers-to: src/device.rs :: changed_instances, REGION_PAD, PreviewRenderer::fallback_textures; src/gpu.rs :: GpuPreview::update_region; src/render.rs :: fall_back +- kind: decision +- logged: v0.6.0 · 2026-12-02 +A material edit should restart only the screen rectangle of the parts that wear it. `changed_instances` refused any change in the material count and compared the default material by index (which is `materials.len()`), so `library.apply` or assigning a new material always reset the whole film; it now allows the count to change and compares the default material by content. `GpuPreview::update_region` always reset fully; it now applies the snapshot without a reset and clears only the changed parts' first-hit rectangle (padded by `REGION_PAD`, 6 pixels), like the CPU. Run on the product template (`library.apply metal/gold-polished` on Band at 24 to 28 samples): CPU and lavapipe both answered `reset: region` with rectangle [110, 126, 210, 182] and 5,600 of 76,800 pixels cleared, the job unchanged, every changed pixel inside the rectangle. The GPU preview also remembers its texture set (`fallback_textures`), and `fall_back` hands it to the CPU renderer that takes over after a device failure, which before drew plain constants (checked with `FORMSHOT_GPU_FAULT=pass`). + +### crates/fsh-commands/src/ext/library/preset.rs, thumbs.rs · preset graphs that match the presets +- refers-to: src/ext/library/preset.rs :: Preset::material, granular_stone; src/ext/library/thumbs.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Looking at thumbnails showed every metallic paint blue (the paint_metallic graph's flake mix was never tuned to the preset; it now mixes around 1.5 times the preset's base colour) and every stone with marble veins; non-marble stones (concrete, limestone, sandstone, slate, travertine, granite) now get a fractal mottling graph (`granular_stone`; granite uses 4 mm Voronoi grains). The look marker is `ball-4`, so older pictures are dropped. Wood presets still read as flat tones at 128 px: their rings (250 per metre) are finer than a pixel on a 1 m ball, so the anti-aliasing correctly shows the mean. + ## fsh-cli ### crates/fsh-cli/src/main.rs · the formshot-engine command line @@ -484,6 +1010,12 @@ Binary `formshot-engine` with the subcommands render, info, convert, catalogue, - logged: v0.3.0 · 2026-12-02 Every `dispatch` reply line, whether result, error or unreadable request, carries `meta: {revision, content_revision}`, and the usage text says so. The field is additive: a client reading `result` by id is unaffected. Run: `scene.summary` gave revision 1, content 1; `file.new` 2 and 2; `camera.set` 3 and 2; `environment.set` 4 and 3; `selection.clear` 5 and 3; an unknown command's error and an unreadable line both carried meta. Release CLI after the change: `render sample --samples 16` on the CPU 2.83 s, 4,613,856 rays; `--device gpu` on lavapipe 2.36 s, 4,613,858 rays. +### crates/fsh-cli/src/main.rs · import options, probe and reimport +- refers-to: src/main.rs :: probe, reimport, USAGE +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`render`, `convert` and `info` take import options for model files: `--units` (auto, mm, cm, m, in, ft), `--up` (auto, y, z), `--floor[=no]`, `--center[=yes]`, `--merge[=yes]`; a note says they apply to model files only. Models load through `import.start` with the stage on stderr, so STEP and IGES go through the CAD worker here too. New subcommands: `probe <file> [--json]` (`import.probe`) and `reimport <project.fshot> [output.fshot] [--json]` (`file.reimport` on every imported model, then save). `info` on a model adds the probe and the options the import used. There is no `--cad-quality` option; the CAD default quality (medium) applies. Run: options, info, probe and reimport, with `convert` output byte-identical to the previous build; `info` and `probe` on the gearbox IGES and STEP. + ## fsh-py ### crates/fsh-py/src/lib.rs, pyproject.toml · the Python binding @@ -524,6 +1056,18 @@ The entry above is superseded. The package (`--target web`, default export `init - logged: v0.3.0 · 2026-12-02 Build: `./formshot engine wasm` with `FSH_WASM_TARGET_DIR`, wasm-bindgen 0.2.130 (the version Cargo.lock pins): cargo output 4.9 MB, `fsh_wasm_bg.wasm` 3.66 MB (1.02 MB gzip -9), `fsh_wasm.js` 93 KB; the first wasm build took 3 min 48 s; no wasm-opt. Node 22 with the package: catalogue 87, `file.snapshot` listed, a 96x72 CPU render at 4 spp in 1.9 s with a PNG frame, a `.fshot` loaded into a second Session in 35 ms with equal counts, a CLI-exported GLB loaded in 72 ms, junk bytes refused, a rebuilt mirror equal in counts, transforms (max difference 0), colours, camera and settings. Natively on lavapipe, the renderer-API sequence the viewport uses (4 x `submit(2)` read through `accumulator()`) equalled `render_pass(8)` bit for bit on 14,400 of 14,400 pixels. Headless Chromium (SwiftShader WebGPU): with the earlier placeholder kernel the viewport presented frames (create 359 to 469 ms, 1 sample per pass at 0.5 to 1.3 s, read back correctly), orbiting dropped to half size, a service edit came through the poll within 7 s, and destroying the GPUDevice handed over to streamed frames. With the real megakernel `create_viewport` never finished: SwiftShader's compiler grew to 4,000 MB and was OOM-killed at about 107 s (a compile-only page with every override constant off reached 3,827 MB at 100 s and died the same way). So the path tracer in the window has not drawn a frame anywhere. Not run: a real GPU, Safari or Firefox WebGPU, Tauri, the premultiplied transparent path (SwiftShader offered Opaque only). Clippy clean on wasm32 and native. +### crates/fsh-wasm/src/textures.rs, session.rs, tracer.rs, viewport.rs · textures in the window's engine +- refers-to: src/textures.rs :: Ident, TextureStore, SceneTextures, decode, pack, unpack; src/session.rs :: textures, take_embedded, put_texture, fail_texture, decode_texture, Scene::counts; src/lib.rs :: decode_texture; src/tracer.rs :: Tracer::set_textures; src/viewport.rs :: create_viewport, set_scene +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The window session's snapshot already compiles programs (`Editor::new(doc).snapshot()`); only the old meshes-mode mirror, used when the engine has no `file.snapshot`, rebuilds materials from presets and so carries no slots, graphs or textures. Images are decoded once per (path, colour space, mipmaps) into a `TextureStore` whose decoded images are `Arc`s shared with the renderer's set; `retain_for(snapshot)` releases what the document no longer names; failures are kept with their reason. Embedded `fshot:textures/...` members come out of the snapshot the mirror already loads (`take_embedded` hands them out once and drops the bytes); outside files come from the service's texture route. `decode` (also exported as `decode_texture` for the window's worker, with a flat little-endian `pack`/`unpack`) now calls fsh-io's `decode_image` and fsh-materials' `TextureImage::from_*` builders (lead commit de35daf replaced tex-wasm's interim PNG and HDR decoder, about 140 lines), so the window decodes PNG, JPEG, HDR and EXR exactly as the engine does. `Tracer::set_textures` is the one call site of `GpuRenderer::set_textures`; `create_viewport` and `set_scene` hand a set over before the snapshot update when the scene's texture tag changed, so the film restarts once; status gains `textures`, `textures_ready`, `textures_wired`. Verified in Node: textures listed, PNG (8 and 16 bit), CC0 brick maps and a damaged PNG decoded or refused with the reason; an integration copy's packed images were byte-identical between the interim decoder and fsh-io's (level 0 and all mips). No textured picture was drawn by the window's GPU viewport: SwiftShader cannot compile the kernel and no real GPU was available. + +### crates/fsh-wasm/src/session.rs, viewport.rs, tracer.rs · the embedded environment in the window +- refers-to: src/session.rs; src/viewport.rs; src/tracer.rs; Scene::counts (environment_image) +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The window session never handed environment pixels to its tracer, so the in-window path tracer showed the studio for an HDRI scene. It now decodes an environment image embedded in the project (through fsh-commands' `environment_image`) and the viewport hands it to the tracer when the path changes; `Scene.counts()` reports `environment_image`. Environments still referenced by an outside path show the studio in the window, but new ones are embedded by `environment.set`. Checked natively (a throwaway program loading a project reported a 1024 by 512 environment) and by wasm32 clippy; no browser frame was drawn. + ## fsh-render-gpu ### crates/fsh-render-gpu/src/lib.rs · placeholder for the GPU tracer @@ -631,6 +1175,48 @@ The megakernel entry above is superseded in three points. (1) Adaptive sampling - logged: v0.3.0 · 2026-12-02 On lavapipe at 320x240 with the shader cache off: before the change the first switch to adaptive took 1.01 s in `set_adaptive` and 5.34 s for the next pass (a new pipeline); after it every toggle took 0.000 s and the next 1-spp pass 0.13 to 0.24 s. Through the engine (release builds, shader cache off) the first switch reached 3 samples in 0.67 s instead of 7.18 s. Parity against the CPU is unchanged: sample 0.000010, spheres 0.000010, daylight 0.000001, a scene without lights and catcher 0.000011 mean absolute difference at 16 spp; adaptive retired flags 76,799 or 76,800 of 76,800 equal. Variants: `Some(Features::NONE)` built the scene's own kernel; an ALL renderer on a plain scene reported `needs_specialise`, `specialise_async` compiled in 0.99 s, a second call compiled nothing, and the two kernels drew 19,200 of 19,200 pixels bit-identical. Region (rect 80..240 x 60..120): 9,600 of 9,600 pixels inside reached 6 samples bit-identical to a full-film renderer, 67,200 of 67,200 outside kept 2; a region pass took 0.116 s against 1.137 s for the full film. naga: 24 reports OK, Frame 62 members and 288 bytes on both sides. Not run: a real GPU, the region on llvmpipe GL separately, a region over a film split into several bands; the wasm32 path (`specialise_async` awaited in the window) was compiled for wasm32 and run natively only, and the window does not call it yet. +### crates/fsh-render-gpu/src/shaders/procedural.wgsl · the procedural port +- refers-to: src/shaders/procedural.wgsl :: procedural, proc_*, PROC_*, ProcNearest; src/shaders.rs +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`fn procedural(kind: u32, output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32>` ports fsh-materials' ten kinds with the same pcg3d integer hashing, argument order and anti-aliasing, so the patterns agree with the CPU's: their integer parts bit for bit, floats within 1e-4 (largest measured 5.4e-7). The module is self-contained (helpers prefixed `proc_`, `PROC_`, `ProcNearest`); it is now in shaders.rs's table and included by `program.wgsl`, whose `Proc` opcode calls it (GPU texture work, logged below). The interpreter passes at most 16 arguments, the WGSL array holds 12, and the largest kind uses 7. A check assembled kernel.wgsl with its includes plus procedural.wgsl into a shader module on lavapipe with no messages (no name clashes). Software driver only. + +### crates/fsh-render-gpu/src/layout.rs, bindings.wgsl, validate.rs · vertex slots, Frame.textures, the 160-byte material +- refers-to: src/layout.rs :: Vertex, vertex_stride, INST_NORMALS, INST_UV_SHIFT, INST_UV_MASK, INST_TANGENTS, MAX_GPU_UV_SETS, MAT_PROGRAM, Frame::textures, Material::program, Material::set_optics; src/shaders/bindings.wgsl :: vertex_uv_sets, vertex_stride; src/validate.rs :: program_report +- kind: decision +- logged: v0.6.0 · 2026-12-02 +This supersedes the layouts of the Turn 2 entries above. `Vertex` is one 16-byte attribute slot `{v: [f32; 4]}`; a mesh owns `stride * vertex_count` slots from `Instance.vertex_base`, in this order when present: the authored normal (xyz, 0) with `INST_NORMALS` (bit 3), uv sets 0 and 1 as (u0, v0, u1, v1) and sets 2 and 3 likewise, `ceil(n / 2)` slots for n = `(flags >> 4) & 7` sets, and the tangent (xyz, sign) with `INST_TANGENTS` (bit 7). Uvs are packed as the mesh stores them (v up). Uvs and tangents are packed only for meshes worn by an instance whose program is not constant, so constant scenes keep 16 bytes per vertex with normals; a glTF mesh with normals, one uv set and tangents costs 48. Frame grows from 288 to 304 bytes: `textures` (float offset of the texture directory in `tables`, NONE without textures) at 288, then three pad words. Material grows from 144 to 160 bytes: the record holds `program.base` (identical to the old inputs for constant programs), `program` (float offset of the material's `encode_f32()` blob, NONE for constant or refused programs) with flags bit 0 `MAT_PROGRAM`, and at 144..160 `film_weight, film_thickness, film_ior, dispersion` written by `set_optics` from the material's params (the optics work; host.rs's `build_materials` applies both). Materials sharing one `Arc<Program>` share one blob. naga validated 27 reports with Frame at 66 members and 304 bytes and every struct member by member; `program_report` checks that every admitted opcode has an `OP_<NAME>` constant of the contract's value. + +### crates/fsh-render-gpu/src/texpack.rs, host.rs, scene.rs, renderer.rs, refusals.rs · programs and textures in tables +- refers-to: src/texpack.rs :: append, block_len; src/host.rs :: build_materials, append_programs, mesh_attributes, attributes_match, textures_start, programs_start, set_textures; src/scene.rs :: GpuScene::set_textures, TEXTURE_MEMORY; src/renderer.rs :: GpuRenderer::set_textures, Features::programs; src/refusals.rs :: program_refusal, GPU_OPCODES, GPU_PROCEDURALS +- kind: decision +- logged: v0.6.0 · 2026-12-02 +The 8 storage bindings are taken, so programs and texels go into `tables`, whose blocks are now: environment, BSDF energy, textures, program blobs, emissive. The texture block at `Frame.textures` = D holds offsets relative to D (so they stay exact floats however long the environment is): `[N, lut, 0, 0]`, N records `[levels, colour space (0 srgb, 1 linear, 2 acescg, 3 data), storage (0 rgba8, 1 rgbaf32), first level record]` (levels 0 for a missing image or a malformed level 0; levels after a malformed one are left out, as the CPU stops there), level records `[width, height, texel offset >> 16, texel offset & 0xffff]`, the 256 floats of `srgb8_table()`, then texels (rgba8 as `r + 256 g` and `b + 256 a`, rgbaf32 as four floats). A texture index past N samples the fallback. `GpuScene::set_textures` uploads only what changed; material edits rewrite blobs; an environment change rewrites material records (program offsets move); a change in packed attributes rebuilds geometry. A fourth `Features` member, `programs` (`USE_PROGRAMS`), removes the interpreter at pipeline creation for scenes without programs; WebAssembly always builds every feature, so the window's kernel grows. Refusals: `material_program` (Feature) for a used material whose program fails `check()`, needs more than 32 registers, uses an opcode outside `GPU_OPCODES` (0 to 24), reads a uv set past 4 or a procedural outside `GPU_PROCEDURALS` (all ten); refused programs are not uploaded and the job renders on the CPU. `texture_memory` (Limit) when `tables` would exceed `max_storage_buffer_binding_size`, from `set_textures` (pixels kept until new ones fit) or a full upload; through `GpuPreview::set_textures` it stops the device so the CPU takes over. Not provoked in a run. + +### crates/fsh-render-gpu/src/shaders/texture.wgsl, program.wgsl, surface.wgsl, integrator.wgsl, lights.wgsl, camera.wgsl, features.wgsl · the interpreter in WGSL +- refers-to: src/shaders/texture.wgsl :: tex_sample; src/shaders/program.wgsl :: HitCtx, run_program, atan2_p, acos_p, sanitize_inputs; src/shaders/surface.wgsl :: hit_ctx, shade_inputs, shading_normal; src/shaders/integrator.wgsl :: camera_cone, cone_widening, CONE_MIN_COS, dispersion_channel, dispersion_ior; src/shaders/lights.wgsl; src/shaders/camera.wgsl :: camera_cone; src/shaders/features.wgsl :: USE_PROGRAMS; src/shaders.rs :: SOURCES +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`tex_sample(t, uv, footprint, wrap, mode, fallback)` reads the directory and filters as the CPU sampler does. `run_program(offset, ctx, &m, &ns)` runs every opcode 0 to 24 (24 is `Label`) from the blob and calls `procedural(kind, output, &args, count)` from procedural.wgsl; `sanitize_inputs` ports `SurfaceInputs::sanitized` and sets `eta = specular_ior`. `atan2` and `acos` are Cephes polynomials (`atan2_p`, `acos_p`), because lavapipe's driver versions moved projected uvs by up to 6e-4. `shade_inputs` in surface.wgsl builds `HitCtx` exactly as the CPU's `hit_context` and runs the program (behind `USE_PROGRAMS` and `MAT_PROGRAM`), then the tint; emissive triangle samples in lights.wgsl run it at the sample point with footprint 0. The integrator carries the CPU's ray cone, so footprints match. The merged integrator.wgsl keeps the CPU's order at a hit: `shade_inputs`, regularisation, opacity, `eta = m.eta`, then the material record's optics: a dispersive transmissive hit draws `DIM_WAVELENGTH` and shifts the evaluated `specular_ior` (`dispersion_ior`), and `bsdf_add_film` adds the film after `bsdf_new` (bsdf.wgsl ports the Airy film; the rough film albedo is averaged over visible normals as on the CPU). The kernel assembles to about 4,350 lines (software) and 4,268 (hardware), against about 3,400 before; the film code is compiled into every kernel (no override constant for it). + +### crates/fsh-render-gpu · programs, textures and optics verification (software drivers only) +- refers-to: crates/fsh-render-gpu :: (crate) +- kind: verification +- logged: v0.6.0 · 2026-12-02 +On lavapipe: constant scenes against the CPU at 320 by 240, 16 spp, unchanged (sample and spheres 0.000010, product-white 0.000004, daylight 0.000001). 77 programs at 64 random hit contexts each, every SurfaceInputs field, eta and the normal compared with `Program::evaluate`: largest difference 1.4e-5, apart from bump through cylindrical and spherical projections (up to 3.7e-3 on 31 of 2560 values, where the CPU itself moves by 1.9e-2 for a one-ulp nudge of the hit) and procedural outputs compared while procedural.wgsl was still a stub. A textured sample scene (uv checker, a normal map with roughness from alpha, box-projected colour and bump, a spherical checker; 128 px textures with mips) against tex-cpu's CPU tracer: mean absolute difference 0.000083, 0.079 % of pixels over 0.02, with ray queries and with software traversal. Optics scenes against the CPU on lavapipe: soap bubbles 0.00001, the anodised and pearl presets 0.00001, an SF11 prism and a diamond 0.00000, a rough prism 0.00007; on llvmpipe GL bubbles 0.00001 and the prism 0.00000. Not run: a real GPU, Metal, Direct3D 12, SwiftShader or browser WebGPU with programs, the `texture_memory` refusal, a texture block past 2^24 floats. + +### crates/fsh-render-gpu/src/texpack.rs, shaders/texture.wgsl · storage 2, opaque 8-bit texels in one float +- refers-to: src/texpack.rs :: STORAGE_RGBA8, STORAGE_RGBAF32, STORAGE_RGB8, storage; src/shaders/texture.wgsl :: TEX_STORAGE_RGB8 +- kind: decision +- logged: v0.6.0 · 2026-12-02 +Three Khronos samples (NormalTangentMirrorTest 145 MB of tables, WaterBottle 190 MB, AlphaBlendModeTest 156 MB) were refused by lavapipe's 128 MiB binding (`texture_memory`) and drawn by the CPU. An 8-bit image whose every level has alpha 255 now packs as storage 2 (`STORAGE_RGB8`): one float per texel, `r + 256 g + 65536 b` (an exact integer below 2^24), instead of two; storage 0 (rgba8, two floats) and 1 (rgbaf32, four) are unchanged. All three now render on the GPU within 0.0008 of the CPU. MATERIALS_SEAMS.md section 6 lists storage 0 and 1 only; docs/GPU-ENGINE.md now lists all three. + +### crates/fsh-render-gpu/src/renderer.rs, shaders/integrator.wgsl · region updates and the bent-normal clamp +- refers-to: src/renderer.rs :: GpuRenderer::update_region, apply_snapshot, set_snapshot; src/shaders/integrator.wgsl :: clamp_bent_normal +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`set_snapshot` is split into `apply_snapshot` and the reset, and `update_region(snapshot, instances, pad)` applies a snapshot without resetting and clears only the first-hit rectangle of the given instances (answering the rectangle, or none when a full reset is needed), so a material edit on the GPU restarts only the edited parts as on the CPU. `clamp_bent_normal` ports the CPU's clamp of program-changed normals. QA table at 320 by 240 and 16 spp against the CPU on lavapipe, ray queries and software traversal: 30 scenes (textures, labels, procedurals, thin film, dispersion, normal maps, alpha blend and mask, the library, under the sky and under an HDRI), every mean absolute difference at most 0.0009 and no NaN. First renders of a programs scene after a new build compile that kernel variant (15 to 35 s on lavapipe, then cached). + ### (workspace) · clippy clean under the pinned toolchain - refers-to: crates/fsh-core/src/color.rs :: planckian_xy; crates/fsh-materials/src/bsdf.rs :: Bsdf::sample, Bsdf::prepare; crates/fsh-materials/src/tables.rs :: DielGroup, fill_diel; crates/fsh-scene/src/mesh.rs :: compute_normals; crates/fsh-io/src/clean.rs; crates/fsh-io/src/gltf.rs; crates/fsh-io/src/png.rs - kind: decision diff --git a/native/crates/fsh-accel/Cargo.toml b/native/crates/fsh-accel/Cargo.toml index 92a0cc72..7628866a 100644 --- a/native/crates/fsh-accel/Cargo.toml +++ b/native/crates/fsh-accel/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-accel" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false diff --git a/native/crates/fsh-cad/Cargo.toml b/native/crates/fsh-cad/Cargo.toml new file mode 100644 index 00000000..2e8a3235 --- /dev/null +++ b/native/crates/fsh-cad/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "fsh-cad" +version = "0.6.0" +edition = "2021" +license = "Apache-2.0" +publish = false + +[dependencies] +fsh-core = { path = "../fsh-core" } +fsh-io = { path = "../fsh-io" } +serde_json = "1" diff --git a/native/crates/fsh-cad/src/client.rs b/native/crates/fsh-cad/src/client.rs new file mode 100644 index 00000000..af1aead7 --- /dev/null +++ b/native/crates/fsh-cad/src/client.rs @@ -0,0 +1,273 @@ +use crate::error::{CadError, Result}; +use crate::locate::Located; +use fsh_io::Watch; +use serde_json::{json, Map, Value}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::collections::VecDeque; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +/// Protocol version this client speaks (the worker's `hello` reports it). +pub const PROTOCOL: u64 = 2; +/// Longest reply line accepted, in bytes. +pub const MAX_LINE: u64 = 256 << 20; +const POLL: Duration = Duration::from_millis(40); + +enum Line { + Text(Vec<u8>), + TooLong, + Closed(String), +} + +/// What the worker said to `hello`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Hello { + /// OpenCascade version. + pub occt: String, + /// Protocol version (0 when the worker does not say). + pub protocol: u64, + /// Methods the worker answers. + pub methods: Vec<String>, + /// The whole reply. + pub raw: Value, +} + +impl Hello { + /// True when the worker lists `method`. + pub fn has(&self, method: &str) -> bool { + self.methods.iter().any(|m| m == method) + } +} + +/// A running worker; dropping it asks the worker to stop and kills it if it does not. +pub struct Worker { + child: Child, + stdin: Option<ChildStdin>, + lines: Receiver<Line>, + next: u64, + hello: Hello, + errors: Arc<Mutex<VecDeque<String>>>, +} + +const KEPT_ERROR_LINES: usize = 6; + +fn spawn_error_tail(err: impl Read + Send + 'static) -> Arc<Mutex<VecDeque<String>>> { + let tail = Arc::new(Mutex::new(VecDeque::new())); + let keep = tail.clone(); + thread::Builder::new() + .name("cad-worker-stderr".into()) + .spawn(move || { + let mut reader = BufReader::new(err); + let mut buf = Vec::new(); + loop { + buf.clear(); + match reader.by_ref().take(64 << 10).read_until(b'\n', &mut buf) { + Ok(0) | Err(_) => return, + Ok(_) => { + let line: String = String::from_utf8_lossy(&buf).trim().chars().filter(|c| !c.is_control()).take(300).collect(); + if line.is_empty() { + continue; + } + if let Ok(mut t) = keep.lock() { + if t.len() == KEPT_ERROR_LINES { + t.pop_front(); + } + t.push_back(line); + } + } + } + } + }) + .ok(); + tail +} + +fn spawn_reader(out: impl Read + Send + 'static) -> Receiver<Line> { + let (tx, rx) = mpsc::channel(); + thread::Builder::new() + .name("cad-worker-reader".into()) + .spawn(move || { + let mut reader = BufReader::new(out); + loop { + let mut buf = Vec::new(); + match reader.by_ref().take(MAX_LINE + 1).read_until(b'\n', &mut buf) { + Ok(0) => { + let _ = tx.send(Line::Closed("its output ended".into())); + return; + } + Ok(_) if buf.len() as u64 > MAX_LINE => { + let _ = tx.send(Line::TooLong); + return; + } + Ok(_) => { + if tx.send(Line::Text(buf)).is_err() { + return; + } + } + Err(e) => { + let _ = tx.send(Line::Closed(e.to_string())); + return; + } + } + } + }) + .ok(); + rx +} + +impl Worker { + /// Starts the worker and waits for its `hello` (at most `timeout`), honouring the watch's cancel flag. + pub fn start(located: &Located, timeout: Duration, watch: Option<&Watch>) -> Result<Worker> { + let (program, args) = located.command.split_first().ok_or_else(|| CadError::Start("empty command".into()))?; + let mut cmd = Command::new(program); + cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + if let Some(dir) = located.path.parent() { + cmd.current_dir(dir); + } + let mut child = cmd.spawn().map_err(|e| CadError::Start(format!("{}: {e}", located.path.display())))?; + let stdin = child.stdin.take(); + let Some(stdout) = child.stdout.take() else { + let _ = child.kill(); + let _ = child.wait(); + return Err(CadError::Start("no output pipe".into())); + }; + let errors = child.stderr.take().map(spawn_error_tail).unwrap_or_default(); + let lines = spawn_reader(stdout); + let mut worker = Worker { child, stdin, lines, next: 1, hello: Hello::default(), errors }; + let raw = worker.call("hello", json!({}), timeout, watch)?; + let methods = raw + .get("methods") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + let protocol = raw.get("protocol").and_then(Value::as_u64).unwrap_or(0); + let occt = raw.get("occt").and_then(Value::as_str).unwrap_or("unknown").to_string(); + if protocol != 0 && protocol != PROTOCOL { + return Err(CadError::Protocol(format!("it speaks protocol {protocol}, FormShot speaks {PROTOCOL}"))); + } + worker.hello = Hello { occt, protocol, methods, raw }; + Ok(worker) + } + + /// What `hello` answered. + pub fn hello(&self) -> &Hello { + &self.hello + } + + fn kill(&mut self) { + self.stdin = None; + let _ = self.child.kill(); + let _ = self.child.wait(); + } + + fn exit_note(&mut self) -> String { + let until = Instant::now() + Duration::from_millis(500); + let status = loop { + match self.child.try_wait() { + Ok(Some(s)) => break format!("{s}"), + Ok(None) if Instant::now() < until => thread::sleep(Duration::from_millis(10)), + _ => break "it closed its output".into(), + } + }; + thread::sleep(Duration::from_millis(50)); + let tail: Vec<String> = self.errors.lock().map(|t| t.iter().cloned().collect()).unwrap_or_default(); + match tail.last() { + Some(last) => format!("{status}; it last said: {last}"), + None => status, + } + } + + /// Sends one request and waits for its answer; on cancel or timeout the worker is killed. + pub fn call(&mut self, method: &str, params: Value, timeout: Duration, watch: Option<&Watch>) -> Result<Value> { + let id = self.next; + self.next += 1; + let mut line = serde_json::to_vec(&json!({"id": id, "method": method, "params": params})) + .map_err(|e| CadError::Protocol(format!("request could not be encoded: {e}")))?; + line.push(b'\n'); + let sent = match self.stdin.as_mut() { + Some(w) => w.write_all(&line).and_then(|_| w.flush()), + None => Err(std::io::Error::other("the worker was stopped")), + }; + if let Err(e) = sent { + let note = self.exit_note(); + self.kill(); + return Err(CadError::Exited(format!("{method} could not be sent ({e}; {note})"))); + } + let deadline = Instant::now() + timeout; + loop { + if watch.is_some_and(Watch::is_cancelled) { + self.kill(); + return Err(CadError::Cancelled); + } + let now = Instant::now(); + if now >= deadline { + self.kill(); + return Err(CadError::Timeout(format!("{method} took longer than {} s; the worker was stopped", timeout.as_secs()))); + } + let text = match self.lines.recv_timeout(POLL.min(deadline - now)) { + Ok(Line::Text(t)) => t, + Ok(Line::TooLong) => { + self.kill(); + return Err(CadError::Protocol(format!("a reply to {method} is longer than {MAX_LINE} bytes"))); + } + Ok(Line::Closed(why)) => { + let note = self.exit_note(); + self.kill(); + return Err(CadError::Exited(format!("while answering {method} ({why}; {note})"))); + } + Err(RecvTimeoutError::Timeout) => continue, + Err(RecvTimeoutError::Disconnected) => { + let note = self.exit_note(); + self.kill(); + return Err(CadError::Exited(format!("while answering {method} ({note})"))); + } + }; + let Ok(Value::Object(reply)) = serde_json::from_slice::<Value>(&text) else { continue }; + if reply.get("id").and_then(Value::as_u64) != Some(id) { + continue; + } + return answer(method, reply); + } + } + + /// Asks the worker to stop, waits briefly, then kills it. + pub fn shutdown(mut self) { + let _ = self.call("shutdown", json!({}), Duration::from_secs(3), None); + self.stop_now(); + } + + fn stop_now(&mut self) { + self.stdin = None; + let until = Instant::now() + Duration::from_secs(2); + while Instant::now() < until { + if let Ok(Some(_)) = self.child.try_wait() { + return; + } + thread::sleep(Duration::from_millis(20)); + } + self.kill(); + } +} + +fn answer(method: &str, mut reply: Map<String, Value>) -> Result<Value> { + if let Some(err) = reply.get("error") { + let msg = err + .get("message") + .and_then(Value::as_str) + .map(str::to_string) + .unwrap_or_else(|| format!("{method} failed without a message")); + return Err(CadError::Worker(msg)); + } + reply.remove("result").ok_or_else(|| CadError::Protocol(format!("the reply to {method} has neither result nor error"))) +} + +impl Drop for Worker { + fn drop(&mut self) { + if matches!(self.child.try_wait(), Ok(None)) { + self.stop_now(); + } + } +} diff --git a/native/crates/fsh-cad/src/error.rs b/native/crates/fsh-cad/src/error.rs new file mode 100644 index 00000000..f8c2a517 --- /dev/null +++ b/native/crates/fsh-cad/src/error.rs @@ -0,0 +1,71 @@ +use fsh_io::IoError; +use std::fmt; + +/// Everything that can go wrong between FormShot and the CAD worker. +#[derive(Debug, Clone, PartialEq)] +pub enum CadError { + /// No worker program was found; the text says where FormShot looked. + Missing(String), + /// The worker could not be started. + Start(String), + /// The worker stopped while FormShot waited for an answer. + Exited(String), + /// The worker did not answer in time and was stopped. + Timeout(String), + /// The worker answered with something that is not the protocol. + Protocol(String), + /// The worker reported an error for a request. + Worker(String), + /// The file could not be used (wrong extension, unreadable, no geometry). + File(String), + /// The watch's cancel flag was raised; the worker was stopped. + Cancelled, +} + +impl CadError { + /// Stable snake_case code for scripting and the UI. + pub fn code(&self) -> &'static str { + match self { + CadError::Missing(_) => "cad_worker_missing", + CadError::Start(_) => "cad_worker_start", + CadError::Exited(_) => "cad_worker_exited", + CadError::Timeout(_) => "cad_worker_timeout", + CadError::Protocol(_) => "cad_worker_protocol", + CadError::Worker(_) => "cad_worker_error", + CadError::File(_) => "cad_file", + CadError::Cancelled => "cancelled", + } + } +} + +impl fmt::Display for CadError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CadError::Missing(s) => write!(f, "the CAD worker is not installed: {s}"), + CadError::Start(s) => write!(f, "the CAD worker could not be started: {s}"), + CadError::Exited(s) => write!(f, "the CAD worker stopped: {s}"), + CadError::Timeout(s) => write!(f, "the CAD worker did not answer in time: {s}"), + CadError::Protocol(s) => write!(f, "the CAD worker answered outside its protocol: {s}"), + CadError::Worker(s) => write!(f, "the CAD worker reported: {s}"), + CadError::File(s) => write!(f, "{s}"), + CadError::Cancelled => write!(f, "cancelled"), + } + } +} + +impl std::error::Error for CadError {} + +impl From<CadError> for IoError { + fn from(e: CadError) -> Self { + match e { + CadError::Cancelled => IoError::Cancelled, + CadError::Missing(_) => IoError::Unsupported(e.to_string()), + CadError::File(s) => IoError::InvalidData(s), + CadError::Worker(_) => IoError::Malformed(e.to_string()), + other => IoError::Io(other.to_string()), + } + } +} + +/// Result with a [`CadError`]. +pub type Result<T> = std::result::Result<T, CadError>; diff --git a/native/crates/fsh-cad/src/lib.rs b/native/crates/fsh-cad/src/lib.rs new file mode 100644 index 00000000..a8d79c04 --- /dev/null +++ b/native/crates/fsh-cad/src/lib.rs @@ -0,0 +1,22 @@ +//! FormShot's client for FormCAD's kernel worker: finds the worker, starts it as a child process, speaks its +//! JSON-lines protocol, opens STEP and IGES files, tessellates them and returns an `fsh_io::RawScene`. +//! Native only: the engine never downloads the worker, the service or `setup/cad_worker` does. + +mod client; +mod error; +mod locate; +pub mod mesh; +mod quality; +mod probe; +mod read; +pub mod scan; + +pub use client::{Hello, Worker, MAX_LINE, PROTOCOL}; +pub use error::{CadError, Result}; +pub use probe::probe; +pub use quality::{Quality, MIN_LINEAR_MM}; +pub use read::{ + hello_timeout, is_cad_path, read, CadFormat, CadRead, MeshTag, ReadOptions, HELLO_TIMEOUT_ENV, HELLO_TIMEOUT_SECS, + TIMEOUT_ENV, +}; +pub use locate::{cache_dir, installed, locate, workers_dir, Located, Origin, CACHE_ENV, PROGRAM, WORKER_ENV}; diff --git a/native/crates/fsh-cad/src/locate.rs b/native/crates/fsh-cad/src/locate.rs new file mode 100644 index 00000000..d0196ecc --- /dev/null +++ b/native/crates/fsh-cad/src/locate.rs @@ -0,0 +1,123 @@ +use crate::error::{CadError, Result}; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +/// Environment variable naming a worker program (or a `.py` worker script) to use before any other. +pub const WORKER_ENV: &str = "FORMSHOT_CAD_WORKER"; +/// Environment variable replacing the platform's user cache folder. +pub const CACHE_ENV: &str = "FORMSHOT_CACHE"; +/// File name of the worker program on this platform. +pub const PROGRAM: &str = if cfg!(windows) { "formcad-kernel.exe" } else { "formcad-kernel" }; + +/// Where the worker was found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Origin { + /// From `FORMSHOT_CAD_WORKER`. + Env, + /// Beside the running program. + App, + /// In the user cache folder, installed by the service or `setup/cad_worker`. + Cache, +} + +impl Origin { + /// Short name: env, app or cache. + pub fn as_str(self) -> &'static str { + match self { + Origin::Env => "env", + Origin::App => "app", + Origin::Cache => "cache", + } + } +} + +/// A worker that can be started. +#[derive(Clone, Debug, PartialEq)] +pub struct Located { + /// The program, or the script for a `.py` worker. + pub path: PathBuf, + /// Release tag, from the cache folder name (`occt-8.0.1`); none for the other origins. + pub tag: Option<String>, + /// Where it was found. + pub origin: Origin, + /// Program and arguments that start it. + pub command: Vec<OsString>, +} + +/// The platform's user cache folder (`FORMSHOT_CACHE` replaces it). +pub fn cache_dir() -> Option<PathBuf> { + let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from); + if let Some(p) = env(CACHE_ENV) { + return Some(p); + } + let home = env("HOME").or_else(|| env("USERPROFILE")); + if cfg!(windows) { + return env("LOCALAPPDATA").or_else(|| home.map(|h| h.join("AppData").join("Local"))); + } + if cfg!(target_os = "macos") { + return home.map(|h| h.join("Library").join("Caches")); + } + env("XDG_CACHE_HOME").filter(|p| p.is_absolute()).or_else(|| home.map(|h| h.join(".cache"))) +} + +/// `<cache>/formshot/workers`, where installed workers live, one folder per release tag. +pub fn workers_dir() -> Option<PathBuf> { + cache_dir().map(|c| c.join("formshot").join("workers")) +} + +fn tag_key(tag: &str) -> Vec<u64> { + tag.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).map(|s| s.parse().unwrap_or(0)).collect() +} + +fn script_command(script: &Path) -> Vec<OsString> { + let folder = script.parent().unwrap_or(Path::new(".")); + let venv = [folder.join("venv").join("bin").join("python"), folder.join("venv").join("Scripts").join("python.exe")]; + let python = venv.into_iter().find(|p| p.is_file()).map(PathBuf::into_os_string).unwrap_or_else(|| { + OsString::from(if cfg!(windows) { "python" } else { "python3" }) + }); + vec![python, script.as_os_str().to_owned()] +} + +fn from_file(path: PathBuf, origin: Origin, tag: Option<String>) -> Located { + let is_script = path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("py")); + let command = if is_script { script_command(&path) } else { vec![path.clone().into_os_string()] }; + Located { path, tag, origin, command } +} + +/// Installed tags in the cache folder, newest first. +pub fn installed() -> Vec<(String, PathBuf)> { + let Some(root) = workers_dir() else { return Vec::new() }; + let Ok(entries) = std::fs::read_dir(&root) else { return Vec::new() }; + let mut found: Vec<(String, PathBuf)> = entries + .filter_map(|e| e.ok()) + .filter_map(|e| { + let name = e.file_name().to_str()?.to_string(); + let program = e.path().join(PROGRAM); + (!name.starts_with('.') && program.is_file()).then_some((name, program)) + }) + .collect(); + found.sort_by(|a, b| tag_key(&b.0).cmp(&tag_key(&a.0)).then_with(|| b.0.cmp(&a.0))); + found +} + +/// Finds the worker: `FORMSHOT_CAD_WORKER`, then beside the running program, then the newest tag in the cache. +pub fn locate() -> Result<Located> { + if let Some(raw) = std::env::var_os(WORKER_ENV).filter(|v| !v.is_empty()) { + let path = PathBuf::from(&raw); + if path.is_file() { + return Ok(from_file(path, Origin::Env, None)); + } + return Err(CadError::Missing(format!("{WORKER_ENV} names {}, which is not a file", path.display()))); + } + let beside = std::env::current_exe().ok().and_then(|e| e.parent().map(|d| d.join(PROGRAM))); + if let Some(p) = beside.as_ref().filter(|p| p.is_file()) { + return Ok(from_file(p.clone(), Origin::App, None)); + } + if let Some((tag, program)) = installed().into_iter().next() { + return Ok(from_file(program, Origin::Cache, Some(tag))); + } + let cache = workers_dir().map(|d| d.display().to_string()).unwrap_or_else(|| "no user cache folder".into()); + Err(CadError::Missing(format!( + "no {PROGRAM} in {WORKER_ENV}, beside the app or in {cache}; fetch it with ./formshot cad fetch or from the window" + ))) +} diff --git a/native/crates/fsh-cad/src/mesh.rs b/native/crates/fsh-cad/src/mesh.rs new file mode 100644 index 00000000..c089b19c --- /dev/null +++ b/native/crates/fsh-cad/src/mesh.rs @@ -0,0 +1,122 @@ +use crate::error::{CadError, Result}; + +/// `FCBM` in little-endian order, the first word of a worker `.mesh` file. +pub const MAGIC: u32 = 0x4D42_4346; +/// Layout version this parser reads. +pub const VERSION: u32 = 1; +/// Header size in bytes: 18 words, then the bounding box as six floats. +pub const HEADER: usize = 96; + +/// One B-rep face's run of triangles. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FaceRun { + /// Face index in the shape's face map (0-based). + pub face: u32, + /// First triangle of the run. + pub first: u32, + /// Triangle count. + pub count: u32, + /// OpenCascade surface kind. + pub kind: u32, +} + +/// The triangles of one tessellated body, in millimetres, as the worker wrote them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BodyMesh { + /// Positions. + pub positions: Vec<[f32; 3]>, + /// Normals, one per position (zero where the worker had none). + pub normals: Vec<[f32; 3]>, + /// Triangle list. + pub indices: Vec<u32>, + /// Face index of each triangle. + pub tri_face: Vec<u32>, + /// Face runs. + pub faces: Vec<FaceRun>, +} + +impl BodyMesh { + /// Number of triangles. + pub fn triangle_count(&self) -> usize { + self.indices.len() / 3 + } +} + +fn bad(msg: impl Into<String>) -> CadError { + CadError::Protocol(format!("the tessellation file is damaged: {}", msg.into())) +} + +fn word(b: &[u8], i: usize) -> u32 { + u32::from_le_bytes([b[i * 4], b[i * 4 + 1], b[i * 4 + 2], b[i * 4 + 3]]) +} + +fn section<'a>(b: &'a [u8], offset: u32, count: usize, size: usize, what: &str) -> Result<&'a [u8]> { + let start = offset as usize; + let len = count.checked_mul(size).ok_or_else(|| bad(format!("{what} size overflows")))?; + let end = start.checked_add(len).ok_or_else(|| bad(format!("{what} size overflows")))?; + if count > 0 && (start < HEADER || !start.is_multiple_of(4) || end > b.len()) { + return Err(bad(format!("{what} lies outside the file"))); + } + Ok(if count == 0 { &[] } else { &b[start..end] }) +} + +fn floats3(s: &[u8]) -> Vec<[f32; 3]> { + s.as_chunks::<12>() + .0 + .iter() + .map(|c| { + let f = |k: usize| f32::from_le_bytes([c[k], c[k + 1], c[k + 2], c[k + 3]]); + [f(0), f(4), f(8)] + }) + .collect() +} + +fn words(s: &[u8]) -> Vec<u32> { + s.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect() +} + +/// Parses a worker `.mesh` file; every count and offset is checked against the bytes before anything is read. +pub fn parse(b: &[u8]) -> Result<BodyMesh> { + if b.len() < HEADER { + return Err(bad("shorter than its header")); + } + if word(b, 0) != MAGIC { + return Err(bad("wrong magic")); + } + if word(b, 1) != VERSION { + return Err(bad(format!("layout version {} (this FormShot reads {VERSION})", word(b, 1)))); + } + if word(b, 16) as usize != b.len() { + return Err(bad(format!("header says {} bytes, file has {}", word(b, 16), b.len()))); + } + if fsh_io::deflate::crc32(&b[HEADER..]) != word(b, 17) { + return Err(bad("checksum mismatch")); + } + let nv = word(b, 2) as usize; + let nt = word(b, 3) as usize; + let nf = word(b, 4) as usize; + let off = |k: usize| word(b, 8 + k); + let positions = floats3(section(b, off(0), nv, 12, "positions")?); + let normals = floats3(section(b, off(1), nv, 12, "normals")?); + let indices = words(section(b, off(2), nt, 12, "indices")?); + let tri_face = words(section(b, off(3), nt, 4, "triangle faces")?); + let face_words = words(section(b, off(4), nf, 16, "face table")?); + if indices.iter().any(|&i| i as usize >= nv) { + return Err(bad("a triangle names a vertex that does not exist")); + } + if positions.iter().chain(normals.iter()).flatten().any(|v| !v.is_finite()) { + return Err(bad("a position or normal is not a finite number")); + } + let faces: Vec<FaceRun> = face_words + .as_chunks::<4>() + .0 + .iter() + .map(|w| FaceRun { face: w[0], first: w[1], count: w[2], kind: w[3] }) + .collect(); + for f in &faces { + if (f.first as usize).saturating_add(f.count as usize) > nt { + return Err(bad("a face run passes the last triangle")); + } + } + Ok(BodyMesh { positions, normals, indices, tri_face, faces }) +} diff --git a/native/crates/fsh-cad/src/probe.rs b/native/crates/fsh-cad/src/probe.rs new file mode 100644 index 00000000..e32edf56 --- /dev/null +++ b/native/crates/fsh-cad/src/probe.rs @@ -0,0 +1,145 @@ +use crate::client::Worker; +use crate::error::{CadError, Result}; +use crate::locate::locate; +use crate::read::{CadFormat, ReadOptions}; +use crate::scan::{self, Header}; +use fsh_io::Watch; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +use std::path::Path; + +fn metres_per(unit: &str) -> Option<f64> { + Some(match unit { + "mm" => 0.001, + "cm" => 0.01, + "m" => 1.0, + "in" => 0.0254, + "ft" => 0.3048, + "micron" => 1e-6, + "km" => 1000.0, + _ => return None, + }) +} + +fn header_json(h: &Header) -> Value { + json!({"schema": h.schema, "name": h.name, "system": h.system, "unit": h.unit, "entities": h.entities}) +} + +/// Describes a STEP or IGES file for an import dialog without tessellating it: the header, declared unit and entity +/// counts from the file itself, then, when `use_worker` and the worker is installed, the worker's open (bodies, +/// assembly groups, colours, size). Without the worker the answer says why and carries only what the file says. +pub fn probe(path: &Path, opts: &ReadOptions, use_worker: bool, watch: &Watch) -> Result<Value> { + let bytes = std::fs::read(path).map_err(|e| CadError::File(format!("{} cannot be read: {e}", path.display())))?; + let head = &bytes[..bytes.len().min(512)]; + let format = CadFormat::detect(path, head).ok_or_else(|| CadError::File(format!("{} is not a STEP or IGES file", path.display())))?; + let h = match format { + CadFormat::Step => scan::step(&bytes), + CadFormat::Iges => scan::iges(&bytes), + }; + let declared = h.unit.clone().filter(|u| metres_per(u).is_some()); + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("CAD").to_string(); + let mut out = json!({ + "path": path.to_string_lossy(), + "bytes": bytes.len(), + "name": stem, + "format": format.extension(), + "units_declared": declared, + "units_guess": declared.clone().unwrap_or_else(|| "mm".into()), + "unit_guessed": declared.is_none(), + "up_axis": "z", + "up_axis_declared": false, + "bounds": null, + "triangles": null, + "meshes": null, + "nodes": null, + "materials": null, + "textures": 0, + "warnings": [], + "cad": header_json(&h), + }); + if !use_worker { + out["cad"]["worker"] = json!(false); + out["cad"]["reason"] = json!("the worker was not asked (worker: false)"); + return Ok(out); + } + let located = match opts.worker.clone().map(Ok).unwrap_or_else(locate) { + Ok(l) => l, + Err(e) => { + out["cad"]["worker"] = json!(false); + out["cad"]["reason"] = json!(e.to_string()); + out["cad"]["code"] = json!(e.code()); + return Ok(out); + } + }; + let opened = (|| -> Result<(Value, String)> { + let abs = path.canonicalize().map_err(|e| CadError::File(format!("{} cannot be opened: {e}", path.display())))?; + let mut worker = Worker::start(&located, opts.hello_timeout, Some(watch))?; + let occt = worker.hello().occt.clone(); + let reply = worker.call("xde_read", json!({"path": abs.to_string_lossy(), "unit": "mm", "pmi": false}), opts.timeout, Some(watch))?; + worker.shutdown(); + Ok((reply, occt)) + })(); + let (reply, occt) = match opened { + Ok(r) => r, + Err(CadError::Cancelled) => return Err(CadError::Cancelled), + Err(e) => { + out["cad"]["worker"] = json!(false); + out["cad"]["reason"] = json!(e.to_string()); + out["cad"]["code"] = json!(e.code()); + return Ok(out); + } + }; + let bodies = reply.get("bodies").and_then(Value::as_array).cloned().unwrap_or_default(); + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + let mut groups: BTreeSet<Vec<String>> = BTreeSet::new(); + let mut colours: BTreeSet<String> = BTreeSet::new(); + let mut defs: BTreeSet<String> = BTreeSet::new(); + let mut faces = 0u64; + for b in &bodies { + if let Some(bb) = b.pointer("/summary/bbox").and_then(Value::as_array).filter(|a| a.len() == 6) { + let v: Vec<f64> = bb.iter().filter_map(Value::as_f64).collect(); + if v.len() == 6 { + for k in 0..3 { + lo[k] = lo[k].min(v[k]); + hi[k] = hi[k].max(v[k + 3]); + } + } + } + faces += b.pointer("/summary/faces").and_then(Value::as_u64).unwrap_or(0); + let path: Vec<String> = b.get("path").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); + for d in 1..=path.len() { + groups.insert(path[..d].to_vec()); + } + if let Some(c) = b.get("rgb").filter(|c| c.is_array()) { + colours.insert(c.to_string()); + } + if let Some(d) = b.get("def").and_then(Value::as_str).filter(|_| format == CadFormat::Step) { + defs.insert(d.to_string()); + } + } + if format == CadFormat::Iges && colours.is_empty() { + colours.extend(h.solids.iter().filter_map(|s| s.rgb).map(|c| format!("{c:?}"))); + } + let unit = declared.clone().unwrap_or_else(|| "mm".into()); + let per = metres_per(&unit).unwrap_or(0.001); + if lo[0].is_finite() && hi[0] >= lo[0] { + let to_file = 0.001 / per; + let f = |a: [f64; 3]| json!([a[0] * to_file, a[1] * to_file, a[2] * to_file]); + let size = [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]; + out["bounds"] = json!({"min": f(lo), "max": f(hi), "size": f(size), "size_m": [size[0] * 0.001, size[1] * 0.001, size[2] * 0.001]}); + } + out["nodes"] = json!(bodies.len() + groups.len()); + out["materials"] = json!(colours.len()); + out["cad"]["worker"] = json!(true); + out["cad"]["bodies"] = json!(bodies.len()); + out["cad"]["groups"] = json!(groups.len()); + out["cad"]["faces"] = json!(faces); + out["cad"]["distinct_shapes"] = json!(if format == CadFormat::Step { Some(defs.len()) } else { None }); + out["cad"]["colours_in_file"] = reply.get("colours_in_file").cloned().unwrap_or(Value::Null); + out["cad"]["occt"] = json!(occt); + if let Some(list) = reply.get("untranslated").and_then(Value::as_array).filter(|a| !a.is_empty()) { + out["warnings"] = json!([format!("{} entities had no geometry the worker could translate", list.len())]); + } + Ok(out) +} diff --git a/native/crates/fsh-cad/src/quality.rs b/native/crates/fsh-cad/src/quality.rs new file mode 100644 index 00000000..f784360b --- /dev/null +++ b/native/crates/fsh-cad/src/quality.rs @@ -0,0 +1,106 @@ +use serde_json::{json, Value}; + +/// Smallest chord deviation sent to the worker, in millimetres. +pub const MIN_LINEAR_MM: f64 = 1.0e-4; + +/// How finely CAD surfaces become triangles. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum Quality { + /// Quick look: coarse curves. + Draft, + /// The default. + #[default] + Medium, + /// Close-ups. + High, + /// Hero shots of curved parts. + Ultra, + /// `chord`: largest distance between a triangle and the surface, as a fraction of the model's + /// bounding-box diagonal; `angle`: largest angle between neighbouring triangle normals, in degrees. + Custom { chord: f64, angle: f64 }, +} + +impl Quality { + /// The named presets. + pub const PRESETS: [Quality; 4] = [Quality::Draft, Quality::Medium, Quality::High, Quality::Ultra]; + + /// Chord as a fraction of the diagonal and angle in degrees. + pub fn chord_angle(self) -> (f64, f64) { + match self { + Quality::Draft => (2.0e-3, 30.0), + Quality::Medium => (5.0e-4, 20.0), + Quality::High => (1.5e-4, 12.0), + Quality::Ultra => (5.0e-5, 6.0), + Quality::Custom { chord, angle } => (chord, angle), + } + } + + /// Worker deflections for a model whose bounding-box diagonal is `diagonal_mm`: linear in mm, angular in radians. + pub fn deflection(self, diagonal_mm: f64) -> (f64, f64) { + let (chord, angle) = self.chord_angle(); + let d = if diagonal_mm.is_finite() && diagonal_mm > 0.0 { diagonal_mm } else { 1.0 }; + ((chord * d).max(MIN_LINEAR_MM), angle.to_radians()) + } + + /// Preset name, or "custom". + pub fn name(self) -> &'static str { + match self { + Quality::Draft => "draft", + Quality::Medium => "medium", + Quality::High => "high", + Quality::Ultra => "ultra", + Quality::Custom { .. } => "custom", + } + } + + /// `"draft"` .. `"ultra"`, or `{chord, angle}` for a custom setting. + pub fn to_json(self) -> Value { + match self { + Quality::Custom { chord, angle } => json!({"chord": chord, "angle": angle}), + q => json!(q.name()), + } + } + + /// Compact text kept in node metadata: the preset name, or `chord,angle`. + pub fn to_text(self) -> String { + match self { + Quality::Custom { chord, angle } => format!("{chord},{angle}"), + q => q.name().to_string(), + } + } + + /// Reads [`Quality::to_text`] back. + pub fn from_text(s: &str) -> Option<Quality> { + if let Some((c, a)) = s.split_once(',') { + return Quality::custom(c.trim().parse().ok()?, a.trim().parse().ok()?).ok(); + } + Quality::PRESETS.into_iter().find(|q| q.name() == s.trim().to_ascii_lowercase()) + } + + /// A checked custom quality: chord in (0, 0.1], angle in [1, 90] degrees. + pub fn custom(chord: f64, angle: f64) -> Result<Quality, String> { + if !(chord.is_finite() && chord > 0.0 && chord <= 0.1) { + return Err(format!("chord {chord} must be above 0 and at most 0.1 (a fraction of the model's diagonal)")); + } + if !(angle.is_finite() && (1.0..=90.0).contains(&angle)) { + return Err(format!("angle {angle} must be 1 to 90 degrees")); + } + Ok(Quality::Custom { chord, angle }) + } + + /// Parses `"draft"`, `"medium"`, `"high"`, `"ultra"` or `{chord, angle}`; null means the default. + pub fn from_json(v: &Value) -> Result<Quality, String> { + match v { + Value::Null => Ok(Quality::default()), + Value::String(s) => Quality::PRESETS + .into_iter() + .find(|q| q.name() == s.trim().to_ascii_lowercase()) + .ok_or_else(|| format!("{s:?} is not draft, medium, high, ultra or {{chord, angle}}")), + Value::Object(o) => { + let num = |k: &str| o.get(k).and_then(Value::as_f64).ok_or_else(|| format!("a custom quality needs a number {k}")); + Quality::custom(num("chord")?, num("angle")?) + } + other => Err(format!("{other} is not draft, medium, high, ultra or {{chord, angle}}")), + } + } +} diff --git a/native/crates/fsh-cad/src/read.rs b/native/crates/fsh-cad/src/read.rs new file mode 100644 index 00000000..16001a5e --- /dev/null +++ b/native/crates/fsh-cad/src/read.rs @@ -0,0 +1,677 @@ +use crate::client::Worker; +use crate::error::{CadError, Result}; +use crate::locate::{locate, Located}; +use crate::mesh::{self, BodyMesh}; +use crate::quality::Quality; +use fsh_core::{LengthUnit, Mat4, Vec3}; +use fsh_io::{RawMaterial, RawMesh, RawNode, RawScene, Stage, UpAxis, Watch}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +/// Environment variable giving the per-request timeout in seconds. +pub const TIMEOUT_ENV: &str = "FORMSHOT_CAD_TIMEOUT"; +/// Environment variable giving the longest wait in seconds for the worker to start and say hello. +pub const HELLO_TIMEOUT_ENV: &str = "FORMSHOT_CAD_HELLO_TIMEOUT"; +/// Hello wait when the environment does not set one: a cold start of the worker on a busy machine. +pub const HELLO_TIMEOUT_SECS: u64 = 120; + +/// The hello wait: [`HELLO_TIMEOUT_ENV`] when it holds a positive number of seconds, else [`HELLO_TIMEOUT_SECS`]. +pub fn hello_timeout() -> Duration { + let secs = std::env::var(HELLO_TIMEOUT_ENV).ok().and_then(|s| s.trim().parse::<u64>().ok()).filter(|s| *s > 0); + Duration::from_secs(secs.unwrap_or(HELLO_TIMEOUT_SECS)) +} +const MM: f64 = 0.001; +const RETRIES: u32 = 2; +const MAX_BODIES: usize = 5000; + +/// CAD exchange formats the worker opens. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CadFormat { + /// ISO 10303-21 (STEP). + Step, + /// IGES 5.x. + Iges, +} + +impl CadFormat { + /// Lower-case extension the worker accepts. + pub fn extension(self) -> &'static str { + match self { + CadFormat::Step => "step", + CadFormat::Iges => "iges", + } + } + + /// Format named by a file extension (step, stp, iges, igs). + pub fn from_extension(ext: &str) -> Option<CadFormat> { + match ext.trim_start_matches('.').to_ascii_lowercase().as_str() { + "step" | "stp" => Some(CadFormat::Step), + "iges" | "igs" => Some(CadFormat::Iges), + _ => None, + } + } + + /// Format of a file: its extension, else its first bytes. + pub fn detect(path: &Path, head: &[u8]) -> Option<CadFormat> { + if let Some(f) = path.extension().and_then(|e| e.to_str()).and_then(CadFormat::from_extension) { + return Some(f); + } + let start = head.iter().position(|b| !b.is_ascii_whitespace()).map(|i| &head[i..]).unwrap_or(&[]); + if start.starts_with(b"ISO-10303-21") { + return Some(CadFormat::Step); + } + let first = head.split(|&b| b == b'\n').next().unwrap_or(&[]); + let first = first.strip_suffix(b"\r").unwrap_or(first); + (first.len() == 80 && first[72] == b'S').then_some(CadFormat::Iges) + } +} + +/// True when the path's extension is one of the CAD formats. +pub fn is_cad_path(path: &Path) -> bool { + path.extension().and_then(|e| e.to_str()).and_then(CadFormat::from_extension).is_some() +} + +/// How to read a CAD file. +#[derive(Clone, Debug)] +pub struct ReadOptions { + /// Tessellation quality. + pub quality: Quality, + /// Longest wait for one worker answer (the open, or one body's tessellation). + pub timeout: Duration, + /// Longest wait for the worker to start and say hello. + pub hello_timeout: Duration, + /// Worker to use; found with [`locate`] when absent. + pub worker: Option<Located>, +} + +impl Default for ReadOptions { + fn default() -> Self { + let secs = std::env::var(TIMEOUT_ENV).ok().and_then(|s| s.trim().parse::<u64>().ok()).filter(|s| *s > 0).unwrap_or(600); + Self { quality: Quality::default(), timeout: Duration::from_secs(secs), hello_timeout: hello_timeout(), worker: None } + } +} + +/// Which body and colour slot a raw mesh came from; stable for the same file and worker, whatever the quality. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MeshTag { + /// Body index in the worker's reading order. + pub body: usize, + /// Colour slot within the body (0 is the body colour; later slots are face colours). + pub slot: usize, +} + +/// A CAD file read into a raw scene, with what the reader decided. +#[derive(Clone, Debug)] +pub struct CadRead { + /// The scene: Z up, metres, one node per body under groups for its assembly path. + pub scene: RawScene, + /// One tag per mesh of `scene`. + pub tags: Vec<MeshTag>, + /// The body each node shows, per node of `scene` (none for assembly groups). + pub node_body: Vec<Option<usize>>, + /// Bodies the worker returned. + pub bodies: usize, + /// Bodies drawn with another body's mesh and a transform. + pub shared: usize, + /// Format read. + pub format: CadFormat, + /// Bounding-box diagonal of the model in millimetres. + pub diagonal_mm: f64, + /// Linear deflection asked of the worker, in millimetres. + pub linear_mm: f64, + /// Angular deflection asked of the worker, in radians. + pub angular_rad: f64, + /// Quality asked for. + pub quality: Quality, + /// Worker's OpenCascade version. + pub occt: String, + /// Worker release tag when it came from the cache. + pub tag: Option<String>, +} + +#[derive(Clone, Debug, Default)] +struct Body { + id: String, + name: String, + rgb: Option<[f32; 3]>, + path: Vec<String>, + def: String, + bbox: Option<[f64; 6]>, + face_rgb: Vec<Option<[f32; 3]>>, + faces: usize, +} + +fn rgb_of(v: &Value) -> Option<[f32; 3]> { + let a = v.as_array()?; + if a.len() != 3 { + return None; + } + let mut out = [0.0f32; 3]; + for (o, x) in out.iter_mut().zip(a) { + let f = x.as_f64().filter(|f| f.is_finite())?; + *o = f.clamp(0.0, 1.0) as f32; + } + Some(out) +} + +fn bbox_of(v: &Value) -> Option<[f64; 6]> { + let a = v.as_array()?; + if a.len() != 6 { + return None; + } + let mut out = [0.0f64; 6]; + for (o, x) in out.iter_mut().zip(a) { + *o = x.as_f64().filter(|f| f.is_finite())?; + } + (out[0] <= out[3] && out[1] <= out[4] && out[2] <= out[5]).then_some(out) +} + +fn text(v: Option<&Value>) -> String { + v.and_then(Value::as_str).map(|s| s.chars().filter(|c| !c.is_control()).take(256).collect()).unwrap_or_default() +} + +fn parse_bodies(reply: &Value) -> Result<Vec<Body>> { + let list = reply + .get("bodies") + .and_then(Value::as_array) + .ok_or_else(|| CadError::Protocol("the open reply has no bodies list".into()))?; + let mut out = Vec::with_capacity(list.len().min(MAX_BODIES)); + for (i, b) in list.iter().take(MAX_BODIES).enumerate() { + let id = b.get("id").and_then(Value::as_str).filter(|s| !s.is_empty() && s.len() < 64); + let id = id.ok_or_else(|| CadError::Protocol(format!("body {i} has no shape id")))?.to_string(); + out.push(Body { + id, + name: text(b.get("name")), + rgb: b.get("rgb").and_then(rgb_of), + path: b + .get("path") + .and_then(Value::as_array) + .map(|a| a.iter().take(64).map(|s| text(Some(s))).filter(|s| !s.is_empty()).collect()) + .unwrap_or_default(), + def: text(b.get("def")), + bbox: b.get("summary").and_then(|s| s.get("bbox")).and_then(bbox_of), + faces: b.pointer("/summary/faces").and_then(Value::as_u64).unwrap_or(0) as usize, + face_rgb: b + .get("face_rgb") + .and_then(Value::as_array) + .map(|a| a.iter().take(1 << 20).map(rgb_of).collect()) + .unwrap_or_default(), + }); + } + if out.is_empty() { + return Err(CadError::File("the file holds no solids or surfaces".into())); + } + Ok(out) +} + +struct TempDir(PathBuf); + +impl TempDir { + fn new() -> Result<TempDir> { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let dir = std::env::temp_dir().join(format!( + "formshot-cad-{}-{nanos}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).map_err(|e| CadError::File(format!("no scratch folder for the worker: {e}")))?; + Ok(TempDir(dir)) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn srgb_hex(c: [f32; 3]) -> String { + let enc = |v: f32| { + let v = v.clamp(0.0, 1.0); + let s = if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + (s * 255.0).round().clamp(0.0, 255.0) as u8 + }; + format!("#{:02X}{:02X}{:02X}", enc(c[0]), enc(c[1]), enc(c[2])) +} + +fn colour_key(c: [f32; 3]) -> [i32; 3] { + c.map(|v| (v * 10000.0).round() as i32) +} + +type M3 = [[f64; 3]; 3]; + +fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn dot(a: [f64; 3], b: [f64; 3]) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn len(a: [f64; 3]) -> f64 { + dot(a, a).sqrt() +} + +fn cols(a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> M3 { + [[a[0], b[0], c[0]], [a[1], b[1], c[1]], [a[2], b[2], c[2]]] +} + +fn inverse3(m: &M3) -> Option<M3> { + let det = m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); + if !det.is_finite() || det.abs() < 1e-300 { + return None; + } + let mut inv = [[0.0; 3]; 3]; + for (r, row) in inv.iter_mut().enumerate() { + for (c, v) in row.iter_mut().enumerate() { + let (r1, r2) = ((c + 1) % 3, (c + 2) % 3); + let (c1, c2) = ((r + 1) % 3, (r + 2) % 3); + *v = (m[r1][c1] * m[r2][c2] - m[r1][c2] * m[r2][c1]) / det; + } + } + Some(inv) +} + +fn mul3(a: &M3, b: &M3) -> M3 { + let mut o = [[0.0; 3]; 3]; + for (r, row) in o.iter_mut().enumerate() { + for (c, v) in row.iter_mut().enumerate() { + *v = (0..3).map(|k| a[r][k] * b[k][c]).sum(); + } + } + o +} + +fn p64(p: [f32; 3]) -> [f64; 3] { + [p[0] as f64, p[1] as f64, p[2] as f64] +} + +fn farthest(points: &[[f32; 3]], score: impl Fn([f64; 3]) -> f64) -> usize { + let mut best = (0usize, -1.0f64); + for (i, p) in points.iter().enumerate() { + let s = score(p64(*p)); + if s > best.1 { + best = (i, s); + } + } + best.0 +} + +fn frame(points: &[[f32; 3]], idx: [usize; 3], scale: f64) -> Option<(M3, [f64; 3])> { + let p0 = p64(*points.get(idx[0])?); + let e1 = sub(p64(*points.get(idx[1])?), p0); + let e2 = sub(p64(*points.get(idx[2])?), p0); + let n = cross(e1, e2); + let ln = len(n); + if ln <= 0.0 { + return None; + } + let e3 = n.map(|v| v / ln * scale); + Some((cols(e1, e2, e3), p0)) +} + +fn relative_transform(owner: &BodyMesh, other: &BodyMesh, tol: f64) -> Option<(M3, [f64; 3])> { + if owner.positions.len() != other.positions.len() || owner.indices != other.indices || owner.positions.len() < 3 { + return None; + } + let pts = &owner.positions; + let p0 = p64(pts[0]); + let i1 = farthest(pts, |p| len(sub(p, p0))); + let a = sub(p64(pts[i1]), p0); + let i2 = farthest(pts, |p| len(cross(a, sub(p, p0)))); + let scale = len(a).max(1e-9); + let (e, o) = frame(pts, [0, i1, i2], scale)?; + let (f, q) = frame(&other.positions, [0, i1, i2], scale)?; + let a3 = mul3(&f, &inverse3(&e)?); + let t = sub(q, [dot(a3[0], o), dot(a3[1], o), dot(a3[2], o)]); + for (p, q) in owner.positions.iter().zip(&other.positions) { + let p = p64(*p); + let mapped = [dot(a3[0], p) + t[0], dot(a3[1], p) + t[1], dot(a3[2], p) + t[2]]; + if len(sub(mapped, p64(*q))) > tol { + return None; + } + } + Some((a3, t)) +} + +fn mat_metres(a: &M3, t: [f64; 3]) -> Mat4 { + Mat4::from_rows([ + [a[0][0] as f32, a[0][1] as f32, a[0][2] as f32, (t[0] * MM) as f32], + [a[1][0] as f32, a[1][1] as f32, a[1][2] as f32, (t[1] * MM) as f32], + [a[2][0] as f32, a[2][1] as f32, a[2][2] as f32, (t[2] * MM) as f32], + [0.0, 0.0, 0.0, 1.0], + ]) +} + +fn slot_meshes(body: &Body, m: &BodyMesh) -> Vec<(Option<[f32; 3]>, Vec<usize>)> { + if body.face_rgb.iter().all(Option::is_none) { + return vec![(body.rgb, (0..m.triangle_count()).collect())]; + } + let mut slots: Vec<(Option<[f32; 3]>, Vec<usize>)> = vec![(body.rgb, Vec::new())]; + let mut by_key: HashMap<[i32; 3], usize> = HashMap::new(); + for t in 0..m.triangle_count() { + let face = m.tri_face.get(t).copied().unwrap_or(0) as usize; + match body.face_rgb.get(face).copied().flatten() { + Some(c) if body.rgb.map(colour_key) != Some(colour_key(c)) => { + let s = *by_key.entry(colour_key(c)).or_insert_with(|| { + slots.push((Some(c), Vec::new())); + slots.len() - 1 + }); + slots[s].1.push(t); + } + _ => slots[0].1.push(t), + } + } + slots +} + +fn raw_mesh(name: String, m: &BodyMesh, tris: &[usize]) -> RawMesh { + let mut remap: HashMap<u32, u32> = HashMap::new(); + let mut positions = Vec::new(); + let mut normals = Vec::new(); + let mut indices = Vec::with_capacity(tris.len() * 3); + let mut normals_ok = true; + for &t in tris { + for k in 0..3 { + let v = m.indices[t * 3 + k]; + let id = *remap.entry(v).or_insert_with(|| { + let p = m.positions[v as usize]; + positions.push(Vec3::new((p[0] as f64 * MM) as f32, (p[1] as f64 * MM) as f32, (p[2] as f64 * MM) as f32)); + let n = m.normals.get(v as usize).copied().unwrap_or([0.0; 3]); + let n = Vec3::new(n[0], n[1], n[2]); + let l = n.length(); + if l.is_finite() && l > 1e-6 { + normals.push(n / l); + } else { + normals_ok = false; + normals.push(Vec3::Y); + } + (positions.len() - 1) as u32 + }); + indices.push(id); + } + } + RawMesh { name, positions, normals: if normals_ok { normals } else { Vec::new() }, indices, ..Default::default() } +} + +fn worker_path(path: &Path, format: CadFormat, scratch: &TempDir) -> Result<PathBuf> { + let abs = path.canonicalize().map_err(|e| CadError::File(format!("{} cannot be opened: {e}", path.display())))?; + if is_cad_path(&abs) { + return Ok(abs); + } + let copy = scratch.0.join(format!("source.{}", format.extension())); + std::fs::copy(&abs, ©).map_err(|e| CadError::File(format!("{} cannot be copied for the worker: {e}", abs.display())))?; + Ok(copy) +} + +fn open(worker: &mut Worker, path: &Path, format: CadFormat, opts: &ReadOptions, watch: &Watch) -> Result<Value> { + let p = path.to_string_lossy().to_string(); + if worker.hello().has("xde_read") || worker.hello().methods.is_empty() { + match worker.call("xde_read", json!({"path": p, "unit": "mm", "pmi": false}), opts.timeout, Some(watch)) { + Err(CadError::Worker(m)) if m.starts_with("Unknown method") => {} + other => return other, + } + } + let method = match format { + CadFormat::Step => "open_step", + CadFormat::Iges => "open_iges", + }; + worker.call(method, json!({"path": p}), opts.timeout, Some(watch)) +} + +fn tessellate(worker: &mut Worker, id: &str, linear: f64, angular: f64, out: &Path, opts: &ReadOptions, watch: &Watch) -> Result<(BodyMesh, f64)> { + let mut lin = linear; + for attempt in 0..=RETRIES { + let params = json!({"id": id, "linear": lin, "angular": angular, "path": out.to_string_lossy()}); + match worker.call("tessellate", params, opts.timeout, Some(watch)) { + Ok(_) => { + let bytes = std::fs::read(out).map_err(|e| CadError::Protocol(format!("the worker's tessellation file is missing: {e}")))?; + let _ = std::fs::remove_file(out); + return Ok((mesh::parse(&bytes)?, lin)); + } + Err(CadError::Worker(m)) if m.contains("too fine") && attempt < RETRIES => lin *= 4.0, + Err(e) => return Err(e), + } + } + Err(CadError::Worker("the tessellation stayed too fine".into())) +} + +fn synthetic_name(name: &str, index: usize) -> bool { + name.is_empty() || name.rsplit_once(' ').is_some_and(|(_, n)| n == (index + 1).to_string()) +} + +/// The worker's XDE read gives IGES bodies no colour and numbered names. When the file's manifold solids match the +/// bodies one to one (same count, directory order), their colours and names are taken from the file; otherwise a +/// note says why not. +fn iges_colours(path: &Path, bodies: &mut [Body]) -> Option<String> { + let bytes = std::fs::read(path).ok()?; + let h = crate::scan::iges(&bytes); + if h.solids.iter().all(|s| s.rgb.is_none() && s.name.is_empty()) { + return None; + } + if h.solids.len() != bodies.len() { + return Some(format!( + "the IGES file has {} solids for {} bodies, so its colours and names could not be matched and were left out", + h.solids.len(), + bodies.len() + )); + } + for (i, (b, s)) in bodies.iter_mut().zip(h.solids).enumerate() { + b.rgb = s.rgb; + if synthetic_name(&b.name, i) && !s.name.is_empty() { + b.name = s.name; + } + } + None +} + +const FACE_COLOUR_SCAN_BYTES: u64 = 256 << 20; + +/// The worker reports one colour per body. A STEP file that styles single faces has them read here: each body takes +/// the face colours of the one manifold solid with its face count (the worker numbers faces in shell order). Bodies +/// whose face count several differently coloured solids share keep their body colour, and a note says so. +fn step_face_colours(path: &Path, bodies: &mut [Body]) -> Option<String> { + if std::fs::metadata(path).ok()?.len() > FACE_COLOUR_SCAN_BYTES { + return None; + } + let bytes = std::fs::read(path).ok()?; + let solids = crate::scan::step_face_colours(&bytes); + if solids.is_empty() { + return None; + } + let mut ambiguous = 0usize; + for b in bodies.iter_mut() { + let same: Vec<&crate::scan::StepSolid> = solids.iter().filter(|s| s.faces.len() == b.faces && b.faces > 0).collect(); + let Some(first) = same.first() else { continue }; + if same.iter().any(|s| s.faces != first.faces) { + ambiguous += 1; + continue; + } + if first.faces.iter().any(Option::is_some) { + b.face_rgb = first.faces.clone(); + } + } + (ambiguous > 0).then(|| format!("{ambiguous} bodies have a face count that several differently coloured solids share, so their face colours were left out")) +} + +/// Opens a STEP or IGES file with the worker and tessellates every body at the asked quality. +pub fn read(path: &Path, opts: &ReadOptions, watch: &Watch) -> Result<CadRead> { + watch.step(Stage::Reading, 0.0).map_err(|_| CadError::Cancelled)?; + let mut head = vec![0u8; 512]; + let n = std::fs::File::open(path) + .and_then(|mut f| std::io::Read::read(&mut f, &mut head)) + .map_err(|e| CadError::File(format!("{} cannot be read: {e}", path.display())))?; + head.truncate(n); + let format = CadFormat::detect(path, &head).ok_or_else(|| CadError::File(format!("{} is not a STEP or IGES file", path.display())))?; + let located = match &opts.worker { + Some(l) => l.clone(), + None => locate()?, + }; + let scratch = TempDir::new()?; + let source = worker_path(path, format, &scratch)?; + let mut worker = Worker::start(&located, opts.hello_timeout, Some(watch))?; + let occt = worker.hello().occt.clone(); + watch.step(Stage::Reading, 0.02).map_err(|_| CadError::Cancelled)?; + let reply = open(&mut worker, &source, format, opts, watch)?; + let mut bodies = parse_bodies(&reply)?; + let mut warnings: Vec<String> = Vec::new(); + if format == CadFormat::Iges && bodies.iter().all(|b| b.rgb.is_none()) { + if let Some(note) = iges_colours(path, &mut bodies) { + warnings.push(note); + } + } + if format == CadFormat::Step && bodies.iter().all(|b| b.face_rgb.is_empty()) { + if let Some(note) = step_face_colours(path, &mut bodies) { + warnings.push(note); + } + } + if let Some(list) = reply.get("untranslated").and_then(Value::as_array).filter(|a| !a.is_empty()) { + let names: Vec<String> = list.iter().take(8).map(|v| text(Some(v))).collect(); + warnings.push(format!("{} entities had no geometry the worker could translate ({})", list.len(), names.join(", "))); + } + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for b in bodies.iter().filter_map(|b| b.bbox) { + for k in 0..3 { + lo[k] = lo[k].min(b[k]); + hi[k] = hi[k].max(b[k + 3]); + } + } + let diagonal_mm = len(sub(hi, lo)); + if !diagonal_mm.is_finite() || diagonal_mm <= 0.0 { + return Err(CadError::File("the model has no usable size (check the length unit in the file)".into())); + } + let (linear, angular) = opts.quality.deflection(diagonal_mm); + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("CAD").to_string(); + let mut scene = RawScene::named(stem.clone()); + scene.unit = Some(LengthUnit::Metre); + scene.up_axis = Some(UpAxis::Z); + let mut tags = Vec::new(); + let mut node_body = Vec::new(); + let mut materials: HashMap<[i32; 3], usize> = HashMap::new(); + let mut groups: HashMap<Vec<String>, usize> = HashMap::new(); + let mut owners: HashMap<String, Vec<(usize, BodyMesh, Vec<usize>)>> = HashMap::new(); + let mut shared = 0usize; + let mut coarsened = 0usize; + let mut empty = 0usize; + let total = bodies.len(); + for (bi, body) in bodies.iter().enumerate() { + watch.step(Stage::Reading, 0.1 + 0.9 * bi as f32 / total as f32).map_err(|_| CadError::Cancelled)?; + let out = scratch.0.join(format!("b{bi}.mesh")); + let (m, used) = tessellate(&mut worker, &body.id, linear, angular, &out, opts, watch)?; + if used > linear { + coarsened += 1; + } + if m.triangle_count() == 0 { + empty += 1; + continue; + } + let mut parent = None; + for depth in 1..=body.path.len() { + let key = body.path[..depth].to_vec(); + let idx = match groups.get(&key) { + Some(&g) => g, + None => { + scene.nodes.push(RawNode::new(key[depth - 1].clone(), parent, Vec::new())); + node_body.push(None); + groups.insert(key, scene.nodes.len() - 1); + scene.nodes.len() - 1 + } + }; + parent = Some(idx); + } + let name = if body.name.is_empty() { format!("{stem} {}", bi + 1) } else { body.name.clone() }; + let tol = (diagonal_mm * 1e-6).max(1e-6) + used * 1e-3; + let reuse = if body.def.is_empty() { + None + } else { + owners.get(&body.def).and_then(|list| { + list.iter().find_map(|(ob, om, meshes)| { + let same_colour = bodies[*ob].rgb.map(colour_key) == body.rgb.map(colour_key) && bodies[*ob].face_rgb == body.face_rgb; + if !same_colour { + return None; + } + relative_transform(om, &m, tol).map(|(a, t)| (meshes.clone(), mat_metres(&a, t))) + }) + }) + }; + let mut node = RawNode::new(name.clone(), parent, Vec::new()); + if let Some((meshes, xf)) = reuse { + node.meshes = meshes; + node.transform = xf; + shared += 1; + } else { + let slots = slot_meshes(body, &m); + let several = slots.iter().filter(|s| !s.1.is_empty()).count() > 1; + let mut ids = Vec::new(); + for (si, (colour, tris)) in slots.iter().enumerate() { + if tris.is_empty() { + continue; + } + let mesh_name = match (several, colour) { + (true, Some(c)) => format!("{name} {}", srgb_hex(*c)), + _ => name.clone(), + }; + let mut raw = raw_mesh(mesh_name, &m, tris); + if let Some(c) = colour { + let next = scene.materials.len(); + let mi = *materials.entry(colour_key(*c)).or_insert(next); + if mi == next { + scene.materials.push(RawMaterial { + name: format!("Colour {}", srgb_hex(*c)), + base_colour: *c, + roughness: 0.4, + ..RawMaterial::default() + }); + } + raw.material = Some(mi); + } + scene.meshes.push(raw); + tags.push(MeshTag { body: bi, slot: si }); + ids.push(scene.meshes.len() - 1); + } + node.meshes = ids.clone(); + if !body.def.is_empty() { + owners.entry(body.def.clone()).or_default().push((bi, m, ids)); + } + } + scene.nodes.push(node); + node_body.push(Some(bi)); + } + worker.shutdown(); + if scene.meshes.is_empty() { + let what = if total == 1 { "its one body is".to_string() } else { format!("all {total} of its bodies are") }; + return Err(CadError::File(format!("the file holds no surfaces to draw: {what} curves or points only"))); + } + if empty > 0 { + warnings.push(format!("{empty} bodies have no surfaces (curves or points only) and were left out")); + } + if coarsened > 0 { + warnings.push(format!("{coarsened} bodies were too fine at this quality and were tessellated coarser")); + } + scene.warnings = warnings; + watch.set(Stage::Reading, 1.0); + Ok(CadRead { + scene, + tags, + node_body, + bodies: total, + shared, + format, + diagonal_mm, + linear_mm: linear, + angular_rad: angular, + quality: opts.quality, + occt, + tag: located.tag.clone(), + }) +} diff --git a/native/crates/fsh-cad/src/scan.rs b/native/crates/fsh-cad/src/scan.rs new file mode 100644 index 00000000..8bd4a72d --- /dev/null +++ b/native/crates/fsh-cad/src/scan.rs @@ -0,0 +1,425 @@ +//! What a STEP or IGES file says about itself without the worker: header, length unit, entity counts, and for IGES +//! the colour and label of each solid (the worker's XDE read drops IGES colours). + +use std::collections::BTreeMap; + +/// Length unit a file declares, as FormShot names units (mm, cm, m, in, ft), or the file's own name for others. +pub type Unit = String; + +/// One IGES manifold solid (entity 186) in directory order. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct IgesSolid { + /// Colour in linear RGB 0..1, when the solid has one. + pub rgb: Option<[f32; 3]>, + /// Name from the solid's name property (406 form 15), else its directory label. + pub name: String, +} + +/// Header facts of a CAD file. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Header { + /// Schema (STEP) or empty. + pub schema: String, + /// File name written in the header. + pub name: String, + /// The system that wrote the file. + pub system: String, + /// Declared length unit. + pub unit: Option<Unit>, + /// Counts of the entities that tell what the file holds. + pub entities: BTreeMap<String, usize>, + /// IGES solids with their colours and names, in directory order. + pub solids: Vec<IgesSolid>, +} + +const STEP_COUNTED: &[&str] = &[ + "PRODUCT", + "NEXT_ASSEMBLY_USAGE_OCCURRENCE", + "MANIFOLD_SOLID_BREP", + "BREP_WITH_VOIDS", + "SHELL_BASED_SURFACE_MODEL", + "ADVANCED_FACE", + "COLOUR_RGB", + "STYLED_ITEM", + "MAPPED_ITEM", +]; + +fn srgb_to_linear(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.040_45 { + v / 12.92 + } else { + ((v + 0.055) / 1.055).powf(2.4) + } +} + +fn quoted(s: &str) -> Vec<String> { + let mut out = Vec::new(); + let mut cur: Option<String> = None; + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + match (&mut cur, c) { + (None, '\'') => cur = Some(String::new()), + (Some(t), '\'') if chars.peek() == Some(&'\'') => { + t.push('\''); + chars.next(); + } + (Some(_), '\'') => out.extend(cur.take()), + (Some(t), c) => t.push(c), + _ => {} + } + } + out +} + +fn entity_text<'a>(text: &'a str, keyword: &str) -> Option<&'a str> { + let at = text.find(keyword)?; + let end = text[at..].find(';').map(|e| at + e).unwrap_or(text.len()); + Some(&text[at..end]) +} + +fn count_keyword(text: &str, keyword: &str) -> usize { + let bytes = text.as_bytes(); + let mut n = 0; + let mut from = 0; + while let Some(i) = text[from..].find(keyword) { + let at = from + i; + let before = at.checked_sub(1).map(|b| bytes[b]); + let after = bytes.get(at + keyword.len()).copied(); + let starts = before.is_none_or(|b| !(b.is_ascii_alphanumeric() || b == b'_')); + if starts && matches!(after, Some(b'(') | Some(b' ')) { + n += 1; + } + from = at + keyword.len(); + } + n +} + +fn step_unit(text: &str) -> Option<Unit> { + let mut from = 0; + while let Some(i) = text[from..].find("LENGTH_UNIT") { + let at = from + i; + from = at + 11; + let start = text[..at].rfind('=').unwrap_or(0); + let end = text[at..].find(';').map(|e| at + e).unwrap_or(text.len()); + let entity = &text[start..end]; + if entity.contains("CONVERSION_BASED_UNIT") { + let name = quoted(entity).into_iter().next().unwrap_or_default().to_ascii_uppercase(); + return Some( + match name.as_str() { + "INCH" | "IN" => "in", + "FOOT" | "FT" => "ft", + "MILLIMETRE" | "MILLIMETER" | "MM" => "mm", + "CENTIMETRE" | "CENTIMETER" | "CM" => "cm", + "METRE" | "METER" | "M" => "m", + other => return Some(other.to_ascii_lowercase()), + } + .to_string(), + ); + } + if let Some(si) = entity.find("SI_UNIT(") { + let args = &entity[si + 8..]; + let prefix = args.split(',').next().unwrap_or("").trim(); + return Some( + match prefix { + ".MILLI." => "mm", + ".CENTI." => "cm", + ".MICRO." => "micron", + ".KILO." => "km", + _ => "m", + } + .to_string(), + ); + } + } + None +} + +/// Reads a STEP file's header, unit and entity counts. +pub fn step(bytes: &[u8]) -> Header { + let text = String::from_utf8_lossy(bytes); + let mut h = Header::default(); + if let Some(e) = entity_text(&text, "FILE_SCHEMA") { + h.schema = quoted(e).join(", "); + } + if let Some(e) = entity_text(&text, "FILE_NAME") { + let q = quoted(e); + h.name = q.first().cloned().unwrap_or_default(); + h.system = q.iter().rev().skip(1).take(2).find(|s| !s.trim().is_empty()).cloned().unwrap_or_default(); + } + h.unit = step_unit(&text); + for k in STEP_COUNTED { + h.entities.insert(k.to_ascii_lowercase(), count_keyword(&text, k)); + } + h +} + +/// One STEP manifold solid in file order: its face colours in shell order (the order the worker numbers faces). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StepSolid { + /// Colour of each face of the outer shell, in linear RGB, when the file styles it. + pub faces: Vec<Option<[f32; 3]>>, +} + +fn refs(args: &str) -> Vec<u64> { + let mut out = Vec::new(); + let b = args.as_bytes(); + let mut i = 0; + let mut quoted = false; + while i < b.len() { + match b[i] { + b'\'' => quoted = !quoted, + b'#' if !quoted => { + let s = i + 1; + let mut e = s; + while e < b.len() && b[e].is_ascii_digit() { + e += 1; + } + if let Ok(n) = args[s..e].parse() { + out.push(n); + } + i = e; + continue; + } + _ => {} + } + i += 1; + } + out +} + +fn records(text: &str) -> BTreeMap<u64, (&str, &str)> { + let mut out = BTreeMap::new(); + let data = text.find("DATA;").map(|i| &text[i + 5..]).unwrap_or(text); + let mut start = 0; + let mut quoted = false; + for (i, c) in data.char_indices() { + match c { + '\'' => quoted = !quoted, + ';' if !quoted => { + let rec = data[start..i].trim(); + start = i + 1; + let Some(rest) = rec.strip_prefix('#') else { continue }; + let Some((id, body)) = rest.split_once('=') else { continue }; + let Ok(id) = id.trim().parse::<u64>() else { continue }; + let body = body.trim(); + let name_end = body.find('(').unwrap_or(body.len()); + out.insert(id, (body[..name_end].trim(), &body[name_end..])); + } + _ => {} + } + } + out +} + +const NAMED_COLOURS: &[(&str, [f32; 3])] = &[ + ("red", [1.0, 0.0, 0.0]), + ("green", [0.0, 1.0, 0.0]), + ("blue", [0.0, 0.0, 1.0]), + ("yellow", [1.0, 1.0, 0.0]), + ("magenta", [1.0, 0.0, 1.0]), + ("cyan", [0.0, 1.0, 1.0]), + ("black", [0.0, 0.0, 0.0]), + ("white", [1.0, 1.0, 1.0]), +]; + +fn colour_from(recs: &BTreeMap<u64, (&str, &str)>, start: &[u64]) -> Option<[f32; 3]> { + let mut frontier: Vec<u64> = start.to_vec(); + for _ in 0..10 { + let mut next = Vec::new(); + for id in frontier { + let Some((name, args)) = recs.get(&id) else { continue }; + match *name { + "COLOUR_RGB" => { + let nums: Vec<f32> = args + .trim_matches(|c| c == '(' || c == ')') + .split(',') + .skip(1) + .filter_map(|s| s.trim().trim_end_matches('.').parse::<f32>().ok().or_else(|| s.trim().parse().ok())) + .collect(); + if nums.len() >= 3 { + return Some([srgb_to_linear(nums[0]), srgb_to_linear(nums[1]), srgb_to_linear(nums[2])]); + } + } + "DRAUGHTING_PRE_DEFINED_COLOUR" => { + let q = quoted(args).into_iter().next().unwrap_or_default().to_ascii_lowercase(); + if let Some((_, c)) = NAMED_COLOURS.iter().find(|(n, _)| *n == q) { + return Some(*c); + } + } + _ => next.extend(refs(args)), + } + } + if next.is_empty() { + return None; + } + frontier = next; + } + None +} + +/// The face colours of every manifold solid in a STEP file, in file order; empty when the file styles no faces. +pub fn step_face_colours(bytes: &[u8]) -> Vec<StepSolid> { + let text = String::from_utf8_lossy(bytes); + if !text.contains("STYLED_ITEM") { + return Vec::new(); + } + let recs = records(&text); + let mut face_colour: BTreeMap<u64, [f32; 3]> = BTreeMap::new(); + for (name, args) in recs.values() { + if *name != "STYLED_ITEM" && *name != "OVER_RIDING_STYLED_ITEM" { + continue; + } + let r = refs(args); + let Some(&item) = (if *name == "STYLED_ITEM" { r.last() } else { r.get(r.len().saturating_sub(2)) }) else { continue }; + if recs.get(&item).is_some_and(|(n, _)| *n == "ADVANCED_FACE" || *n == "FACE_SURFACE") { + let styles: Vec<u64> = r.iter().copied().filter(|x| *x != item).collect(); + if let Some(c) = colour_from(&recs, &styles) { + face_colour.insert(item, c); + } + } + } + if face_colour.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + for (name, args) in recs.values() { + if *name != "MANIFOLD_SOLID_BREP" { + continue; + } + let Some(shell) = refs(args).first().and_then(|s| recs.get(s)) else { continue }; + let faces = refs(shell.1).into_iter().map(|f| face_colour.get(&f).copied()).collect(); + out.push(StepSolid { faces }); + } + out +} + +fn columns(line: &[u8], from: usize, to: usize) -> &str { + let end = to.min(line.len()); + let start = from.min(end); + std::str::from_utf8(&line[start..end]).unwrap_or("").trim() +} + +fn field(line: &[u8], index: usize) -> i64 { + columns(line, index * 8, index * 8 + 8).parse().unwrap_or(0) +} + +/// Splits IGES parameter data into fields, honouring Hollerith strings (`5Hhello`). +fn params(data: &str, delim: char, end: char) -> Vec<String> { + let mut out = Vec::new(); + let mut cur = String::new(); + let chars: Vec<char> = data.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if c.is_ascii_digit() && cur.trim().chars().all(|d| d.is_ascii_digit()) { + let mut j = i; + while j < chars.len() && chars[j].is_ascii_digit() { + j += 1; + } + if j < chars.len() && chars[j] == 'H' { + let n: usize = (cur.trim().to_string() + &chars[i..j].iter().collect::<String>()).parse().unwrap_or(0); + let text: String = chars.iter().skip(j + 1).take(n).collect(); + cur = text; + i = j + 1 + n; + continue; + } + } + if c == delim || c == end { + out.push(std::mem::take(&mut cur)); + if c == end { + break; + } + } else { + cur.push(c); + } + i += 1; + } + out +} + +const IGES_UNITS: &[(i64, &str)] = &[(1, "in"), (2, "mm"), (4, "ft"), (5, "mi"), (6, "m"), (7, "km"), (8, "mil"), (9, "micron"), (10, "cm"), (11, "microinch")]; +const IGES_STANDARD: &[[f32; 3]] = + &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0]]; + +struct Entry { + kind: i64, + colour: i64, + form: i64, + label: String, +} + +/// Reads an IGES file's global section, unit, entity counts and its solids' colours and names. +pub fn iges(bytes: &[u8]) -> Header { + let mut h = Header::default(); + let mut global = String::new(); + let mut dir: Vec<&[u8]> = Vec::new(); + let mut pdata: BTreeMap<i64, String> = BTreeMap::new(); + for raw in bytes.split(|&b| b == b'\n') { + let line = raw.strip_suffix(b"\r").unwrap_or(raw); + match line.get(72) { + Some(b'G') => global.push_str(&String::from_utf8_lossy(&line[..72])), + Some(b'D') => dir.push(line), + Some(b'P') => { + let back: i64 = columns(line, 64, 72).parse().unwrap_or(0); + pdata.entry(back).or_default().push_str(&String::from_utf8_lossy(&line[..64.min(line.len())])); + } + _ => {} + } + } + let g = global.trim_start(); + let (delim, end) = if g.starts_with("1H") && g.len() > 6 { + let mut c = g.chars(); + let d = c.nth(2).unwrap_or(','); + let e = g.get(4..).and_then(|r| r.strip_prefix("1H")).and_then(|r| r.chars().next()).unwrap_or(';'); + (d, e) + } else { + (',', ';') + }; + let gp = params(&global, delim, end); + let gv = |i: usize| gp.get(i).map(|s| s.trim().to_string()).unwrap_or_default(); + h.name = gv(3); + h.system = gv(4); + let flag: i64 = gv(13).parse().unwrap_or(0); + h.unit = IGES_UNITS.iter().find(|(f, _)| *f == flag).map(|(_, u)| u.to_string()).or_else(|| Some(gv(14).to_ascii_lowercase()).filter(|s| !s.is_empty())); + let mut entries: BTreeMap<i64, Entry> = BTreeMap::new(); + for (i, pair) in dir.chunks(2).enumerate() { + let [l1, l2] = pair else { continue }; + let kind = field(l1, 0); + *h.entities.entry(kind.to_string()).or_default() += 1; + let label = columns(l2, 56, 64).to_string(); + entries.insert((i * 2 + 1) as i64, Entry { kind, colour: field(l2, 2), form: field(l2, 4), label }); + } + let param_of = |de: i64| -> Vec<String> { pdata.get(&de).map(|d| params(d, delim, end)).unwrap_or_default() }; + let colour_of = |c: i64| -> Option<[f32; 3]> { + if c > 0 { + return IGES_STANDARD.get((c - 1) as usize).copied(); + } + entries.get(&-c).filter(|e| e.kind == 314)?; + let p = param_of(-c); + let v = |i: usize| p.get(i).and_then(|s| s.trim().parse::<f32>().ok()).map(|x| srgb_to_linear(x / 100.0)); + Some([v(1)?, v(2)?, v(3)?]) + }; + for (de, e) in entries.iter().filter(|(_, e)| e.kind == 186) { + let p = param_of(*de); + let mut name = String::new(); + let voids: usize = p.get(3).and_then(|s| s.trim().parse().ok()).unwrap_or(0); + let mut at = 4 + 2 * voids; + let assoc: usize = p.get(at).and_then(|s| s.trim().parse().ok()).unwrap_or(0); + at += 1 + assoc; + let props: usize = p.get(at).and_then(|s| s.trim().parse().ok()).unwrap_or(0); + for k in 0..props.min(64) { + let ptr: i64 = p.get(at + 1 + k).and_then(|s| s.trim().parse().ok()).unwrap_or(0); + if entries.get(&ptr).is_some_and(|x| x.kind == 406 && x.form == 15) { + if let Some(n) = param_of(ptr).get(2).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) { + name = n; + } + } + } + if name.is_empty() { + name = e.label.clone(); + } + h.solids.push(IgesSolid { rgb: colour_of(e.colour), name }); + } + h +} diff --git a/native/crates/fsh-cli/Cargo.toml b/native/crates/fsh-cli/Cargo.toml index 1b7d435f..fc1c4e27 100644 --- a/native/crates/fsh-cli/Cargo.toml +++ b/native/crates/fsh-cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-cli" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false diff --git a/native/crates/fsh-cli/src/main.rs b/native/crates/fsh-cli/src/main.rs index 11b0a62e..6342bb70 100644 --- a/native/crates/fsh-cli/src/main.rs +++ b/native/crates/fsh-cli/src/main.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::time::Instant; -const USAGE: &str = "formshot-engine 0.4.0, the FormShot engine +const USAGE: &str = "formshot-engine 0.6.0, the FormShot engine Usage: formshot-engine render <input> <output.png|.hdr|.exr> [options] @@ -22,8 +22,22 @@ Usage: --transparent transparent background (straight alpha) --device D cpu (default), gpu (the best adapter) or gpu:<n> from devices; a GPU that cannot render this scene falls back to the CPU and the output says why - formshot-engine info <file> what a model or .fshot project holds - formshot-engine convert <input> <output.fshot|.glb> + and the import options below + formshot-engine info <file> [import options] [--json] + what a model or .fshot project holds; for a model, also the + probe result and the options the import used + formshot-engine probe <file> [--json] read a model without importing it: format, declared and guessed + units, up axis, bounds in file units, counts and warnings + formshot-engine reimport <project.fshot> [output.fshot] [--json] + read every imported model of a project again (file.reimport) + and save the result over the project or to output + formshot-engine convert <input> <output.fshot|.glb> [import options] + import options (render, convert and info, for model files): + --units U unit the model is in: auto (default: declared, else guessed from its size), mm, cm, m, in, ft + --up A axis that points up in the model: auto (default), y or z + --floor[=no] stand the model on the floor (default yes) + --center[=yes] move the model's footprint centre to the origin (default no) + --merge[=yes] put everything the model holds under one group (default no) formshot-engine devices [--json] the CPU and every GPU adapter on this machine formshot-engine bench [options] time each device to a fixed sample count on the sample scene, count its rays and compare its picture with the CPU's @@ -76,6 +90,8 @@ fn main() -> ExitCode { Some("bench") => bench(&args[1..]), Some("render") => render(&args[1..]), Some("info") => info(&args[1..]), + Some("probe") => probe(&args[1..]), + Some("reimport") => reimport(&args[1..]), Some("convert") => convert(&args[1..]), Some("dispatch") => dispatch(&args[1..]), Some(other) => Err(Failure::Usage(format!("unknown command \"{other}\""))), @@ -98,7 +114,13 @@ struct Parsed { options: Vec<(String, Option<String>)>, } -const FLAGS: &[&str] = &["denoise", "transparent", "json"]; +const FLAGS: &[&str] = &["denoise", "transparent", "json", "floor", "center", "merge"]; + +const IMPORT_OPTIONS: &[&str] = &["units", "up", "floor", "center", "merge"]; + +fn with_import_options(known: &[&'static str]) -> Vec<&'static str> { + known.iter().chain(IMPORT_OPTIONS).copied().collect() +} fn parse(args: &[String], known: &[&str]) -> Result<Parsed, Failure> { let mut p = Parsed { positional: Vec::new(), options: Vec::new() }; @@ -114,7 +136,7 @@ fn parse(args: &[String], known: &[&str]) -> Result<Parsed, Failure> { return Err(Failure::Usage(format!("unknown option --{name}"))); } if FLAGS.contains(&name.as_str()) { - p.options.push((name, None)); + p.options.push((name, inline)); } else if let Some(v) = inline { p.options.push((name, Some(v))); } else { @@ -139,6 +161,39 @@ impl Parsed { self.options.iter().any(|(n, _)| n == name) } + /// A flag that may also be written `--name=yes` or `--name=no`; `None` when absent. + fn switch(&self, name: &str) -> Result<Option<bool>, Failure> { + let Some((_, v)) = self.options.iter().rev().find(|(n, _)| n == name) else { return Ok(None) }; + match v.as_deref().map(str::to_ascii_lowercase).as_deref() { + None | Some("yes") | Some("true") | Some("on") | Some("1") => Ok(Some(true)), + Some("no") | Some("false") | Some("off") | Some("0") => Ok(Some(false)), + Some(other) => Err(Failure::Usage(format!("--{name} takes yes or no, got \"{other}\""))), + } + } + + /// The import options given on the command line, as `file.import` and `import.probe` arguments. + fn import_args(&self) -> Result<Value, Failure> { + let mut a = json!({}); + if let Some(u) = self.value("units") { + if !["auto", "mm", "cm", "m", "in", "ft"].contains(&u) { + return Err(Failure::Usage(format!("--units must be auto, mm, cm, m, in or ft, got \"{u}\""))); + } + a["units"] = json!(u); + } + if let Some(up) = self.value("up") { + if !["auto", "y", "z"].contains(&up) { + return Err(Failure::Usage(format!("--up must be auto, y or z, got \"{up}\""))); + } + a["up_axis"] = json!(up); + } + for (flag, key) in [("floor", "stand_on_floor"), ("center", "center"), ("merge", "merge")] { + if let Some(b) = self.switch(flag)? { + a[key] = json!(b); + } + } + Ok(a) + } + fn number<T: std::str::FromStr>(&self, name: &str) -> Result<Option<T>, Failure> { match self.value(name) { None => Ok(None), @@ -151,27 +206,62 @@ fn run(engine: &Engine, name: &str, args: Value) -> Result<Value, Failure> { engine.dispatch_value(name, args).map_err(|e| Failure::Run(format!("{name}: {e}"))) } -fn load(engine: &Engine, input: &str) -> Result<(), Failure> { - if input == "sample" { - run(engine, "file.new", json!({"template": "sample", "title": "Sample"}))?; - return Ok(()); +fn is_project(input: &str) -> bool { + Path::new(input).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("fshot")) +} + +/// Opens `input` (a model, a project or the word sample); `import` holds the import options for models. +fn load(engine: &Engine, input: &str, import: &Value) -> Result<Value, Failure> { + let given = import.as_object().is_some_and(|o| !o.is_empty()); + if input == "sample" || is_project(input) { + if given { + eprintln!("formshot-engine: note: --units, --up, --floor, --center and --merge apply to model files only"); + } + if input == "sample" { + return run(engine, "file.new", json!({"template": "sample", "title": "Sample"})); + } } let path = Path::new(input); if !path.is_file() { return Err(Failure::Run(format!("{input}: no such file"))); } - run(engine, "file.open", json!({"path": input}))?; - Ok(()) + let mut args = import.clone(); + args["path"] = json!(input); + if is_project(input) { + return run(engine, "file.open", args); + } + let title = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled"); + run(engine, "file.new", json!({"title": title}))?; + args["frame"] = json!(true); + let job = run(engine, "import.start", args)?["job"].clone(); + let start = Instant::now(); + let mut shown = String::new(); + loop { + let s = run(engine, "import.status", json!({"job": job}))?; + match s["state"].as_str() { + Some("done") => return Ok(json!({"import": s["result"]})), + Some("running") => {} + _ => return Err(Failure::Run(format!("{input}: {}", s["error"]["message"].as_str().unwrap_or("the import stopped")))), + } + let stage = s["stage"].as_str().unwrap_or("").to_string(); + if start.elapsed().as_secs_f64() > 1.0 && stage != shown { + eprintln!("formshot-engine: importing {input}: {stage}, {:.0}%", s["fraction"].as_f64().unwrap_or(0.0) * 100.0); + shown = stage; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } } fn render(args: &[String]) -> Outcome { - let p = parse(args, &["samples", "width", "height", "threads", "seed", "exposure", "tonemap", "denoise", "environment", "transparent", "device"])?; + let known = with_import_options(&["samples", "width", "height", "threads", "seed", "exposure", "tonemap", "denoise", "environment", "transparent", "device"]); + let p = parse(args, &known)?; let [input, output] = p.positional.as_slice() else { return Err(Failure::Usage("render needs <input> and <output>".into())); }; + let import = p.import_args()?; let threads: usize = p.number("threads")?.unwrap_or(0); let engine = Engine::with_options(EngineOptions { threaded: false, threads }); - load(&engine, input)?; + load(&engine, input, &import)?; let selected = select_device(&engine, p.value("device").unwrap_or("cpu"))?; if let Some(env) = p.value("environment") { match env { @@ -290,7 +380,7 @@ fn bench(args: &[String]) -> Outcome { continue; } let engine = Engine::with_options(EngineOptions { threaded: false, threads }); - load(&engine, "sample")?; + load(&engine, "sample", &json!({}))?; let selected = select_device(&engine, &id)?; let opts = StillOptions { path: tmp.clone(), @@ -379,17 +469,96 @@ fn mean_abs_difference(a: &fsh_io::FloatPicture, b: &fsh_io::FloatPicture) -> Op Some(sum / (pixels * 3) as f64) } -fn info(args: &[String]) -> Outcome { +fn print_probe(r: &Value) { + println!("format: {}", r["format"].as_str().unwrap_or("")); + let declared = r["units_declared"].as_str().map(|u| format!("declared {u}")).unwrap_or_else(|| "not declared".into()); + let used = r["units_guess"].as_str().unwrap_or(""); + println!("units: {declared}; auto import uses {used}{}", if r["unit_guessed"] == true { " (guessed from the size)" } else { "" }); + println!("up axis: {}{}", r["up_axis"].as_str().unwrap_or(""), if r["up_axis_declared"] == true { " (declared)" } else { " (assumed)" }); + if !r["bounds"].is_null() { + println!("file bounds: min {} max {} size {} (file units)", r["bounds"]["min"], r["bounds"]["max"], r["bounds"]["size"]); + println!("size: {} metres at {}", r["bounds"]["size_m"], r["units_guess"].as_str().unwrap_or("")); + } + println!( + "contents: {} triangles, {} meshes, {} nodes, {} materials, {} textures", + r["triangles"], r["meshes"], r["nodes"], r["materials"], r["textures"] + ); + for w in r["warnings"].as_array().into_iter().flatten() { + println!("warning: {}", w.as_str().unwrap_or("")); + } +} + +fn probe(args: &[String]) -> Outcome { let p = parse(args, &["json"])?; + let [input] = p.positional.as_slice() else { + return Err(Failure::Usage("probe needs <file>".into())); + }; + let engine = Engine::with_options(EngineOptions { threaded: false, threads: 0 }); + let r = run(&engine, "import.probe", json!({"path": input}))?; + if p.flag("json") { + println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default()); + return Ok(()); + } + println!("file: {} ({} bytes)", input, r["bytes"]); + print_probe(&r); + Ok(()) +} + +fn reimport(args: &[String]) -> Outcome { + let p = parse(args, &["json"])?; + let (input, output) = match p.positional.as_slice() { + [i] => (i, i), + [i, o] => (i, o), + _ => return Err(Failure::Usage("reimport needs <project.fshot> [output.fshot]".into())), + }; + if !is_project(input) || !is_project(output) { + return Err(Failure::Usage("reimport reads and writes .fshot projects".into())); + } + let engine = Engine::with_options(EngineOptions { threaded: false, threads: 0 }); + load(&engine, input, &json!({}))?; + let r = run(&engine, "file.reimport", json!({}))?; + if r["change"] != "none" || output != input { + run(&engine, "file.save", json!({"path": output}))?; + } + if p.flag("json") { + println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default()); + return Ok(()); + } + for f in r["files"].as_array().into_iter().flatten() { + match f["error"]["message"].as_str() { + Some(e) => println!("{}: not read: {e}", f["path"].as_str().unwrap_or("")), + None => println!( + "{}: {} matched, {} added, {} hidden, {} reshaped", + f["path"].as_str().unwrap_or(""), + f["matched"], + f["added"], + f["hidden"], + f["updated"] + ), + } + for w in f["warnings"].as_array().into_iter().flatten() { + println!(" warning: {}", w.as_str().unwrap_or("")); + } + } + println!("{}", if r["change"] == "none" { format!("{input}: nothing changed") } else { format!("{output}: saved") }); + Ok(()) +} + +fn info(args: &[String]) -> Outcome { + let p = parse(args, &with_import_options(&["json"]))?; let [input] = p.positional.as_slice() else { return Err(Failure::Usage("info needs <file>".into())); }; + let import = p.import_args()?; let path = Path::new(input); let bytes = std::fs::metadata(path).map_err(|e| Failure::Run(format!("{input}: {e}")))?.len(); let engine = Engine::with_options(EngineOptions { threaded: false, threads: 0 }); let mut out = json!({"file": input, "bytes": bytes}); let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); if ext == "fshot" { + if import.as_object().is_some_and(|o| !o.is_empty()) { + eprintln!("formshot-engine: note: --units, --up, --floor, --center and --merge apply to model files only"); + } let (project, report) = files::load_file(path).map_err(|e| Failure::Run(e.to_string()))?; out["kind"] = json!("project"); out["format_version"] = json!(report.version.to_string()); @@ -399,11 +568,13 @@ fn info(args: &[String]) -> Outcome { out["preview"] = json!(project.preview_png.is_some()); engine.set_document(project.document, Some(path.to_path_buf())); } else { + out["probe"] = run(&engine, "import.probe", json!({"path": input}))?; let start = Instant::now(); - let reply = run(&engine, "file.open", json!({"path": input}))?; + let reply = load(&engine, input, &import)?; out["kind"] = json!("model"); - out["format"] = json!(ext); + out["format"] = out["probe"]["format"].clone(); out["import"] = reply["import"]["report"].clone(); + out["import_options"] = reply["import"]["options"].clone(); out["import_seconds"] = json!(start.elapsed().as_secs_f64()); } let s = run(&engine, "scene.summary", json!({}))?; @@ -447,6 +618,17 @@ fn info(args: &[String]) -> Outcome { r["instances_found"], r["triangles_dropped"] ); + let o = &out["import_options"]; + println!( + "options: units {}, up {}, floor {}, center {}, merge {}", + o["units"].as_str().unwrap_or(""), + o["up_axis"].as_str().unwrap_or(""), + o["stand_on_floor"], + o["center"], + o["merge"] + ); + println!("the file as read (import.probe):"); + print_probe(&out["probe"]); } if let Some(ws) = out["warnings"].as_array().or(out["import"]["warnings"].as_array()) { for w in ws { @@ -457,12 +639,13 @@ fn info(args: &[String]) -> Outcome { } fn convert(args: &[String]) -> Outcome { - let p = parse(args, &[])?; + let p = parse(args, IMPORT_OPTIONS)?; let [input, output] = p.positional.as_slice() else { return Err(Failure::Usage("convert needs <input> and <output>".into())); }; + let import = p.import_args()?; let engine = Engine::with_options(EngineOptions { threaded: false, threads: 0 }); - load(&engine, input)?; + load(&engine, input, &import)?; let ext = Path::new(output).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); let reply = match ext.as_str() { "fshot" => run(&engine, "file.save", json!({"path": output}))?, diff --git a/native/crates/fsh-commands/Cargo.toml b/native/crates/fsh-commands/Cargo.toml index 4f105fa6..cea8e3a0 100644 --- a/native/crates/fsh-commands/Cargo.toml +++ b/native/crates/fsh-commands/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-commands" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false @@ -15,5 +15,6 @@ fsh-render-cpu = { path = "../fsh-render-cpu" } serde_json = "1" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +fsh-cad = { path = "../fsh-cad" } fsh-render-gpu = { path = "../fsh-render-gpu" } pollster = "1" diff --git a/native/crates/fsh-commands/src/catalogue.rs b/native/crates/fsh-commands/src/catalogue.rs index c57718bd..2533eeab 100644 --- a/native/crates/fsh-commands/src/catalogue.rs +++ b/native/crates/fsh-commands/src/catalogue.rs @@ -32,9 +32,9 @@ pub(crate) const ENGINE_COMMANDS: &[EngineCommand] = &[ cmd("history.barrier", Nothing, false, false, "End merging of continuous edits (call when a drag ends)."), cmd("camera.frame", Full, true, false, "Move the active camera so every visible part fits the view, keeping its direction."), cmd("file.new", Full, true, false, "Start a new document, empty or from a template (empty-studio, product-white, studio-light, studio-dark, spheres, turntable, daylight, sample)."), - cmd("file.open", Full, true, false, "Open a .fshot project, or a model file as a new document."), + cmd("file.open", Full, true, false, "Open a .fshot project, or a model file as a new document with the file.import options (camera framed)."), cmd("file.save", Nothing, false, false, "Save the document as .fshot to path, or to its own path."), - cmd("file.import", Full, true, false, "Import a model (glb, gltf, obj, stl, ply) with clean-up as one undoable step."), + cmd("file.import", Full, true, false, "Import a model (glb, gltf, obj, stl, ply, 3mf, fbx, step, iges) with clean-up as one undoable step; units, up_axis, stand_on_floor, center, merge and cad_quality are optional, and every node made carries source.path and source.node metadata."), cmd("file.close", Full, true, false, "Close the document, leaving an empty one, and stop rendering."), cmd("file.export_image", Nothing, false, false, "Write the latest progressive frame to png, hdr or exr."), cmd("file.export_model", Nothing, false, false, "Write the visible document as a binary glTF (.glb)."), @@ -107,33 +107,9 @@ pub(crate) fn engine_schema(name: &str) -> Value { ], &[], ), - "file.open" => obj(vec![("path", s("A .fshot project or a model file"))], &["path"]), + "file.open" => crate::ext::import::file_open_schema(), "file.save" => obj(vec![("path", s("Target .fshot; the document's own path when absent"))], &[]), - "file.import" => obj( - vec![ - ("path", s("Model file: glb, gltf, obj, stl or ply")), - ("name", s("Name for the imported group (the original file name)")), - ("frame", b("Frame the camera on the result (default: only when the document was empty)")), - ( - "options", - obj( - vec![ - ("unit", json!({"type": "string", "enum": ["m", "cm", "mm", "in", "ft"], "description": "Unit the file is in"})), - ("up_axis", json!({"type": "string", "enum": ["y", "z", "x", "-y", "-z", "-x"]})), - ("smoothing_angle_deg", json!({"type": "number", "default": 30})), - ("weld", json!({"type": "boolean", "default": true})), - ("generate_normals", json!({"type": "boolean", "default": true})), - ("detect_instances", json!({"type": "boolean", "default": true})), - ("stand_on_floor", json!({"type": "boolean", "default": true})), - ("centre", json!({"type": "boolean", "default": false})), - ("wrap_in_group", json!({"type": "boolean", "default": true})), - ], - &[], - ), - ), - ], - &["path"], - ), + "file.import" => crate::ext::import::file_import_schema(), "file.export_image" => obj(vec![("path", s("Target file")), ("format", picture_format()), ("denoise", b("Denoise first"))], &["path"]), "file.export_model" => obj(vec![("path", s("Target .glb"))], &["path"]), "render.start" => obj( @@ -257,6 +233,9 @@ pub fn catalogue_value() -> Value { for e in ENGINE_COMMANDS { commands.push(entry(e.name, e.description, engine_schema(e.name), e.level, e.mutates, e.read_only, false)); } + for e in crate::ext::commands() { + commands.push(entry(e.name, e.description, (e.schema)(), e.level, e.mutates, e.read_only, false)); + } let mut aliases = Vec::new(); for a in ALIASES { aliases.push(json!({"name": a.name, "target": a.target, "fields": a.fields})); diff --git a/native/crates/fsh-commands/src/device.rs b/native/crates/fsh-commands/src/device.rs index 0859142d..24fcb87c 100644 --- a/native/crates/fsh-commands/src/device.rs +++ b/native/crates/fsh-commands/src/device.rs @@ -35,6 +35,11 @@ pub(crate) trait PreviewRenderer: Send { fn update_display(&mut self, style: ImageStyle); /// Supplies HDRI pixels; resets accumulation. fn set_environment_image(&mut self, image: Option<EnvImage>); + /// Supplies the decoded pixels of the textures the snapshot's material programs sample, in + /// `RenderSnapshot::textures` order (`None` or a missing image samples the fallbacks); resets accumulation. + fn set_textures(&mut self, textures: Option<fsh_scene::fsh_materials::TextureSet>) { + let _ = textures; + } /// Asks for passes at a fraction of the full resolution (1 is full); returns the scale the engine uses. fn set_resolution_scale(&mut self, scale: f32) -> f32; /// Adds `samples` to every pixel unless `cancel` is raised between tiles. An error from a GPU engine means the @@ -53,6 +58,10 @@ pub(crate) trait PreviewRenderer: Send { fn inputs(&self) -> Option<(Arc<RenderSnapshot>, Option<EnvImage>)> { None } + /// The texture pixels this renderer was last given, for the same CPU fallback. + fn fallback_textures(&self) -> Option<fsh_scene::fsh_materials::TextureSet> { + None + } } /// What a region-level update cleared. @@ -192,23 +201,24 @@ struct CpuPreview { } /// Film pixels added around the changed parts' rectangle, for their soft edges and nearby reflections. -const REGION_PAD: u32 = 6; +pub(crate) const REGION_PAD: u32 = 6; fn emits(m: Option<&fsh_scene::RenderMaterial>) -> bool { m.is_some_and(|m| m.params.emission_luminance > 0.0) } /// Snapshot instance indices whose material or part colour changed, when nothing else did; `None` when the change -/// reaches further (lights, environment, ground, geometry, an emitting material) and the whole film must reset. -fn changed_instances(old: &RenderSnapshot, new: &RenderSnapshot) -> Option<Vec<u32>> { +/// reaches further (lights, environment, ground, geometry, an emitting material) and the whole film must reset. A +/// material added or removed (applying a preset makes one) is not by itself a reason: parts whose material index +/// moved count as changed. +pub(crate) fn changed_instances(old: &RenderSnapshot, new: &RenderSnapshot) -> Option<Vec<u32>> { if old.lights != new.lights || old.environment != new.environment || old.ground != new.ground || old.render != new.render || old.cutaways != new.cutaways - || old.default_material != new.default_material + || old.materials.get(old.default_material.index()) != new.materials.get(new.default_material.index()) || old.instances.len() != new.instances.len() - || old.materials.len() != new.materials.len() { return None; } @@ -301,6 +311,11 @@ impl PreviewRenderer for CpuPreview { self.r.set_environment_image(image); } + fn set_textures(&mut self, textures: Option<fsh_scene::fsh_materials::TextureSet>) { + self.base = 0; + self.r.set_textures(textures); + } + fn set_resolution_scale(&mut self, scale: f32) -> f32 { let before = self.r.film_size(); let s = cpu_resolution_scale(&mut self.r, scale); diff --git a/native/crates/fsh-commands/src/engine.rs b/native/crates/fsh-commands/src/engine.rs index e6a22a29..79572344 100644 --- a/native/crates/fsh-commands/src/engine.rs +++ b/native/crates/fsh-commands/src/engine.rs @@ -9,9 +9,9 @@ use crate::sample; use crate::summary::{summary, DocInfo}; use crate::util::{base64, get_bool, get_f32, get_str, get_u32, key_of, numeric_keys, parse_args, vec3_json}; use crate::view; -use fsh_core::{DocKey, LengthUnit, NodeId, Rgb, Vec3}; +use fsh_core::{DocKey, LengthUnit, NodeId, Vec3}; use fsh_format::{Project, SaveOptions}; -use fsh_io::{CleanOptions, FloatPicture, ImportOptions, UpAxis, Watch}; +use fsh_io::{CleanOptions, FloatPicture, UpAxis}; use crate::device::{self, PreviewRenderer, RegionReset}; use fsh_render_cpu::{EnvImage, Image, STUDIO_PATH}; use fsh_scene::{ @@ -87,49 +87,68 @@ struct View { samples: Option<u32>, } -struct State { - editor: Editor, - path: Option<PathBuf>, - kept: Project, - revision: u64, - content: u64, +pub(crate) struct State { + pub(crate) editor: Editor, + pub(crate) path: Option<PathBuf>, + pub(crate) kept: Project, + pub(crate) revision: u64, + pub(crate) content: u64, view: View, threads: usize, env_cache: Option<(String, EnvImage)>, renderer_env: Option<String>, + pub(crate) textures: crate::textures::Textures, png_cache: Option<(u64, Arc<String>)>, picks: view::PickCache, mesh_view: MeshView, device: String, last_reset: &'static str, last_region: Option<RegionReset>, - journal: Option<CrashJournal>, + pub(crate) journal: Option<CrashJournal>, + pub(crate) jobs: crate::ext::import::Jobs, + textures_unjournaled: bool, } impl State { - fn note(&mut self, out: &Outcome) { + pub(crate) fn note(&mut self, out: &Outcome) { if let Some(j) = self.journal.as_mut() { j.record(out, &self.editor); } } - fn note_begin(&mut self, label: &str) { + pub(crate) fn note_begin(&mut self, label: &str) { if let Some(j) = self.journal.as_mut() { j.begin(label, &self.editor); } } - fn note_end(&mut self) { + pub(crate) fn note_end(&mut self) { if let Some(j) = self.journal.as_mut() { j.end(&self.editor); } } + pub(crate) fn note_sources(&mut self) { + if let Some(j) = self.journal.as_mut() { + j.keep_sources(&self.kept.preserved.sources); + } + } + fn note_barrier(&mut self) { if let Some(j) = self.journal.as_mut() { j.barrier(&self.editor); } } + + /// Hands images a command embedded to the crash journal once no history group is open (inside a group the + /// journal cannot snapshot yet, so the hand-over waits for the group's end). + fn journal_embedded(&mut self, embedded: bool) { + self.textures_unjournaled |= embedded; + if self.textures_unjournaled && self.editor.history().group_depth() == 0 { + crate::ext::import::textures::journal_textures(self); + self.textures_unjournaled = false; + } + } } /// One engine session: the document with its history and selection, the project it came from, and a background renderer. @@ -188,26 +207,19 @@ fn write_file(path: &Path, bytes: &[u8]) -> Result<()> { fsh_format::atomic_write(path, bytes).map_err(EngineError::from) } -fn load_env_image(path: &str) -> std::result::Result<EnvImage, String> { - let bytes = std::fs::read(path).map_err(|e| format!("cannot read environment image {path}: {e}"))?; - match fsh_io::detect_picture(path, &bytes) { - Some(fsh_io::PictureFormat::Hdr) => { - let p = fsh_io::read_hdr(&bytes).map_err(|e| e.to_string())?; - let pixels = (0..p.height) - .flat_map(|y| (0..p.width).map(move |x| (x, y))) - .map(|(x, y)| Rgb::from_linear_srgb(p.rgb(x, y))) - .collect(); - EnvImage::new(p.width, p.height, pixels).map_err(|e| e.to_string()) - } - _ => Err(format!("environment image {path} is not a Radiance .hdr file (the only HDRI format read so far)")), - } +fn load_env_image(path: &str, kept: &Project) -> std::result::Result<EnvImage, String> { + let bytes = match path.strip_prefix(fsh_format::EMBED_SCHEME) { + Some(_) => kept.texture_bytes(path).map(<[u8]>::to_vec).ok_or_else(|| format!("environment image {path} is not in the project"))?, + None => std::fs::read(path).map_err(|e| format!("cannot read environment image {path}: {e}"))?, + }; + crate::textures::environment_image(path, &bytes) } fn parse_unit(s: &str) -> Result<LengthUnit> { s.parse::<LengthUnit>().map_err(|e| EngineError::args(e.to_string())) } -fn clean_options(o: &Value) -> Result<CleanOptions> { +pub(crate) fn clean_options(o: &Value) -> Result<CleanOptions> { let mut c = CleanOptions::default(); if let Some(u) = get_str(o, "unit") { c.unit = Some(parse_unit(u)?); @@ -232,7 +244,7 @@ fn clean_options(o: &Value) -> Result<CleanOptions> { Ok(c) } -fn has_parts(doc: &Document) -> bool { +pub(crate) fn has_parts(doc: &Document) -> bool { doc.nodes().values().any(|n| matches!(n.kind, NodeKind::Part { .. })) } @@ -241,7 +253,7 @@ fn is_model(path: &Path) -> bool { fsh_io::ModelFormat::from_extension(&ext).is_some() } -fn title_from(path: &Path) -> String { +pub(crate) fn title_from(path: &Path) -> String { path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled").to_string() } @@ -281,6 +293,7 @@ impl Engine { threads: opts.threads, env_cache: None, renderer_env: None, + textures: Default::default(), png_cache: None, picks: view::PickCache::default(), mesh_view: MeshView::default(), @@ -288,6 +301,8 @@ impl Engine { last_reset: "none", last_region: None, journal: None, + jobs: Default::default(), + textures_unjournaled: false, }), render: RenderControl::new(opts.threaded, opts.threads), } @@ -308,17 +323,20 @@ impl Engine { _ => return Err(EngineError::args("arguments must be a JSON object")), }; let mut st = lock(&self.state); + crate::ext::import::pump(self, &mut st); let (name, mut args) = alias::translate(name, args, st.editor.document())?; numeric_keys(&mut args); - if ENGINE_COMMANDS.iter().any(|c| c.name == name) { + if ENGINE_COMMANDS.iter().any(|c| c.name == name) || crate::ext::commands().any(|c| c.name == name) { return self.engine_command(&mut st, &name, &args); } if !Command::NAMES.contains(&name.as_str()) { return Err(EngineError::UnknownCommand(name)); } let camera_only = matches!(name.as_str(), "camera.set" | "camera.set_active"); + let embedded = crate::textures::embed_command_path(&mut st, &name, &mut args); let out = st.editor.dispatch(&name, args)?; st.note(&out); + st.journal_embedded(embedded); Ok(self.changed(&mut st, &out, camera_only)) } @@ -336,7 +354,7 @@ impl Engine { j.close(); } let Some(root) = root else { return Ok(None) }; - let j = CrashJournal::start(root, &st.editor, &st.kept.textures, st.path.as_deref()); + let j = CrashJournal::start(root, &st.editor, &st.kept, st.path.as_deref()); if let Some(e) = j.error() { return Err(EngineError::File(format!("the crash journal could not start: {e}"))); } @@ -364,7 +382,7 @@ impl Engine { lock(&self.state).editor.document().clone() } - fn changed(&self, st: &mut State, out: &Outcome, camera_only: bool) -> Value { + pub(crate) fn changed(&self, st: &mut State, out: &Outcome, camera_only: bool) -> Value { st.revision += 1; if !camera_only { st.content += 1; @@ -416,7 +434,7 @@ impl Engine { fn hdri_path(doc: &Document) -> Option<String> { match &doc.environment().source { - EnvironmentSource::Hdri { path } if path != STUDIO_PATH && !path.starts_with(fsh_format::EMBED_SCHEME) => Some(path.clone()), + EnvironmentSource::Hdri { path } if path != STUDIO_PATH => Some(path.clone()), _ => None, } } @@ -427,7 +445,7 @@ impl Engine { return Some(img.clone()); } } - match load_env_image(path) { + match load_env_image(path, &st.kept) { Ok(img) => { st.env_cache = Some((path.to_string(), img.clone())); Some(img) @@ -468,16 +486,22 @@ impl Engine { fn request_renderer(&self, st: &mut State, warnings: &mut Vec<String>) { let snap = Self::view_snapshot(st); let (key, env) = Self::build_env(st, warnings); - self.render.request(Build::new(&st.device, snap, env, key)); + let textures = crate::textures::for_snapshot(st, &snap, warnings); + self.render.request(Build::new(&st.device, snap, env, key).with_textures(textures)); } fn update_request(&self, st: &mut State, warnings: &mut Vec<String>) -> bool { let snap = Self::view_snapshot(st); let env = Self::env_image(st, warnings); - self.render.update_request(snap, env) + let pending = self.render.update_request(Arc::clone(&snap), env); + if pending { + let textures = crate::textures::for_snapshot(st, &snap, warnings); + self.render.update_request_textures(textures); + } + pending } - fn refresh_render(&self, st: &mut State, level: ChangeLevel, camera_only: bool) -> Vec<String> { + pub(crate) fn refresh_render(&self, st: &mut State, level: ChangeLevel, camera_only: bool) -> Vec<String> { let mut warnings = Vec::new(); st.png_cache = None; if level != ChangeLevel::None && self.render.building() && self.update_request(st, &mut warnings) { @@ -502,7 +526,9 @@ impl Engine { ChangeLevel::Region => { let snap = Self::view_snapshot(st); let mut held = self.render.hold(); + let new_textures = crate::textures::sync(st, &mut held, &snap, &mut warnings); let reset = match held.renderer().map(|r| r.update_region(&snap)) { + Some(Ok(_)) if new_textures => RegionReset::Full, Some(Ok(r)) => r, Some(Err(e)) => { warnings.push(format!("the renderer kept the previous scene: {e}")); @@ -512,7 +538,11 @@ impl Engine { }; st.last_reset = if matches!(reset, RegionReset::Full) { "full" } else { "region" }; st.last_region = Some(reset); - held.restarted(); + if new_textures { + held.restarted_full(); + } else { + held.restarted(); + } } ChangeLevel::Full => { st.last_reset = "full"; @@ -524,6 +554,7 @@ impl Engine { } } else { Self::sync_env(st, &mut held, &mut warnings); + crate::textures::sync(st, &mut held, &snap, &mut warnings); if let Some(r) = held.renderer() { if let Err(e) = r.set_snapshot(snap) { warnings.push(format!("the renderer kept the previous scene: {e}")); @@ -560,13 +591,14 @@ impl Engine { self.install_editor(st, editor, path, kept); } - fn install_editor(&self, st: &mut State, editor: Editor, path: Option<PathBuf>, kept: Project) { + pub(crate) fn install_editor(&self, st: &mut State, editor: Editor, path: Option<PathBuf>, kept: Project) { st.editor = editor; st.path = path; st.kept = Project { document: Document::default(), ..kept }; if let Some(j) = st.journal.as_mut() { - j.restart(&st.editor, &st.kept.textures, st.path.as_deref()); + j.restart(&st.editor, &st.kept, st.path.as_deref()); } + crate::ext::import::document_changed(st); st.revision += 1; st.content += 1; st.png_cache = None; @@ -658,6 +690,7 @@ impl Engine { "history.end_group" => { st.editor.end_group()?; st.note_end(); + st.journal_embedded(false); st.revision += 1; Ok(json!({"ok": true, "change": "none", "group_depth": st.editor.history().group_depth(), "revision": st.revision})) } @@ -727,7 +760,7 @@ impl Engine { st.path = Some(path.clone()); if st.editor.history().group_depth() == 0 { if let Some(j) = st.journal.as_mut() { - j.restart(&st.editor, &st.kept.textures, st.path.as_deref()); + j.restart(&st.editor, &st.kept, st.path.as_deref()); } } st.revision += 1; @@ -837,7 +870,7 @@ impl Engine { fsh_format::RecoveryStrategy::Snapshot { slot } => json!({"kind": "snapshot", "slot": slot}), }; let path = crashed.project.clone().map(PathBuf::from); - let kept = Project { textures: rec.textures, ..Project::default() }; + let kept = Project { textures: rec.textures, preserved: fsh_format::Preserved { sources: rec.sources, ..Default::default() }, ..Project::default() }; let commands = crashed.commands; self.install_editor(st, rec.editor, path, kept); self.render.clear_frame(); @@ -937,72 +970,15 @@ impl Engine { reply["bounds"] = view::bounds_json(&b); Ok(reply) } - other => Err(EngineError::UnknownCommand(other.to_string())), + other => crate::ext::dispatch(self, st, other, args).unwrap_or_else(|| Err(EngineError::UnknownCommand(other.to_string()))), } } - fn import(&self, st: &mut State, path: &Path, args: &Value, frame: Option<bool>) -> Result<Value> { - let empty = json!({}); - let opts = args.get("options").unwrap_or(&empty); - let clean = clean_options(opts)?; - let import = ImportOptions { parent: None, wrap_in_group: get_bool(opts, "wrap_in_group").unwrap_or(true) }; - let was_empty = !has_parts(st.editor.document()); - let (cmd, report) = fsh_io::import_file(path, st.editor.document(), &clean, &import, &Watch::new())?; - let label = format!("Import {}", get_str(args, "name").map(str::to_string).unwrap_or_else(|| title_from(path))); - st.editor.begin_group(&label); - st.note_begin(&label); - let result = (|| -> Result<Outcome> { - let out = st.editor.execute(cmd)?; - st.note(&out); - if let Some(name) = get_str(args, "name").filter(|n| !n.is_empty()) { - let stem = title_from(Path::new(name)); - let roots: Vec<u64> = out - .created - .iter() - .copied() - .filter(|k| st.editor.document().node(NodeId::from_raw(*k)).is_some_and(|n| n.parent.is_none() && n.name == title_from(path))) - .collect(); - for r in roots { - let renamed = st.editor.dispatch("scene.rename", json!({"id": r, "name": stem}))?; - st.note(&renamed); - } - } - if frame.unwrap_or(was_empty) { - if let Ok(values) = frame_values(st.editor.document(), 1.15) { - let index = st.editor.document().active_camera_index(); - let framed = st.editor.dispatch("camera.set", json!({"index": index, "values": values}))?; - st.note(&framed); - } - } - Ok(out) - })(); - let out = match result { - Ok(o) => { - st.editor.end_group()?; - st.note_end(); - o - } - Err(e) => { - if let Ok(back) = st.editor.abandon_group() { - st.note(&back); - } - return Err(e); - } - }; - let mut reply = self.changed(st, &Outcome { level: ChangeLevel::Full, ..out }, false); - reply["name"] = json!("file.import"); - reply["report"] = json!({ - "triangles_dropped": report.triangles_dropped, - "vertices_welded": report.vertices_welded, - "unused_vertices_removed": report.unused_vertices_removed, - "meshes_given_normals": report.meshes_given_normals, - "instances_found": report.instances_found, - "unit": report.unit.as_str(), - "unit_guessed": report.unit_guessed, - "up_axis": report.up_axis.as_str(), - "warnings": report.warnings, - }); - Ok(reply) + pub(crate) fn import(&self, st: &mut State, path: &Path, args: &Value, frame: Option<bool>) -> Result<Value> { + if crate::ext::cad::is_cad(path) { + return crate::ext::cad::import(self, st, path, args, frame); + } + crate::ext::import::import_now(self, st, path, args, frame) } fn render_start(&self, st: &mut State, args: &Value) -> Result<Value> { @@ -1028,6 +1004,12 @@ impl Engine { r.set_snapshot(snap)?; } held.restarted_full(); + } else if !self.render.building() { + let snap = Self::view_snapshot(st); + let mut held = self.render.hold(); + if crate::textures::sync(st, &mut held, &snap, &mut warnings) { + held.restarted_full(); + } } self.render.start(Self::target(st)); st.png_cache = None; @@ -1117,6 +1099,7 @@ impl Engine { v["resolution_scale"] = crate::util::num(s.scale); v["budget_ms"] = json!((s.budget * 1000.0).round()); v["adaptive"] = json!(s.adaptive); + v["textures"] = st.textures.status(); if let Some(l) = s.live { v["rays"] = json!(l.rays); v["seconds"] = json!(l.seconds); @@ -1206,7 +1189,8 @@ impl Engine { let threads = opts.threads.unwrap_or(st.threads); let mut warnings = Vec::new(); let env = Self::hdri_path(doc).and_then(|p| Self::cached_env(st, &p, &mut warnings)); - let job = StillJob { device: st.device.clone(), snapshot: Arc::new(snap), env, threads, target, denoise }; + let textures = crate::textures::for_snapshot(st, &snap, &mut warnings); + let job = StillJob { device: st.device.clone(), snapshot: Arc::new(snap), env, textures, threads, target, denoise }; let out = if self.render.threaded() { let (tx, rx) = mpsc::channel::<StillMessage>(); self.render.on_render_thread(move |failed| { @@ -1268,6 +1252,7 @@ struct StillJob { device: String, snapshot: Arc<RenderSnapshot>, env: Option<EnvImage>, + textures: Option<fsh_scene::fsh_materials::TextureSet>, threads: usize, target: u32, denoise: bool, @@ -1294,6 +1279,9 @@ impl StillJob { let opened = device::open(&self.device, Arc::clone(&self.snapshot), self.env.clone(), self.threads, failed)?; let mut note = opened.note; let mut r = opened.renderer; + if self.textures.is_some() { + r.set_textures(self.textures.clone()); + } let mut build_seconds = t0.elapsed().as_secs_f64(); let (image, samples, rays, seconds) = match self.passes(r.as_mut(), progress) { Ok(done) => done, @@ -1301,6 +1289,9 @@ impl StillJob { note = Some(device::failure_note(r.device(), &e, failed)); let t0 = Moment::now(); r = device::cpu(Arc::clone(&self.snapshot), self.env.clone(), self.threads)?; + if self.textures.is_some() { + r.set_textures(self.textures.clone()); + } build_seconds += t0.elapsed().as_secs_f64(); self.passes(r.as_mut(), progress)? } @@ -1361,7 +1352,7 @@ fn still_options(args: &Value) -> Result<StillOptions> { } /// Camera position and target that fit every visible part, keeping the active camera's direction. -fn frame_values(doc: &Document, margin: f32) -> Result<Value> { +pub(crate) fn frame_values(doc: &Document, margin: f32) -> Result<Value> { let snap = fsh_scene::flatten(doc); if snap.bounds.is_empty() || snap.instances.is_empty() { return Err(EngineError::state("nothing visible to frame")); diff --git a/native/crates/fsh-commands/src/ext/cad.rs b/native/crates/fsh-commands/src/ext/cad.rs new file mode 100644 index 00000000..0e419f73 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/cad.rs @@ -0,0 +1,766 @@ +//! STEP and IGES through FormCAD's kernel worker (0.5.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use crate::util::get_bool; +use fsh_io::{RawScene, Watch}; +use fsh_scene::ChangeLevel; +use serde_json::{json, Value}; +use std::path::Path; + +pub(super) static COMMANDS: &[ExtCommand] = &[ + ExtCommand { + name: "cad.status", + description: "Whether the CAD worker that opens STEP and IGES files is installed, where, and which release; probe starts it once to check.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: status_schema, + }, + ExtCommand { + name: "scene.retessellate", + description: "Rebuild the meshes of CAD parts from their kept STEP or IGES source at a new quality; each part keeps its id, name, placement, material, visibility and selection (scene.set_part_mesh); one undo step.", + level: ChangeLevel::Full, + mutates: true, + read_only: false, + schema: retessellate_schema, + }, + ExtCommand { + name: "cad.parts", + description: "Parts imported from STEP or IGES files, with their kept source, original path, quality, unit and up axis; nodes limits the answer to the parts under those nodes.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: parts_schema, + }, +]; + +fn parts_schema() -> Value { + json!({ + "type": "object", + "properties": {"nodes": {"type": "array", "items": {"type": ["string", "integer"]}, "description": "Parts or groups to look under; every part when absent"}}, + "required": [] + }) +} + +fn parts(st: &State, args: &Value) -> Result<Value> { + use crate::error::EngineError; + use fsh_core::NodeId; + use fsh_scene::NodeKind; + let doc = st.editor.document(); + let scope: Option<std::collections::BTreeSet<NodeId>> = match args.get("nodes") { + None | Some(Value::Null) => None, + Some(Value::Array(a)) => { + let mut set = std::collections::BTreeSet::new(); + for v in a { + let id = crate::util::key_of(v).map(NodeId::new).ok_or_else(|| EngineError::args(format!("nodes holds {v}, which is not a node id")))?; + doc.get_node(id)?; + set.extend(doc.subtree(id)); + } + Some(set) + } + Some(_) => return Err(EngineError::args("nodes must be a list of node ids")), + }; + let list: Vec<Value> = doc + .nodes() + .iter() + .filter(|(id, n)| matches!(n.kind, NodeKind::Part { .. }) && scope.as_ref().is_none_or(|s| s.contains(id))) + .filter_map(|(id, n)| { + let source = n.metadata.get("source.cad")?; + let meta = |k: &str| n.metadata.get(k).cloned(); + Some(json!({ + "id": id.raw().to_string(), "name": n.name, "source": source, "path": meta("source.path"), + "quality": meta("cad.quality"), "unit": meta("cad.unit"), "up": meta("cad.up"), + })) + }) + .collect(); + Ok(json!({"parts": list})) +} + +fn quality_schema() -> Value { + json!({ + "description": "Tessellation of STEP and IGES surfaces: a preset, or chord (fraction of the model's diagonal) and angle (degrees)", + "oneOf": [ + {"type": "string", "enum": ["draft", "medium", "high", "ultra"]}, + {"type": "object", "properties": { + "chord": {"type": "number", "exclusiveMinimum": 0, "maximum": 0.1, "description": "Largest distance between the surface and its triangles, as a fraction of the model's bounding-box diagonal (not metres)"}, + "angle": {"type": "number", "minimum": 1, "maximum": 90, "description": "Largest angle between neighbouring triangle normals, in degrees"} + }, "required": ["chord", "angle"]} + ] + }) +} + +fn retessellate_schema() -> Value { + json!({ + "type": "object", + "properties": { + "nodes": {"type": "array", "items": {"type": ["string", "integer"]}, "description": "Parts or groups whose CAD parts are rebuilt; every CAD part when absent"}, + "quality": quality_schema() + }, + "required": ["quality"] + }) +} + +fn status_schema() -> Value { + json!({ + "type": "object", + "properties": {"probe": {"type": "boolean", "description": "Start the worker and ask its version (takes a few seconds)"}}, + "required": [] + }) +} + +pub(super) fn dispatch(engine: &Engine, st: &mut State, name: &str, args: &Value) -> Option<Result<Value>> { + match name { + "cad.status" => Some(Ok(native::status(get_bool(args, "probe").unwrap_or(false)))), + "scene.retessellate" => Some(native::retessellate(engine, st, args)), + "cad.parts" => Some(parts(st, args)), + _ => None, + } +} + +/// True for the extensions the CAD worker opens: .step, .stp, .iges, .igs. +pub(crate) fn is_cad(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "step" | "stp" | "iges" | "igs")) +} + +/// Reads a STEP or IGES file into a raw scene (Z up, metres) at `quality`: "draft", "medium", "high", "ultra", +/// `{chord, angle}`, or null for medium. Progress and cancel go through `watch`; cancel stops the worker. +#[allow(dead_code)] +pub(crate) fn read_cad(path: &Path, quality: &Value, watch: &Watch) -> fsh_io::Result<RawScene> { + native::read_cad(path, quality, watch) +} + +/// `file.import` for a STEP or IGES file: read, clean, one undo step, kept source, `source.*` and `cad.*` metadata. +pub(crate) fn import(engine: &Engine, st: &mut State, path: &Path, args: &Value, frame: Option<bool>) -> Result<Value> { + let prepared = prepare(path, args, &Watch::new())?; + apply(engine, st, prepared, args, frame) +} + +pub(crate) use native::Prepared; + +/// `import.probe` for a STEP or IGES file: what the file's header says, then what the worker's open says (bodies, +/// groups, colours, size) without tessellating; `worker: false` skips the worker. +pub(crate) fn probe(path: &Path, args: &Value) -> Result<Value> { + native::probe(path, get_bool(args, "worker").unwrap_or(true)) +} + +/// Reads and cleans a STEP or IGES file off the session (an import job's thread); progress and cancel go through +/// `watch`, and cancel stops the worker. +pub(crate) fn prepare(path: &Path, args: &Value, watch: &Watch) -> Result<Prepared> { + native::prepare(path, args, watch) +} + +/// Adds a prepared CAD read to the document as one undo step and keeps its source. +pub(crate) fn apply(engine: &Engine, st: &mut State, p: Prepared, args: &Value, frame: Option<bool>) -> Result<Value> { + native::apply(engine, st, p, args, frame) +} + +/// A kept CAD source read again for `file.reimport`. +pub(crate) type Reread = (fsh_scene::Command, fsh_io::CleanReport, Option<(Vec<u8>, String)>); + +/// `file.reimport` of a STEP or IGES import: the file read again with the import's stored options at the quality its +/// parts have now, as the `scene.import` to match, plus the bytes to keep (with [`keep_source`]) when it applies. +pub(crate) fn reread(path: &Path, stored: &Value, doc: &fsh_scene::Document, top: fsh_core::NodeId) -> Result<Reread> { + native::reread(path, stored, doc, top) +} + +/// Keeps a CAD source in the project and the crash journal; true when kept. +pub(crate) fn keep_source(st: &mut State, source: Option<(Vec<u8>, String)>) -> bool { + let kept = match source { + Some((bytes, ext)) => st.kept.keep_source(bytes, &ext).is_ok(), + None => false, + }; + if kept { + st.note_sources(); + } + kept +} + +#[cfg(not(target_arch = "wasm32"))] +mod native { + use crate::engine::{Engine, State}; + use crate::error::{EngineError, Result}; + use crate::util::get_str; + use crate::view; + use fsh_cad::{locate, CadError, MeshTag, Quality, ReadOptions, Worker, PROTOCOL}; + use fsh_core::{LengthUnit, NodeId}; + use fsh_io::{CleanOptions, CleanReport, ImportOptions, RawScene, UpAxis, Watch}; + use fsh_scene::{ChangeLevel, Command, NodeKind, Outcome}; + use serde_json::{json, Value}; + use std::collections::HashMap; + use std::path::{Path, PathBuf}; + + pub(super) fn cad_error(e: CadError) -> EngineError { + EngineError::Io { code: e.code(), message: e.to_string() } + } + + fn opt<'a>(args: &'a Value, key: &str) -> Option<&'a Value> { + args.get(key).filter(|v| !v.is_null()) + } + + fn opt_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> { + opt(args, key).and_then(Value::as_str) + } + + fn opt_bool(args: &Value, key: &str) -> Option<bool> { + opt(args, key).and_then(Value::as_bool) + } + + fn legacy(args: &Value) -> Value { + args.get("options").filter(|o| o.is_object()).cloned().unwrap_or_else(|| json!({})) + } + + fn wrap_of(args: &Value) -> bool { + opt_bool(args, "merge") == Some(true) || opt_bool(&legacy(args), "wrap_in_group").unwrap_or(true) + } + + pub(super) fn quality_of(args: &Value, key: &str) -> Result<Quality> { + Quality::from_json(opt(args, key).unwrap_or(&Value::Null)).map_err(|m| EngineError::args(format!("{key}: {m}"))) + } + + pub(super) fn probe(path: &Path, use_worker: bool) -> Result<Value> { + fsh_cad::probe(path, &ReadOptions::default(), use_worker, &Watch::new()).map_err(cad_error) + } + + pub(super) fn read_cad(path: &Path, quality: &Value, watch: &Watch) -> fsh_io::Result<RawScene> { + let quality = Quality::from_json(quality).map_err(fsh_io::IoError::InvalidData)?; + let opts = ReadOptions { quality, ..ReadOptions::default() }; + Ok(fsh_cad::read(path, &opts, watch)?.scene) + } + + fn clean_options(args: &Value) -> Result<CleanOptions> { + let mut c = CleanOptions { detect_instances: false, ..crate::engine::clean_options(&legacy(args))? }; + if let Some(u) = opt_str(args, "units").filter(|u| *u != "auto") { + c.unit = Some(u.parse::<LengthUnit>().map_err(|e| EngineError::args(e.to_string()))?); + } + if let Some(a) = opt_str(args, "up_axis").filter(|a| *a != "auto") { + c.up_axis = Some(UpAxis::parse(a).ok_or_else(|| EngineError::args(format!("unknown up axis \"{a}\"")))?); + } + if let Some(b) = opt_bool(args, "stand_on_floor") { + c.stand_on_floor = b; + } + if let Some(b) = opt_bool(args, "center") { + c.centre = b; + } + Ok(c) + } + + /// A CAD file read and cleaned off the session, ready for [`apply`]. + pub(crate) struct Prepared { + path: PathBuf, + raw: RawScene, + tags: Vec<MeshTag>, + report: CleanReport, + read: Value, + quality: Quality, + source: Option<(Vec<u8>, String)>, + } + + /// Reads and cleans a CAD file without touching the session; safe on a worker thread. + pub(crate) fn prepare(path: &Path, args: &Value, watch: &Watch) -> Result<Prepared> { + let quality = quality_of(args, "cad_quality")?; + let clean = clean_options(args)?; + let abs = path.canonicalize().map_err(|e| EngineError::File(format!("{} cannot be opened: {e}", path.display())))?; + let read = fsh_cad::read(&abs, &ReadOptions { quality, ..ReadOptions::default() }, watch).map_err(cad_error)?; + let mut raw = read.scene; + let report = fsh_io::clean(&mut raw, &clean, watch)?; + let ext = read.format.extension().to_string(); + let size = std::fs::metadata(&abs).map(|m| m.len()).unwrap_or(u64::MAX); + let source = if size <= fsh_format::MAX_SOURCE_BYTES as u64 { + Some((std::fs::read(&abs).map_err(|e| EngineError::File(format!("{} cannot be read: {e}", abs.display())))?, ext)) + } else { + None + }; + let info = json!({ + "format": read.format.extension(), + "bodies": read.bodies, + "shared": read.shared, + "quality": read.quality.to_json(), + "linear_mm": read.linear_mm, + "angular_deg": read.angular_rad.to_degrees(), + "diagonal_mm": read.diagonal_mm, + "occt": read.occt, + "worker_tag": read.tag, + }); + Ok(Prepared { path: abs, raw, tags: read.tags, report, read: info, quality, source }) + } + + fn stored_options(p: &Prepared, args: &Value) -> String { + let mut kept = serde_json::Map::new(); + for k in ["options", "stand_on_floor", "center", "merge", "cad_quality"] { + if let Some(v) = args.get(k).filter(|v| !v.is_null()) { + kept.insert(k.into(), v.clone()); + } + } + kept.insert("units".into(), json!(p.report.unit.as_str())); + kept.insert("up_axis".into(), json!(p.report.up_axis.as_str())); + Value::Object(kept).to_string() + } + + fn tag_payload(cmd: &mut Command, p: &Prepared, wrap: bool, reference: &str, args: &Value) { + let options = stored_options(p, args); + let Command::Import(imp) = cmd else { return }; + let raw = &p.raw; + let mut referenced = vec![false; raw.meshes.len()]; + for n in &raw.nodes { + for &m in &n.meshes { + if let Some(r) = referenced.get_mut(m) { + *r = true; + } + } + } + let emitted: Vec<usize> = (0..raw.meshes.len()).filter(|&i| referenced[i] && !raw.meshes[i].indices.is_empty()).collect(); + let mesh_tag: HashMap<u64, MeshTag> = if emitted.len() == imp.payload.meshes.len() { + imp.payload.meshes.iter().zip(&emitted).filter_map(|(m, &i)| p.tags.get(i).map(|t| (m.key.raw(), *t))).collect() + } else { + HashMap::new() + }; + let source_path = p.path.to_string_lossy().to_string(); + let wrap_id = wrap.then(|| imp.payload.nodes.first().map(|n| n.id)).flatten(); + let mut paths: HashMap<NodeId, String> = HashMap::new(); + for n in &mut imp.payload.nodes { + let own = n.node.name.clone(); + let inside = match n.node.parent.and_then(|q| paths.get(&q)) { + Some(up) if !up.is_empty() => format!("{up}/{own}"), + _ if Some(n.id) == wrap_id => String::new(), + _ => own, + }; + paths.insert(n.id, inside.clone()); + let meta = &mut n.node.metadata; + meta.insert("source.path".into(), source_path.clone()); + meta.insert("source.node".into(), inside); + if n.node.parent.is_none() { + meta.insert("source.options".into(), options.clone()); + } + if let NodeKind::Part { mesh, .. } = n.node.kind { + meta.insert("source.cad".into(), reference.to_string()); + meta.insert("cad.quality".into(), p.quality.to_text()); + meta.insert("cad.unit".into(), p.report.unit.as_str().into()); + meta.insert("cad.up".into(), p.report.up_axis.as_str().into()); + if let Some(t) = mesh_tag.get(&mesh.raw()) { + meta.insert("cad.mesh".into(), format!("{}:{}", t.body, t.slot)); + } + } + } + } + + fn frame_camera(st: &mut State) -> Result<()> { + let snap = st.editor.snapshot(); + let doc = st.editor.document(); + let Ok(b) = view::bounds(doc, &snap, None) else { return Ok(()) }; + let values = view::frame_values(doc.active_camera(), &b, 0.8, doc.render_settings().aspect()); + let index = doc.active_camera_index(); + let out = st.editor.dispatch("camera.set", json!({"index": index, "values": values}))?; + st.note(&out); + Ok(()) + } + + fn reference_of(p: &Prepared) -> String { + match &p.source { + Some((bytes, ext)) => fsh_format::source_member(bytes, ext) + .map(|m| format!("{}{m}", fsh_format::EMBED_SCHEME)) + .unwrap_or_else(|| p.path.to_string_lossy().to_string()), + None => p.path.to_string_lossy().to_string(), + } + } + + /// With merge, a file whose one top node is a part still gets a group named after the file around it, as + /// file.import's merge promises; true when the group was added. + fn merge_single_part(cmd: &mut Command, name: &str) -> bool { + let Command::Import(imp) = cmd else { return false }; + let p = &mut imp.payload; + let tops: Vec<usize> = p.nodes.iter().enumerate().filter(|(_, n)| n.node.parent.is_none()).map(|(i, _)| i).collect(); + let [top] = tops[..] else { return false }; + if matches!(p.nodes[top].node.kind, NodeKind::Group) { + return false; + } + let meshes = p.meshes.iter().map(|m| m.key.raw()); + let materials = p.materials.iter().map(|m| m.key.raw()); + let textures = p.textures.iter().map(|t| t.key.raw()); + let next = meshes.chain(materials).chain(textures).chain(p.nodes.iter().map(|n| n.id.raw())).max().unwrap_or(0) + 1; + let id = NodeId::new(next); + p.nodes[top].node.parent = Some(id); + p.nodes.insert(0, fsh_scene::ImportNode { id, node: fsh_scene::Node::new(name, NodeKind::Group) }); + true + } + + fn import_command(p: &Prepared, doc: &fsh_scene::Document, args: &Value) -> Result<(Command, String)> { + let wrap = wrap_of(args); + let roots = p.raw.nodes.iter().filter(|n| n.parent.is_none()).count(); + let mut cmd = fsh_io::to_import_command(&p.raw, doc, &ImportOptions { parent: None, wrap_in_group: wrap }, &Watch::new())?; + let merged = opt_bool(args, "merge") == Some(true) && merge_single_part(&mut cmd, &p.raw.name); + let reference = reference_of(p); + tag_payload(&mut cmd, p, merged || (wrap && roots > 1), &reference, args); + Ok((cmd, reference)) + } + + /// The `scene.import` a re-import compares against the document: the file read again with the import's stored + /// options, tagged like an import; also the source bytes to keep when the re-import applies. + pub(crate) fn reread(path: &Path, stored: &Value, doc: &fsh_scene::Document, top: NodeId) -> Result<super::Reread> { + let mut args = if stored.is_object() { stored.clone() } else { json!({}) }; + let current = doc.subtree(top).into_iter().find_map(|id| doc.node(id).and_then(|n| n.metadata.get("cad.quality")).and_then(|q| Quality::from_text(q))); + if let Some(q) = current { + args["cad_quality"] = q.to_json(); + } + let p = prepare(path, &args, &Watch::new())?; + let (cmd, _) = import_command(&p, doc, &args)?; + Ok((cmd, p.report, p.source)) + } + + /// Adds a prepared CAD import to the document as one undo step and keeps its source in the project. + pub(crate) fn apply(engine: &Engine, st: &mut State, p: Prepared, args: &Value, frame: Option<bool>) -> Result<Value> { + let (cmd, reference) = import_command(&p, st.editor.document(), args)?; + let was_empty = !st.editor.document().nodes().values().any(|n| matches!(n.kind, NodeKind::Part { .. })); + let stem = p.path.file_stem().and_then(|s| s.to_str()).unwrap_or("CAD").to_string(); + let label = format!("Import {}", get_str(args, "name").filter(|n| !n.is_empty()).unwrap_or(&stem)); + st.editor.begin_group(&label); + st.note_begin(&label); + let result = (|| -> Result<Outcome> { + let out = st.editor.execute(cmd)?; + st.note(&out); + if let Some(name) = get_str(args, "name").filter(|n| !n.is_empty()) { + let roots: Vec<u64> = out + .created + .iter() + .copied() + .filter(|k| st.editor.document().node(NodeId::new(*k)).is_some_and(|n| n.parent.is_none() && n.name == stem)) + .collect(); + for r in roots { + let renamed = st.editor.dispatch("scene.rename", json!({"id": r, "name": name}))?; + st.note(&renamed); + } + } + if frame.unwrap_or(was_empty) { + frame_camera(st)?; + } + Ok(out) + })(); + let out = match result { + Ok(o) => { + st.editor.end_group()?; + st.note_end(); + o + } + Err(e) => { + if let Ok(back) = st.editor.abandon_group() { + st.note(&back); + } + return Err(e); + } + }; + let kept = super::keep_source(st, p.source); + let mut reply = engine.changed(st, &Outcome { level: ChangeLevel::Full, ..out }, false); + reply["name"] = json!("file.import"); + reply["report"] = json!({ + "triangles_dropped": p.report.triangles_dropped, + "vertices_welded": p.report.vertices_welded, + "unused_vertices_removed": p.report.unused_vertices_removed, + "meshes_given_normals": p.report.meshes_given_normals, + "instances_found": p.report.instances_found, + "unit": p.report.unit.as_str(), + "unit_guessed": p.report.unit_guessed, + "up_axis": p.report.up_axis.as_str(), + "warnings": p.report.warnings, + }); + let mut cad = p.read; + cad["source"] = json!(reference); + cad["kept"] = json!(kept); + cad["triangles"] = json!(p.raw.triangle_count()); + reply["cad"] = cad; + let clean = clean_options(args).unwrap_or_default(); + reply["options"] = json!({ + "units": opt_str(args, "units").unwrap_or("auto"), + "up_axis": opt_str(args, "up_axis").unwrap_or("auto"), + "stand_on_floor": clean.stand_on_floor, + "center": clean.centre, + "merge": opt_bool(args, "merge").unwrap_or(false), + "cad_quality": p.quality.to_json(), + }); + reply["source"] = json!(p.path.to_string_lossy()); + Ok(reply) + } + + struct Scratch(Option<PathBuf>); + + impl Drop for Scratch { + fn drop(&mut self) { + if let Some(d) = self.0.take() { + let _ = std::fs::remove_dir_all(d); + } + } + } + + fn source_file(st: &State, reference: &str, fallback: Option<&str>, scratch: &mut Scratch, n: usize) -> Result<PathBuf> { + if let Some(bytes) = st.kept.source_bytes(reference).filter(|_| reference.starts_with(fsh_format::EMBED_SCHEME)) { + let ext = reference.rsplit('.').next().unwrap_or("step"); + let dir = match &scratch.0 { + Some(d) => d.clone(), + None => { + let d = std::env::temp_dir().join(format!("formshot-retessellate-{}-{}", std::process::id(), st.revision)); + std::fs::create_dir_all(&d).map_err(|e| EngineError::File(format!("no scratch folder for the CAD source: {e}")))?; + scratch.0 = Some(d.clone()); + d + } + }; + let file = dir.join(format!("source{n}.{ext}")); + std::fs::write(&file, bytes).map_err(|e| EngineError::File(format!("the kept CAD source could not be written out: {e}")))?; + return Ok(file); + } + let direct = (!reference.starts_with(fsh_format::EMBED_SCHEME)).then(|| PathBuf::from(reference)); + if let Some(p) = direct.into_iter().chain(fallback.map(PathBuf::from)).find(|p| p.is_file()) { + return Ok(p); + } + Err(EngineError::state(format!( + "the CAD source {reference} is neither kept in this project nor on disk{}", + fallback.map(|f| format!(" (nor at {f})")).unwrap_or_default() + ))) + } + + fn parse_tag(s: &str) -> Option<(usize, usize)> { + let (b, k) = s.split_once(':')?; + Some((b.trim().parse().ok()?, k.trim().parse().ok()?)) + } + + struct Target { + id: NodeId, + name: String, + mesh: fsh_core::MeshKey, + tag: (usize, usize), + } + + pub(super) fn retessellate(engine: &Engine, st: &mut State, args: &Value) -> Result<Value> { + use fsh_scene::{Mesh, MeshAdd}; + use std::collections::{BTreeMap, BTreeSet}; + use std::sync::Arc; + + if opt(args, "quality").is_none() { + return Err(EngineError::args("scene.retessellate needs quality: draft, medium, high, ultra or {chord, angle}")); + } + let quality = quality_of(args, "quality")?; + let doc = st.editor.document(); + let scope: Option<BTreeSet<NodeId>> = match args.get("nodes") { + None | Some(Value::Null) => None, + Some(Value::Array(a)) => { + let mut set = BTreeSet::new(); + for v in a { + let id = crate::util::key_of(v).map(NodeId::new).ok_or_else(|| EngineError::args(format!("nodes holds {v}, which is not a node id")))?; + doc.get_node(id)?; + set.extend(doc.subtree(id)); + } + Some(set) + } + Some(_) => return Err(EngineError::args("nodes must be a list of node ids")), + }; + let mut warnings = Vec::new(); + let mut groups: BTreeMap<(String, String, String, String), Vec<Target>> = BTreeMap::new(); + for (id, n) in doc.nodes() { + if scope.as_ref().is_some_and(|s| !s.contains(id)) { + continue; + } + let NodeKind::Part { mesh, .. } = n.kind else { continue }; + let (Some(reference), Some(tag)) = (n.metadata.get("source.cad"), n.metadata.get("cad.mesh").and_then(|t| parse_tag(t))) else { + continue; + }; + if doc.is_locked(*id) { + warnings.push(format!("{} ({id}) is locked and was left as it is", n.name)); + continue; + } + let unit = n.metadata.get("cad.unit").cloned().unwrap_or_else(|| "m".into()); + let up = n.metadata.get("cad.up").cloned().unwrap_or_else(|| "z".into()); + let fallback = n.metadata.get("source.path").cloned().unwrap_or_default(); + groups.entry((reference.clone(), unit, up, fallback)).or_default().push(Target { id: *id, name: n.name.clone(), mesh, tag }); + } + if groups.is_empty() { + return Err(EngineError::state("there are no CAD parts to re-tessellate (parts imported from STEP or IGES carry source.cad)")); + } + let mut scratch = Scratch(None); + let mut new_meshes: BTreeMap<u64, Arc<Mesh>> = BTreeMap::new(); + let mut plan: Vec<Target> = Vec::new(); + let mut triangles_before = 0usize; + let mut triangles_after = 0usize; + let watch = Watch::new(); + for (i, ((reference, unit, up, fallback), targets)) in groups.into_iter().enumerate() { + let file = source_file(st, &reference, Some(fallback.as_str()).filter(|f| !f.is_empty()), &mut scratch, i)?; + let read = fsh_cad::read(&file, &ReadOptions { quality, ..ReadOptions::default() }, &watch).map_err(cad_error)?; + let clean = CleanOptions { + unit: Some(unit.parse::<LengthUnit>().map_err(|e| EngineError::args(e.to_string()))?), + up_axis: Some(UpAxis::parse(&up).unwrap_or(UpAxis::Z)), + detect_instances: false, + stand_on_floor: false, + centre: false, + ..CleanOptions::default() + }; + let mut raw = read.scene; + fsh_io::clean(&mut raw, &clean, &watch)?; + let index: HashMap<(usize, usize), usize> = read.tags.iter().enumerate().map(|(i, t)| ((t.body, t.slot), i)).collect(); + for t in targets { + if let std::collections::btree_map::Entry::Vacant(slot) = new_meshes.entry(t.mesh.raw()) { + let Some(r) = index.get(&t.tag).and_then(|&i| raw.meshes.get(i)).filter(|r| !r.indices.is_empty()) else { + warnings.push(format!("{} ({}) has no body {}:{} in its source any more and was left as it is", t.name, t.id, t.tag.0, t.tag.1)); + continue; + }; + let old = st.editor.document().mesh(t.mesh); + triangles_before += old.map(|m| m.indices.len() / 3).unwrap_or(0); + let name = old.map(|m| m.name.clone()).unwrap_or_else(|| r.name.clone()); + let mut mesh = Mesh::new(name, r.positions.clone(), r.indices.clone())?; + mesh.normals = r.normals.clone(); + mesh.validate()?; + triangles_after += mesh.indices.len() / 3; + slot.insert(Arc::new(mesh)); + } + plan.push(t); + } + } + if plan.is_empty() { + return Err(EngineError::state(format!("nothing was re-tessellated: {}", warnings.join("; ")))); + } + let label = format!("Re-tessellate {} CAD parts ({})", plan.len(), quality.name()); + st.editor.begin_group(&label); + st.note_begin(&label); + let mut replaced = Vec::new(); + let result = (|| -> Result<Outcome> { + let mut swapped: BTreeMap<u64, fsh_core::MeshKey> = BTreeMap::new(); + let mut last = None; + for (old, mesh) in &new_meshes { + let out = st.editor.execute(Command::MeshAdd(MeshAdd { key: None, mesh: mesh.clone() }))?; + st.note(&out); + let key = out.created.first().copied().ok_or_else(|| EngineError::state("mesh.add created no key"))?; + swapped.insert(*old, fsh_core::MeshKey::new(key)); + } + for t in &plan { + let Some(&mesh) = swapped.get(&t.mesh.raw()) else { continue }; + let out = st.editor.dispatch("scene.set_part_mesh", json!({"id": t.id.raw(), "mesh": mesh.raw(), "remove_unused": true}))?; + st.note(&out); + let tagged = st.editor.dispatch("scene.set_metadata", json!({"id": t.id.raw(), "key": "cad.quality", "value": quality.to_text()}))?; + st.note(&tagged); + replaced.push(json!({"id": t.id.raw().to_string(), "name": t.name, "mesh": mesh.raw().to_string()})); + last = Some(out); + } + last.ok_or_else(|| EngineError::state("nothing was re-tessellated")) + })(); + let out = match result { + Ok(o) => { + st.editor.end_group()?; + st.note_end(); + o + } + Err(e) => { + if let Ok(back) = st.editor.abandon_group() { + st.note(&back); + } + return Err(e); + } + }; + let mut reply = engine.changed(st, &Outcome { level: ChangeLevel::Full, ..out }, false); + reply["name"] = json!("scene.retessellate"); + reply["quality"] = quality.to_json(); + reply["parts"] = json!(replaced.len()); + reply["meshes"] = json!(new_meshes.len()); + reply["triangles_before"] = json!(triangles_before); + reply["triangles_after"] = json!(triangles_after); + reply["replaced"] = json!(replaced); + if !warnings.is_empty() { + let mut all: Vec<Value> = reply.get("warnings").and_then(Value::as_array).cloned().unwrap_or_default(); + all.extend(warnings.into_iter().map(Value::from)); + reply["warnings"] = json!(all); + } + Ok(reply) + } + + + fn capabilities() -> Value { + json!({ + "progress": {"supported": "per body", "reason": "the worker answers each request with one line and sends no progress while it opens a file or tessellates one body"}, + "body_colours": {"supported": true}, + "face_colours": {"supported": "STEP, from the file", "reason": "xde_read reports one rgb per body (label_color on the body's shape), never a colour per face; FormShot reads STEP face styles itself and matches each body to the one manifold solid with its face count (faces in shell order), and reads face_rgb when a worker sends it"}, + "iges_colours": {"supported": "from the file", "reason": "the worker gives IGES bodies no colour; FormShot reads the colours and names of the file's manifold solids (entity 186) when they match the bodies one to one"}, + "instance_transforms": {"supported": "derived", "reason": "xde_read returns bodies already placed and only the shared def key; FormShot recovers each instance's transform by matching its tessellation to the first one"}, + "pmi": {"supported": false, "reason": "not asked for (pmi: false)"}, + }) + } + + pub(super) fn status(probe: bool) -> Value { + let cache = fsh_cad::workers_dir().map(|p| p.to_string_lossy().to_string()); + let installed: Vec<Value> = + fsh_cad::installed().into_iter().map(|(t, p)| json!({"tag": t, "path": p.to_string_lossy()})).collect(); + let located = match locate() { + Ok(l) => l, + Err(e) => { + return json!({"available": false, "reason": e.to_string(), "code": e.code(), "cache": cache, "installed": installed, "protocol": PROTOCOL}) + } + }; + let mut out = json!({ + "available": true, + "path": located.path.to_string_lossy(), + "tag": located.tag, + "origin": located.origin.as_str(), + "cache": cache, + "installed": installed, + "protocol": PROTOCOL, + "capabilities": capabilities(), + }); + if probe { + match Worker::start(&located, fsh_cad::hello_timeout(), None) { + Ok(w) => { + out["occt"] = json!(w.hello().occt); + out["worker_protocol"] = json!(w.hello().protocol); + out["methods"] = json!(w.hello().methods.len()); + w.shutdown(); + } + Err(e) => { + out["available"] = json!(false); + out["reason"] = json!(e.to_string()); + out["code"] = json!(e.code()); + } + } + } + out + } +} + +#[cfg(target_arch = "wasm32")] +mod native { + use crate::engine::{Engine, State}; + use crate::error::Result; + use fsh_io::{IoError, RawScene, Watch}; + use serde_json::{json, Value}; + use std::path::Path; + + const NO_WORKER: &str = "this build has no CAD worker; STEP and IGES open in the desktop app and the service"; + + pub(super) fn status(_probe: bool) -> Value { + json!({"available": false, "reason": NO_WORKER, "code": "cad_unsupported"}) + } + + pub(super) fn read_cad(_path: &Path, _quality: &Value, _watch: &Watch) -> fsh_io::Result<RawScene> { + Err(IoError::Unsupported(NO_WORKER.into())) + } + + pub(crate) struct Prepared; + + pub(super) fn probe(path: &Path, _use_worker: bool) -> Result<Value> { + let bytes = std::fs::metadata(path).map_err(|e| crate::error::EngineError::File(format!("{}: {e}", path.display())))?.len(); + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + let format = if matches!(ext.as_str(), "iges" | "igs") { "iges" } else { "step" }; + Ok(json!({"path": path.to_string_lossy(), "bytes": bytes, "format": format, "warnings": [], "cad": {"worker": false, "reason": NO_WORKER}})) + } + + pub(super) fn prepare(_path: &Path, _args: &Value, _watch: &Watch) -> Result<Prepared> { + Err(IoError::Unsupported(NO_WORKER.into()).into()) + } + + pub(super) fn apply(_engine: &Engine, _st: &mut State, _p: Prepared, _args: &Value, _frame: Option<bool>) -> Result<Value> { + Err(IoError::Unsupported(NO_WORKER.into()).into()) + } + + pub(super) fn reread(_path: &Path, _stored: &Value, _doc: &fsh_scene::Document, _top: fsh_core::NodeId) -> Result<super::Reread> { + Err(IoError::Unsupported(NO_WORKER.into()).into()) + } + + pub(super) fn retessellate(_engine: &Engine, _st: &mut State, _args: &Value) -> Result<Value> { + Err(IoError::Unsupported(NO_WORKER.into()).into()) + } +} diff --git a/native/crates/fsh-commands/src/ext/handoff.rs b/native/crates/fsh-commands/src/ext/handoff.rs new file mode 100644 index 00000000..bfc6fc15 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/handoff.rs @@ -0,0 +1,280 @@ +//! Models and materials handed over by other Form apps (0.5.0). + +use super::ExtCommand; +use crate::engine::{frame_values, Engine, State}; +use crate::error::{EngineError, Result}; +use crate::util::{get_bool, get_str}; +use fsh_core::{DocKey, MaterialKey, NodeId, TextureKey}; +use fsh_format::Project; +use fsh_io::family::{self, Inspection}; +use fsh_io::{surface_params, CleanOptions, ImportOptions, RawScene, Watch}; +use fsh_scene::{ + ChangeLevel, Command, Document, Editor, Import, ImportMaterial, ImportPayload, ImportTexture, Material, NodeKind, Outcome, TextureRef, +}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::path::Path; + +pub(super) static COMMANDS: &[ExtCommand] = &[ + ExtCommand { + name: "handoff.inspect", + description: "Tell what a file or folder another Form app wrote is (a GoF folder from FormSculpt or FormFabric, a FormSurface export folder of maps, a FormCAD, FormSculpt or FormFabric model) and what it holds, without changing the document.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: inspect_schema, + }, + ExtCommand { + name: "handoff.open", + description: "Open what another Form app handed over, as a new document or added to the current one as one undo step; every node that arrives records source.app, source.path and source.node in its metadata, and FormSurface's maps arrive as texture references by role and colour space.", + level: ChangeLevel::Full, + mutates: true, + read_only: false, + schema: open_schema, + }, +]; + +fn open_schema() -> Value { + json!({ + "type": "object", + "properties": { + "path": path_schema(), + "item": item_schema(), + "as": {"type": "string", "enum": ["new", "add"], "default": "add", "description": "new replaces the document with a new one holding the hand-off; add puts it into the current document as one undo step."}, + "frame": {"type": "boolean", "description": "Frame the camera on the scene afterwards; by default when the document had no parts before, or for a new document."} + }, + "required": ["path"], + "additionalProperties": false + }) +} + +fn path_schema() -> Value { + json!({"type": "string", "minLength": 1, "description": "Absolute path of the file or folder: a GoF folder (holding gof.json), a FormSurface export folder or one of its files, or a model file."}) +} + +fn item_schema() -> Value { + json!({"type": ["string", "integer"], "description": "For a GoF folder: the entry's file name, id or name; the newest entry meant for FormShot (target any or formshot) when omitted."}) +} + +fn inspect_schema() -> Value { + json!({ + "type": "object", + "properties": { + "path": path_schema(), + "item": item_schema(), + "read": {"type": "boolean", "default": true, "description": "Read the model too, to count meshes, triangles, materials and textures."} + }, + "required": ["path"], + "additionalProperties": false + }) +} + +fn item_of(args: &Value) -> Option<String> { + match args.get("item") { + Some(Value::String(s)) if !s.trim().is_empty() => Some(s.clone()), + Some(Value::Number(n)) => Some(n.to_string()), + _ => None, + } +} + +fn inspection(args: &Value) -> Result<Inspection> { + let path = get_str(args, "path").filter(|p| !p.trim().is_empty()).ok_or_else(|| EngineError::args("give path: the file or folder another Form app wrote"))?; + Ok(family::inspect(Path::new(path), item_of(args).as_deref())?) +} + +fn contents(raw: &RawScene) -> Value { + json!({ + "meshes": raw.meshes.iter().filter(|m| !m.indices.is_empty()).count(), + "triangles": raw.triangle_count(), + "nodes": raw.nodes.len(), + "materials": raw.materials.iter().map(|m| m.name.clone()).collect::<Vec<_>>(), + "textures": raw.textures.len(), + "unit": raw.unit.map(|u| u.as_str()), + "up_axis": raw.up_axis.map(|a| a.as_str()), + "warnings": raw.warnings, + }) +} + +fn inspect(args: &Value) -> Result<Value> { + let insp = inspection(args)?; + let mut out = insp.to_json(); + if get_bool(args, "read").unwrap_or(true) && (insp.model.is_some() || insp.materials_only()) { + out["contents"] = match insp.read(&Watch::new()) { + Ok(raw) => contents(&raw), + Err(e) => json!({"error": e.to_string(), "code": e.code()}), + }; + } + out["ok"] = json!(true); + Ok(out) +} + +fn add_materials(payload: &mut ImportPayload, raw: &RawScene, which: &[usize], first_key: u64) { + let mut next = first_key.max(1); + let mut key = || { + next += 1; + next - 1 + }; + let mut tex_keys: Vec<Option<TextureKey>> = vec![None; raw.textures.len()]; + for &mi in which { + for &ti in &raw.materials[mi].textures { + let Some(t) = raw.textures.get(ti).filter(|_| tex_keys[ti].is_none()) else { continue }; + let k = TextureKey::from_raw(key()); + tex_keys[ti] = Some(k); + let texture = TextureRef { path: t.uri.clone(), role: t.role, uv_set: t.uv_set, colour_space: Some(t.colour_space.to_string()) }; + payload.textures.push(ImportTexture { key: k, texture }); + } + } + for &mi in which { + let m = &raw.materials[mi]; + let mut material = Material::new(m.name.clone(), if m.metallic > 0.5 { "metal" } else { "generic" }, surface_params(m)); + material.textures = m.textures.iter().filter_map(|&t| tex_keys.get(t).copied().flatten()).collect(); + payload.materials.push(ImportMaterial { key: MaterialKey::from_raw(key()), material }); + } +} + +fn materials_command(raw: &RawScene, doc: &Document) -> Command { + let mut payload = ImportPayload::default(); + add_materials(&mut payload, raw, &(0..raw.materials.len()).collect::<Vec<_>>(), doc.next_key()); + Command::Import(Import { parent: None, payload }) +} + +fn with_unused_materials(mut cmd: Command, raw: &RawScene, doc: &Document) -> Command { + let used: Vec<bool> = (0..raw.materials.len()).map(|i| raw.meshes.iter().any(|m| m.material == Some(i))).collect(); + let unused: Vec<usize> = (0..raw.materials.len()).filter(|&i| !used[i]).collect(); + if let (Command::Import(import), false) = (&mut cmd, unused.is_empty()) { + let p = &import.payload; + let top = p + .meshes + .iter() + .map(|m| m.key.raw()) + .chain(p.materials.iter().map(|m| m.key.raw())) + .chain(p.textures.iter().map(|t| t.key.raw())) + .chain(p.nodes.iter().map(|n| n.id.raw())) + .max() + .unwrap_or(0); + add_materials(&mut import.payload, raw, &unused, (top + 1).max(doc.next_key())); + } + cmd +} + +fn stamp(cmd: &mut Command, insp: &Inspection) { + let Command::Import(import) = cmd else { return }; + let nodes = &mut import.payload.nodes; + let names: HashMap<NodeId, (String, Option<NodeId>)> = nodes.iter().map(|n| (n.id, (n.node.name.clone(), n.node.parent))).collect(); + let source = insp.source_path().to_string_lossy().into_owned(); + let extra = insp.metadata(); + for n in nodes.iter_mut() { + let mut path = vec![n.node.name.clone()]; + let mut up = n.node.parent; + let mut guard = 0; + while let Some(p) = up.and_then(|p| names.get(&p)) { + path.push(p.0.clone()); + up = p.1; + guard += 1; + if guard > names.len() { + break; + } + } + path.reverse(); + let root = n.node.parent.is_none_or(|p| !names.contains_key(&p)); + let meta = &mut n.node.metadata; + meta.insert("source.path".into(), source.clone()); + meta.insert("source.node".into(), path.join("/")); + for (k, v) in &extra { + if root || k == "source.app" || k == "source.handoff" { + meta.insert(k.clone(), v.clone()); + } + } + } +} + +fn has_parts(doc: &Document) -> bool { + doc.nodes().values().any(|n| matches!(n.kind, NodeKind::Part { .. })) +} + +fn open(engine: &Engine, st: &mut State, args: &Value) -> Result<Value> { + let mode = get_str(args, "as").unwrap_or("add"); + if !matches!(mode, "new" | "add") { + return Err(EngineError::args(format!("as is new or add, not \"{mode}\""))); + } + let insp = inspection(args)?; + let watch = Watch::new(); + let mut raw = insp.read(&watch)?; + let materials_only = insp.materials_only(); + let clean = CleanOptions { unit: insp.declared_unit(), ..CleanOptions::default() }; + let report = if materials_only { None } else { Some(fsh_io::clean(&mut raw, &clean, &watch)?) }; + if mode == "new" { + let doc = crate::sample::build(None, &insp.title)?; + let mut editor = Editor::new(doc); + editor.history_mut().mark_saved(); + engine.install_editor(st, editor, None, Project::default()); + } + let was_empty = !has_parts(st.editor.document()); + let mut cmd = if materials_only { + materials_command(&raw, st.editor.document()) + } else { + let cmd = fsh_io::to_import_command(&raw, st.editor.document(), &ImportOptions { parent: None, wrap_in_group: true }, &watch)?; + with_unused_materials(cmd, &raw, st.editor.document()) + }; + stamp(&mut cmd, &insp); + let from = insp.app.map(|a| a.name()).or(insp.writer.as_deref()).unwrap_or("another app"); + let label = format!("Hand-off from {from}: {}", insp.title); + let frame = get_bool(args, "frame").unwrap_or(was_empty && !materials_only); + st.editor.begin_group(&label); + st.note_begin(&label); + let result = (|| -> Result<Outcome> { + let out = st.editor.execute(cmd)?; + st.note(&out); + if frame { + if let Ok(values) = frame_values(st.editor.document(), 1.15) { + let index = st.editor.document().active_camera_index(); + let framed = st.editor.dispatch("camera.set", json!({"index": index, "values": values}))?; + st.note(&framed); + } + } + Ok(out) + })(); + let out = match result { + Ok(o) => { + st.editor.end_group()?; + st.note_end(); + o + } + Err(e) => { + if let Ok(back) = st.editor.abandon_group() { + st.note(&back); + } + return Err(e); + } + }; + let mut reply = engine.changed(st, &Outcome { level: ChangeLevel::Full, ..out }, false); + reply["name"] = json!("handoff.open"); + reply["as"] = json!(mode); + reply["app"] = json!(insp.app.map(|a| a.id())); + reply["app_name"] = json!(from); + reply["kind"] = json!(insp.kind.as_str()); + reply["title"] = json!(insp.title); + reply["source"] = json!(insp.source_path().to_string_lossy()); + reply["materials_only"] = json!(materials_only); + reply["contents"] = contents(&raw); + reply["maps"] = json!(insp.maps().iter().map(|m| m.to_json()).collect::<Vec<_>>()); + if let Some(r) = report { + reply["report"] = json!({ + "triangles_dropped": r.triangles_dropped, "vertices_welded": r.vertices_welded, "meshes_given_normals": r.meshes_given_normals, + "instances_found": r.instances_found, "unit": r.unit.as_str(), "unit_guessed": r.unit_guessed, "up_axis": r.up_axis.as_str(), + "warnings": r.warnings, + }); + } + if !insp.warnings.is_empty() { + reply["notes"] = json!(insp.warnings); + } + Ok(reply) +} + +pub(super) fn dispatch(engine: &Engine, st: &mut State, name: &str, args: &Value) -> Option<Result<Value>> { + match name { + "handoff.inspect" => Some(inspect(args)), + "handoff.open" => Some(open(engine, st, args)), + _ => None, + } +} diff --git a/native/crates/fsh-commands/src/ext/import.rs b/native/crates/fsh-commands/src/ext/import.rs new file mode 100644 index 00000000..4ee83b01 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/import.rs @@ -0,0 +1,160 @@ +//! Import options, progress, cancel and re-import (0.5.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::{EngineError, Result}; +use crate::util::{get_bool, get_str}; +use fsh_io::Watch; +use fsh_scene::ChangeLevel; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +mod jobs; +mod options; +mod probe; +mod reimport; +mod run; +mod source; +pub(crate) mod textures; + +use options::ImportArgs; + +pub(super) static COMMANDS: &[ExtCommand] = &[ + ExtCommand { + name: "import.probe", + description: "Read a model file without changing the document: {format, units_declared, units_guess, unit_guessed, up_axis, bounds: {min, max, size} in file units and size_m (the size in metres at units_guess), triangles, meshes, nodes, materials, textures, images_in_file (images stored inside the model), texture_slots, warnings}.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: probe_schema, + }, + ExtCommand { + name: "import.start", + description: "Start importing a model in the background with the file.import options and return {job}; the read and clean-up run on a worker, and the document changes (one undo step) on the first engine call after the worker finishes. Follow it with import.status.", + level: ChangeLevel::Full, + mutates: true, + read_only: false, + schema: file_import_schema, + }, + ExtCommand { + name: "import.status", + description: "An import job's progress: {job, state (running, done, failed, cancelled, or stale when the document was replaced while it ran and nothing was applied), stage (reading, validating, welding, normals, instancing, placing, converting, then waiting while a history group is open, done), fraction (0 to 1 over the whole import), path, seconds, result (the file.import reply) when done, error {message, code} when failed}; without job, {jobs: [...]} for every job of this session.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: job_schema_optional, + }, + ExtCommand { + name: "import.cancel", + description: "Cancel a running import job; the document stays exactly as it was. Answers the job's status with cancelled true when it was still running.", + level: ChangeLevel::None, + mutates: false, + read_only: false, + schema: job_schema, + }, + ExtCommand { + name: "file.reimport", + description: "Read the source files of the given imported nodes again (every imported node when none): parts match by source.node, then by unique name, then by identical shape; matched parts keep their materials and transforms and take the new shape, new parts are added, parts gone from the file are hidden (marked source.missing), all as one undo step. Answers {matched, added, hidden, updated, files: [{path, matched, added, hidden, updated, warnings, report (the clean-up report of the re-read), error?}]}.", + level: ChangeLevel::Full, + mutates: true, + read_only: false, + schema: reimport_schema, + }, +]; + +fn reimport_schema() -> Value { + let mut p = serde_json::Map::new(); + p.insert("nodes".into(), json!({"type": "array", "items": {"type": ["string", "integer"]}, "description": "Imported nodes (or groups holding them) whose files to read again; every imported node when absent"})); + object(p, &[]) +} + +fn probe_schema() -> Value { + let mut p = serde_json::Map::new(); + p.insert("path".into(), json!({"type": "string", "description": "Model file to read"})); + p.insert("worker".into(), json!({"type": "boolean", "default": true, "description": "STEP and IGES: also open the file with the CAD worker (bodies, groups, colours, size; a few seconds); false answers from the file's header alone"})); + object(p, &["path"]) +} + +fn job_props() -> serde_json::Map<String, Value> { + let mut p = serde_json::Map::new(); + p.insert("job".into(), json!({"type": ["integer", "string"], "description": "Job id from import.start"})); + p +} + +fn job_schema() -> Value { + object(job_props(), &["job"]) +} + +fn job_schema_optional() -> Value { + object(job_props(), &[]) +} + +fn job_of(args: &Value) -> Option<u64> { + args.get("job").and_then(crate::util::key_of) +} + +fn need_path(args: &Value, command: &str) -> Result<PathBuf> { + get_str(args, "path").filter(|p| !p.is_empty()).map(PathBuf::from).ok_or_else(|| EngineError::args(format!("{command} needs path"))) +} + +fn object(props: serde_json::Map<String, Value>, required: &[&str]) -> Value { + json!({"type": "object", "properties": props, "required": required}) +} + +/// The `file.import` argument schema (the catalogue's engine table asks for it). +pub(crate) fn file_import_schema() -> Value { + object(options::properties(), &["path"]) +} + +/// The `file.open` argument schema: a project, or a model opened as a new document with the import options (the +/// camera is always framed, so `frame` is not one of them). +pub(crate) fn file_open_schema() -> Value { + let mut p = options::properties(); + p.remove("frame"); + p.insert( + "path".into(), + json!({"type": "string", "description": "A .fshot project, or a model file (glb, gltf, obj, stl, ply, 3mf, fbx, step, stp, iges, igs) opened as a new document; the other options apply to a model only"}), + ); + object(p, &["path"]) +} + +/// `file.import` (and `file.open` of a model): reads the options, imports now, one undo step. +pub(crate) fn import_now(engine: &Engine, st: &mut State, path: &Path, args: &Value, frame: Option<bool>) -> Result<Value> { + let a = ImportArgs::parse(args, frame)?; + let prepared = run::prepare(path, &a, st.editor.document(), &Watch::new())?; + run::apply(engine, st, prepared, &a) +} + +/// Applies finished background imports; the engine calls it before every command. +pub(crate) fn pump(engine: &Engine, st: &mut State) { + jobs::pump(engine, st); +} + +pub(crate) use jobs::Jobs; + +/// The engine installed another document; running import jobs stop and report stale. +pub(crate) fn document_changed(st: &mut State) { + st.jobs.document_changed(); +} + +fn start(st: &mut State, args: &Value) -> Result<Value> { + let path = need_path(args, "import.start")?; + let a = ImportArgs::parse(args, get_bool(args, "frame"))?; + let job = jobs::start(st, path, a)?; + Ok(json!({"ok": true, "change": "none", "job": job, "state": "running"})) +} + +pub(super) fn dispatch(engine: &Engine, st: &mut State, name: &str, args: &Value) -> Option<Result<Value>> { + if !name.starts_with("import.") && name != "file.reimport" { + return None; + } + jobs::pump(engine, st); + Some(match name { + "file.reimport" => crate::view::node_list(st.editor.document(), args).and_then(|nodes| reimport::reimport(engine, st, nodes)), + "import.probe" => need_path(args, name).and_then(|p| if super::cad::is_cad(&p) { super::cad::probe(&p, args) } else { probe::probe(&p) }), + "import.start" => start(st, args), + "import.status" => jobs::status(st, job_of(args)), + "import.cancel" => job_of(args).ok_or_else(|| EngineError::args("import.cancel needs job")).and_then(|j| jobs::cancel(st, j)), + _ => return None, + }) +} diff --git a/native/crates/fsh-commands/src/ext/import/jobs.rs b/native/crates/fsh-commands/src/ext/import/jobs.rs new file mode 100644 index 00000000..19d6a4a3 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/import/jobs.rs @@ -0,0 +1,256 @@ +use super::options::ImportArgs; +use super::run::{self, Prepared}; +use crate::clock::Moment; +use crate::engine::{Engine, State}; +use crate::error::{EngineError, Result}; +use fsh_io::{Stage, Watch}; +use fsh_scene::Document; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{mpsc, Arc}; + +const KEEP_FINISHED: usize = 64; +const STALE: &str = "the document changed (file.new, file.open, file.close or file.recover) while the job ran; nothing was applied"; + +enum Work { + Mesh(Box<Prepared>), + Cad(Box<crate::ext::cad::Prepared>), +} + +enum JobState { + Running(mpsc::Receiver<Result<Work>>), + Done(Value), + Failed(EngineError), + Cancelled, + Stale, +} + +struct Job { + generation: u64, + cad: bool, + path: PathBuf, + args: ImportArgs, + watch: Arc<Watch>, + state: JobState, + started: Moment, + seconds: Option<f64>, +} + +/// One engine's import jobs, kept in its session state so they end with it, and the generation of the document +/// they apply to. +#[derive(Default)] +pub(crate) struct Jobs { + list: BTreeMap<u64, Job>, + generation: u64, +} + +impl Jobs { + /// The engine installed another document: running jobs stop and report stale, finished ones keep their record. + pub(crate) fn document_changed(&mut self) { + self.generation += 1; + for j in self.list.values_mut() { + if matches!(j.state, JobState::Running(_)) { + j.watch.cancel(); + j.state = JobState::Stale; + j.seconds = Some(j.started.elapsed().as_secs_f64()); + } + } + } +} + +impl Drop for Jobs { + fn drop(&mut self) { + for j in self.list.values().filter(|j| matches!(j.state, JobState::Running(_))) { + j.watch.cancel(); + } + } +} + +static NEXT: AtomicU64 = AtomicU64::new(1); + +fn cad_args(a: &ImportArgs) -> Value { + let mut v = Value::Object(a.geometry.clone()); + if let Some(n) = &a.name { + v["name"] = json!(n); + } + v +} + +fn weight(stage: Stage) -> (f32, f32) { + match stage { + Stage::Idle => (0.0, 0.0), + Stage::Reading => (0.0, 0.40), + Stage::Validating => (0.40, 0.45), + Stage::Welding => (0.45, 0.60), + Stage::Normals => (0.60, 0.70), + Stage::Tangents => (0.70, 0.75), + Stage::Instancing => (0.75, 0.80), + Stage::Placing => (0.80, 0.82), + Stage::Converting => (0.82, 0.97), + Stage::Done => (0.97, 0.97), + } +} + +fn overall(watch: &Watch) -> f32 { + let (a, b) = weight(watch.stage()); + a + (b - a) * watch.fraction() +} + +fn overall_of(j: &Job) -> f32 { + let f = overall(&j.watch); + if !j.cad { + return f; + } + let (_, read_end) = weight(Stage::Reading); + let (_, done) = weight(Stage::Done); + if f <= read_end { + 0.9 * f / read_end + } else { + 0.9 + 0.07 * (f - read_end) / (done - read_end) + } +} + +/// Starts reading, cleaning and converting `path` on a worker thread (inline on wasm32) and returns the job id. +pub(crate) fn start(st: &mut State, path: PathBuf, args: ImportArgs) -> Result<u64> { + if !path.is_file() { + return Err(EngineError::File(format!("{}: no such file", path.display()))); + } + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let watch = Arc::new(Watch::new()); + let (tx, rx) = mpsc::channel(); + let work = { + let (path, args, watch) = (path.clone(), args.clone(), Arc::clone(&watch)); + move || { + let r = if crate::ext::cad::is_cad(&path) { + crate::ext::cad::prepare(&path, &cad_args(&args), &watch).map(|p| Work::Cad(Box::new(p))) + } else { + run::prepare(&path, &args, &Document::default(), &watch).map(|p| Work::Mesh(Box::new(p))) + }; + if r.is_ok() { + watch.set(Stage::Done, 1.0); + } + let _ = tx.send(r); + } + }; + let generation = st.jobs.generation; + let cad = crate::ext::cad::is_cad(&path); + st.jobs.list.insert(id, Job { generation, cad, path, args, watch, state: JobState::Running(rx), started: Moment::now(), seconds: None }); + if cfg!(target_arch = "wasm32") { + work(); + } else { + std::thread::Builder::new() + .name(format!("formshot-import-{id}")) + .spawn(work) + .map_err(|e| EngineError::state(format!("the import thread could not start: {e}")))?; + } + Ok(id) +} + +/// Applies every finished job of this engine, oldest first, each as one history step. Nothing is applied while a +/// history group is open, so an import never lands inside someone else's group. +pub(crate) fn pump(engine: &Engine, st: &mut State) { + if st.editor.history().group_depth() > 0 { + return; + } + let mut ready: Vec<(u64, Result<Work>)> = Vec::new(); + for (id, job) in st.jobs.list.iter_mut() { + let JobState::Running(rx) = &job.state else { continue }; + match rx.try_recv() { + Ok(r) => ready.push((*id, r)), + Err(mpsc::TryRecvError::Empty) => {} + Err(mpsc::TryRecvError::Disconnected) => { + ready.push((*id, Err(EngineError::state("the import thread stopped without a result")))); + } + } + } + for (id, r) in ready { + let Some((args, generation)) = st.jobs.list.get(&id).map(|j| (j.args.clone(), j.generation)) else { continue }; + let state = if generation != st.jobs.generation { + JobState::Stale + } else { + let applied = r.and_then(|w| match w { + Work::Mesh(p) => run::apply(engine, st, *p, &args), + Work::Cad(p) => crate::ext::cad::apply(engine, st, *p, &cad_args(&args), args.frame), + }); + match applied { + Ok(mut reply) => { + reply["job"] = json!(id); + JobState::Done(reply) + } + Err(e) if e.code() == "cancelled" => JobState::Cancelled, + Err(e) => JobState::Failed(e), + } + }; + if let Some(j) = st.jobs.list.get_mut(&id) { + j.seconds = Some(j.started.elapsed().as_secs_f64()); + j.state = state; + } + } + prune(&mut st.jobs); +} + +fn prune(jobs: &mut Jobs) { + let finished: Vec<u64> = jobs.list.iter().filter(|(_, j)| !matches!(j.state, JobState::Running(_))).map(|(id, _)| *id).collect(); + if finished.len() > KEEP_FINISHED { + for id in &finished[..finished.len() - KEEP_FINISHED] { + jobs.list.remove(id); + } + } +} + +fn status_json(id: u64, j: &Job) -> Value { + let (state, stage, fraction) = match &j.state { + JobState::Running(_) if j.watch.stage() == Stage::Done => ("running", "waiting", overall_of(j)), + JobState::Running(_) => ("running", j.watch.stage().as_str(), overall_of(j)), + JobState::Done(_) => ("done", "done", 1.0), + JobState::Failed(_) => ("failed", j.watch.stage().as_str(), overall_of(j)), + JobState::Cancelled => ("cancelled", j.watch.stage().as_str(), overall_of(j)), + JobState::Stale => ("stale", j.watch.stage().as_str(), overall_of(j)), + }; + let mut v = json!({ + "job": id, + "state": state, + "stage": stage, + "fraction": crate::util::num(fraction), + "path": j.path.to_string_lossy(), + "seconds": j.seconds.unwrap_or_else(|| j.started.elapsed().as_secs_f64()), + }); + match &j.state { + JobState::Done(r) => v["result"] = r.clone(), + JobState::Failed(e) => v["error"] = json!({"message": e.to_string(), "code": e.code()}), + JobState::Stale => v["error"] = json!({"message": STALE, "code": "stale"}), + _ => {} + } + v +} + +fn unknown(id: u64) -> EngineError { + EngineError::args(format!("no import job {id} in this session")) +} + +/// One job's status, or every job of this engine when `id` is absent. +pub(crate) fn status(st: &State, id: Option<u64>) -> Result<Value> { + let all = &st.jobs.list; + match id { + Some(id) => all.get(&id).map(|j| status_json(id, j)).ok_or_else(|| unknown(id)), + None => Ok(json!({"jobs": all.iter().map(|(id, j)| status_json(*id, j)).collect::<Vec<_>>()})), + } +} + +/// Stops a running job; its result, if it arrives, is dropped and the document stays as it was. +pub(crate) fn cancel(st: &mut State, id: u64) -> Result<Value> { + let j = st.jobs.list.get_mut(&id).ok_or_else(|| unknown(id))?; + let was_running = matches!(j.state, JobState::Running(_)); + if was_running { + j.watch.cancel(); + j.state = JobState::Cancelled; + j.seconds = Some(j.started.elapsed().as_secs_f64()); + } + let mut v = status_json(id, j); + v["ok"] = json!(true); + v["change"] = json!("none"); + v["cancelled"] = json!(was_running); + Ok(v) +} diff --git a/native/crates/fsh-commands/src/ext/import/options.rs b/native/crates/fsh-commands/src/ext/import/options.rs new file mode 100644 index 00000000..ed2e25c0 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/import/options.rs @@ -0,0 +1,179 @@ +use crate::engine::clean_options; +use crate::error::{EngineError, Result}; +use crate::util::{get_bool, get_f32, get_str}; +use fsh_core::LengthUnit; +use fsh_io::{CleanOptions, ImportOptions, UpAxis}; +use serde_json::{json, Map, Value}; + +pub(crate) const UNITS: &[&str] = &["auto", "mm", "cm", "m", "in", "ft"]; +pub(crate) const UP_AXES: &[&str] = &["auto", "y", "z"]; +pub(crate) const CAD_QUALITIES: &[&str] = &["draft", "medium", "high", "ultra"]; + +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum CadQuality { + Preset(String), + Custom { chord: f32, angle: f32 }, +} + +impl CadQuality { + fn parse(v: &Value) -> Result<CadQuality> { + match v { + Value::String(s) if CAD_QUALITIES.contains(&s.as_str()) => Ok(CadQuality::Preset(s.clone())), + Value::Object(_) => { + let need = |k: &str| { + get_f32(v, k)? + .filter(|x| x.is_finite() && *x > 0.0) + .ok_or_else(|| EngineError::args(format!("cad_quality.{k} must be a number above 0"))) + }; + Ok(CadQuality::Custom { chord: need("chord")?, angle: need("angle")? }) + } + _ => Err(EngineError::args("cad_quality must be draft, medium, high, ultra or {chord, angle}")), + } + } + + pub(crate) fn json(&self) -> Value { + match self { + CadQuality::Preset(s) => json!(s), + CadQuality::Custom { chord, angle } => json!({"chord": chord, "angle": angle}), + } + } +} + +/// Everything `file.import`, `import.start` and `file.reimport` read from their arguments. +#[derive(Clone, Debug)] +pub(crate) struct ImportArgs { + pub clean: CleanOptions, + pub place: ImportOptions, + pub merge: bool, + pub cad_quality: Option<CadQuality>, + pub frame: Option<bool>, + pub name: Option<String>, + pub geometry: Map<String, Value>, +} + +const GEOMETRY_KEYS: &[&str] = &["options", "units", "up_axis", "stand_on_floor", "center", "merge", "cad_quality"]; + +fn unit(s: &str) -> Result<Option<LengthUnit>> { + if s == "auto" { + return Ok(None); + } + if !UNITS.contains(&s) { + return Err(EngineError::args(format!("unknown units \"{s}\" (auto, mm, cm, m, in or ft)"))); + } + s.parse::<LengthUnit>().map(Some).map_err(|e| EngineError::args(e.to_string())) +} + +fn up_axis(s: &str) -> Result<Option<UpAxis>> { + if s == "auto" { + return Ok(None); + } + UpAxis::parse(s).map(Some).ok_or_else(|| EngineError::args(format!("unknown up_axis \"{s}\" (auto, y or z)"))) +} + +fn flag(args: &Value, k: &str) -> Result<Option<bool>> { + match args.get(k) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(_) => Err(EngineError::args(format!("{k} must be true or false"))), + } +} + +impl ImportArgs { + /// Reads the options: the original `options` object first, then the top-level ones, which win. + pub(crate) fn parse(args: &Value, frame: Option<bool>) -> Result<ImportArgs> { + let empty = json!({}); + let legacy = args.get("options").filter(|o| o.is_object()).unwrap_or(&empty); + let mut clean = clean_options(legacy)?; + let place = ImportOptions { wrap_in_group: get_bool(legacy, "wrap_in_group").unwrap_or(true), ..ImportOptions::default() }; + if let Some(u) = get_str(args, "units") { + clean.unit = unit(u)?.or(clean.unit); + } + if let Some(a) = get_str(args, "up_axis") { + clean.up_axis = up_axis(a)?.or(clean.up_axis); + } + if let Some(b) = flag(args, "stand_on_floor")? { + clean.stand_on_floor = b; + } + if let Some(b) = flag(args, "center")? { + clean.centre = b; + } + let merge = flag(args, "merge")?.unwrap_or(false); + let cad_quality = match args.get("cad_quality") { + None | Some(Value::Null) => None, + Some(v) => Some(CadQuality::parse(v)?), + }; + Ok(ImportArgs { + clean, + place, + merge, + cad_quality, + frame, + name: get_str(args, "name").filter(|n| !n.is_empty()).map(str::to_string), + geometry: GEOMETRY_KEYS + .iter() + .filter_map(|k| args.get(*k).filter(|v| !v.is_null()).map(|v| ((*k).to_string(), v.clone()))) + .collect(), + }) + } + /// The options as the reply reports them. + pub(crate) fn json(&self) -> Value { + json!({ + "units": self.clean.unit.map(|u| u.as_str()).unwrap_or("auto"), + "up_axis": self.clean.up_axis.map(|a| a.as_str()).unwrap_or("auto"), + "stand_on_floor": self.clean.stand_on_floor, + "center": self.clean.centre, + "merge": self.merge, + "cad_quality": self.cad_quality.as_ref().map(CadQuality::json), + }) + } +} + +fn enum_of(values: &[&str], desc: &str) -> Value { + json!({"type": "string", "enum": values, "description": desc}) +} + +/// Schema properties shared by `file.import` and `import.start`. +pub(crate) fn properties() -> Map<String, Value> { + let mut p = Map::new(); + p.insert("path".into(), json!({"type": "string", "description": "Model file: glb, gltf, obj, stl, ply, 3mf, fbx, or step, stp, iges, igs through the CAD worker"})); + p.insert("name".into(), json!({"type": "string", "description": "Name for the imported group (the original file name)"})); + p.insert("units".into(), enum_of(UNITS, "Unit the file is in; auto takes what the file declares, else a guess from its size")); + p.insert("up_axis".into(), enum_of(UP_AXES, "Axis that points up in the file; auto takes what the file declares, else y")); + p.insert("stand_on_floor".into(), json!({"type": "boolean", "default": true, "description": "Lift the model so its lowest point rests at height 0"})); + p.insert("center".into(), json!({"type": "boolean", "default": false, "description": "Move the model's footprint centre to the origin"})); + p.insert("frame".into(), json!({"type": "boolean", "description": "Frame the camera on the result (default: only when the document had no parts)"})); + p.insert("merge".into(), json!({"type": "boolean", "default": false, "description": "Put everything the file holds under one group"})); + p.insert( + "cad_quality".into(), + json!({ + "description": "Tessellation quality for CAD files (STEP, IGES): a preset or {chord, angle}", + "oneOf": [ + {"type": "string", "enum": CAD_QUALITIES}, + {"type": "object", "properties": { + "chord": {"type": "number", "exclusiveMinimum": 0, "maximum": 0.1, "description": "Largest distance between the surface and its triangles, as a fraction of the model's bounding-box diagonal"}, + "angle": {"type": "number", "minimum": 1, "maximum": 90, "description": "Largest angle between neighbouring triangle normals, in degrees"} + }, "required": ["chord", "angle"]} + ] + }), + ); + p.insert( + "options".into(), + json!({ + "type": "object", + "description": "Clean-up details (the top-level units, up_axis, stand_on_floor and center win over unit, up_axis, stand_on_floor and centre here)", + "properties": { + "unit": {"type": "string", "enum": ["m", "cm", "mm", "in", "ft"], "description": "Unit the file is in"}, + "up_axis": {"type": "string", "enum": ["y", "z", "x", "-y", "-z", "-x"]}, + "smoothing_angle_deg": {"type": "number", "default": 30}, + "weld": {"type": "boolean", "default": true}, + "generate_normals": {"type": "boolean", "default": true}, + "detect_instances": {"type": "boolean", "default": true}, + "stand_on_floor": {"type": "boolean", "default": true}, + "centre": {"type": "boolean", "default": false}, + "wrap_in_group": {"type": "boolean", "default": true} + }, + "required": [] + }), + ); + p +} diff --git a/native/crates/fsh-commands/src/ext/import/probe.rs b/native/crates/fsh-commands/src/ext/import/probe.rs new file mode 100644 index 00000000..c6e85a4f --- /dev/null +++ b/native/crates/fsh-commands/src/ext/import/probe.rs @@ -0,0 +1,57 @@ +use crate::error::{EngineError, Result}; +use crate::util::vec3_json; +use fsh_core::LengthUnit; +use fsh_io::{IoError, RawScene, Siblings, UpAxis, Watch}; +use serde_json::{json, Value}; +use std::path::Path; + +/// The unit an automatic import would apply to a file of this size, as the clean-up pass guesses it. +fn guess_unit(raw: &RawScene) -> LengthUnit { + let d = fsh_io::world_bounds(raw).diagonal().length(); + if !d.is_finite() || d < 0.5 { + LengthUnit::Metre + } else if d < 50.0 { + LengthUnit::Centimetre + } else { + LengthUnit::Millimetre + } +} + +/// Reads a model file and describes it without touching any document. +pub(crate) fn probe(path: &Path) -> Result<Value> { + let bytes = std::fs::read(path).map_err(|e| EngineError::from(IoError::from(e)))?; + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let format = fsh_io::detect_model(file, &bytes).ok_or_else(|| IoError::UnknownFormat(file.to_string()))?; + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("model"); + let mut raw = fsh_io::read_model_bytes(format, &bytes, stem, &Siblings::of(path), &Watch::new())?; + raw.add_nodes_for_loose_meshes(); + let declared = raw.unit.filter(|u| *u != LengthUnit::Unspecified); + let unit = declared.unwrap_or_else(|| guess_unit(&raw)); + let b = fsh_io::world_bounds(&raw); + let bounds = if b.is_empty() { + Value::Null + } else { + let size = b.max - b.min; + json!({"min": vec3_json(b.min), "max": vec3_json(b.max), "size": vec3_json(size), "size_m": vec3_json(size * unit.to_metres_f32())}) + }; + Ok(json!({ + "path": path.to_string_lossy(), + "bytes": bytes.len(), + "name": raw.name, + "format": format.extension(), + "units_declared": declared.map(|u| u.as_str()), + "units_guess": unit.as_str(), + "unit_guessed": declared.is_none(), + "up_axis": raw.up_axis.unwrap_or(UpAxis::Y).as_str(), + "up_axis_declared": raw.up_axis.is_some(), + "bounds": bounds, + "triangles": raw.triangle_count(), + "meshes": raw.meshes.len(), + "nodes": raw.nodes.len(), + "materials": raw.materials.len(), + "textures": raw.textures.len(), + "images_in_file": raw.images.len(), + "texture_slots": raw.extras.iter().map(|x| x.slots.len()).sum::<usize>(), + "warnings": raw.warnings, + })) +} diff --git a/native/crates/fsh-commands/src/ext/import/reimport.rs b/native/crates/fsh-commands/src/ext/import/reimport.rs new file mode 100644 index 00000000..3bd5085e --- /dev/null +++ b/native/crates/fsh-commands/src/ext/import/reimport.rs @@ -0,0 +1,470 @@ +use super::options::ImportArgs; +use super::run; +use super::source; +use crate::engine::{Engine, State}; +use crate::error::{EngineError, Result}; +use fsh_core::{DocKey, MaterialKey, MeshKey, NodeId}; +use fsh_io::Watch; +use fsh_scene::{ + ChangeLevel, Command, Document, Import, ImportMaterial, ImportMesh, ImportNode, ImportPayload, ImportTexture, Mesh, + MeshAdd, Node, NodeKind, Outcome, +}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::path::Path; +use std::sync::Arc; + +/// What one re-read file changed. +#[derive(Default)] +struct FileReport { + matched: usize, + added: usize, + hidden: usize, + updated: usize, + warnings: Vec<String>, + error: Option<EngineError>, + report: Option<Value>, + textures: Option<Value>, + new_textures: bool, +} + +fn same_shape(a: &Mesh, b: &Mesh) -> bool { + a.positions == b.positions && a.indices == b.indices && a.normals == b.normals && a.uvs == b.uvs && a.colours == b.colours +} + +fn part_of(n: &Node) -> Option<(MeshKey, Option<MaterialKey>)> { + match n.kind { + NodeKind::Part { mesh, material } => Some((mesh, material)), + _ => None, + } +} + +/// The import tops to re-read: those of the given nodes and of imported nodes under them, or every import. +fn tops(doc: &Document, nodes: Option<&[NodeId]>) -> Vec<NodeId> { + let candidates: Vec<NodeId> = match nodes { + Some(list) => list.iter().flat_map(|id| doc.subtree(*id)).collect(), + None => doc.nodes().keys().copied().collect(), + }; + let set: BTreeSet<NodeId> = candidates.into_iter().filter_map(|id| source::import_top(doc, id)).collect(); + set.into_iter().collect() +} + +/// The new file's nodes, matched against one import's nodes in the document. +struct Plan { + payload: ImportPayload, + by_new: BTreeMap<NodeId, NodeId>, + matched_doc: BTreeSet<NodeId>, + new_order: Vec<NodeId>, +} + +fn payload_of(cmd: Command) -> Result<ImportPayload> { + match cmd { + Command::Import(i) => Ok(i.payload), + _ => Err(EngineError::state("the reader did not produce an import")), + } +} + +fn plan(doc: &Document, top: NodeId, payload: ImportPayload) -> Result<Plan> { + let top_node = doc.get_node(top)?; + let file = source::source_path(top_node).unwrap_or_default().to_string(); + let pnodes: BTreeMap<NodeId, &Node> = payload.nodes.iter().map(|n| (n.id, &n.node)).collect(); + let tops_new: Vec<NodeId> = payload.nodes.iter().filter(|n| n.node.parent.is_none()).map(|n| n.id).collect(); + let pick = if tops_new.len() == 1 { + tops_new.first().copied() + } else { + tops_new + .iter() + .copied() + .find(|t| source::source_node(pnodes[t]) == source::source_node(top_node)) + .or_else(|| { + let same: Vec<NodeId> = tops_new.iter().copied().filter(|t| pnodes[t].name == source::file_name(top_node)).collect(); + (same.len() == 1).then(|| same[0]) + }) + }; + let Some(ptop) = pick else { + return Err(EngineError::state(format!("{file}: the file no longer has a top node that matches {}", top_node.name))); + }; + let mut inside: BTreeSet<NodeId> = BTreeSet::from([ptop]); + let mut new_order = vec![ptop]; + for n in &payload.nodes { + if n.node.parent.is_some_and(|p| inside.contains(&p)) && inside.insert(n.id) { + new_order.push(n.id); + } + } + let docs: Vec<NodeId> = doc.subtree(top).into_iter().filter(|id| doc.node(*id).and_then(source::source_path) == Some(file.as_str())).collect(); + let is_part = |n: &Node| matches!(n.kind, NodeKind::Part { .. }); + let mut by_new: BTreeMap<NodeId, NodeId> = BTreeMap::from([(ptop, top)]); + let mut matched_doc: BTreeSet<NodeId> = BTreeSet::from([top]); + + let mut by_path: BTreeMap<&str, VecDeque<NodeId>> = BTreeMap::new(); + for id in docs.iter().filter(|id| **id != top) { + by_path.entry(source::source_node(&doc.nodes()[id])).or_default().push_back(*id); + } + for nid in new_order.iter().skip(1) { + let n = pnodes[nid]; + if let Some(q) = by_path.get_mut(source::source_node(n)) { + if let Some(pos) = q.iter().position(|d| is_part(&doc.nodes()[d]) == is_part(n)) { + let d = q.remove(pos).unwrap_or(top); + by_new.insert(*nid, d); + matched_doc.insert(d); + } + } + } + + let free_doc = |matched: &BTreeSet<NodeId>| -> Vec<NodeId> { docs.iter().copied().filter(|d| !matched.contains(d)).collect() }; + let free_new = |by_new: &BTreeMap<NodeId, NodeId>| -> Vec<NodeId> { new_order.iter().copied().filter(|n| !by_new.contains_key(n)).collect() }; + + let (fd, fnew) = (free_doc(&matched_doc), free_new(&by_new)); + let mut doc_names: BTreeMap<(&str, bool), Vec<NodeId>> = BTreeMap::new(); + for d in &fd { + let n = &doc.nodes()[d]; + doc_names.entry((source::file_name(n), is_part(n))).or_default().push(*d); + } + let mut new_names: BTreeMap<(&str, bool), Vec<NodeId>> = BTreeMap::new(); + for nid in &fnew { + let n = pnodes[nid]; + new_names.entry((n.name.as_str(), is_part(n))).or_default().push(*nid); + } + for (k, ns) in &new_names { + if let (1, Some(ds)) = (ns.len(), doc_names.get(k)) { + if ds.len() == 1 { + by_new.insert(ns[0], ds[0]); + matched_doc.insert(ds[0]); + } + } + } + + let meshes: BTreeMap<MeshKey, &Arc<Mesh>> = payload.meshes.iter().map(|m| (m.key, &m.mesh)).collect(); + let (fd, fnew) = (free_doc(&matched_doc), free_new(&by_new)); + let doc_mesh = |d: &NodeId| part_of(&doc.nodes()[d]).and_then(|(m, _)| doc.mesh(m)); + let new_mesh = |n: &NodeId| part_of(pnodes[n]).and_then(|(m, _)| meshes.get(&m).copied()); + for nid in &fnew { + let Some(nm) = new_mesh(nid) else { continue }; + let ds: Vec<NodeId> = fd.iter().copied().filter(|d| !matched_doc.contains(d) && doc_mesh(d).is_some_and(|m| same_shape(m, nm))).collect(); + let twins = fnew.iter().filter(|o| new_mesh(o).is_some_and(|m| same_shape(m, nm))).count(); + if ds.len() == 1 && twins == 1 { + by_new.insert(*nid, ds[0]); + matched_doc.insert(ds[0]); + } + } + Ok(Plan { payload, by_new, matched_doc, new_order }) +} + +fn exec(st: &mut State, cmd: Command, outs: &mut Vec<Outcome>) -> Result<()> { + let out = st.editor.execute(cmd)?; + st.note(&out); + outs.push(out); + Ok(()) +} + +fn dispatch(st: &mut State, name: &str, args: Value, outs: &mut Vec<Outcome>) -> Result<()> { + let out = st.editor.dispatch(name, args)?; + st.note(&out); + outs.push(out); + Ok(()) +} + +/// A sub-payload holding `nodes` (parents first) and the meshes, materials and textures they use; materials found in +/// `reuse` point at document materials instead. +fn subset(p: &ImportPayload, nodes: Vec<ImportNode>, reuse: &BTreeMap<MaterialKey, MaterialKey>) -> ImportPayload { + let mut out = ImportPayload { nodes, ..ImportPayload::default() }; + let mut meshes = BTreeSet::new(); + let mut materials = BTreeSet::new(); + for n in out.nodes.iter_mut() { + if let NodeKind::Part { mesh, material } = &mut n.node.kind { + meshes.insert(*mesh); + if let Some(m) = material { + match reuse.get(m) { + Some(doc_key) => *m = *doc_key, + None => { + materials.insert(*m); + } + } + } + } + } + out.meshes = p.meshes.iter().filter(|m| meshes.contains(&m.key)).cloned().collect(); + out.materials = p.materials.iter().filter(|m| materials.contains(&m.key)).cloned().collect::<Vec<ImportMaterial>>(); + let textures: BTreeSet<_> = out.materials.iter().flat_map(|m| m.material.texture_keys()).collect(); + out.textures = p.textures.iter().filter(|t| textures.contains(&t.key)).cloned().collect::<Vec<ImportTexture>>(); + out +} + +fn index_in_parent(doc: &Document, id: NodeId) -> Option<usize> { + let parent = doc.node(id)?.parent; + doc.children_of(parent).iter().position(|c| *c == id) +} + +/// Replaces a part's mesh by the re-read one in place (`scene.set_part_mesh`): the part keeps its id, place, name, +/// material, transform, children and every other setting, and its old mesh goes when nothing else uses it. +fn replace_mesh(st: &mut State, d: NodeId, mesh: &ImportMesh, outs: &mut Vec<Outcome>) -> Result<NodeId> { + if part_of(st.editor.document().get_node(d)?).is_none() { + return Ok(d); + } + exec(st, Command::MeshAdd(MeshAdd { key: None, mesh: Arc::clone(&mesh.mesh) }), outs)?; + let key = outs.last().and_then(|o| o.created.first().copied()).ok_or_else(|| EngineError::state("mesh.add created no key"))?; + dispatch(st, "scene.set_part_mesh", json!({"id": d.raw(), "mesh": key, "remove_unused": true}), outs)?; + Ok(d) +} + +/// The reader turns a file node holding one mesh into a part, and one holding several into a group of parts. When +/// the document has the group and the file now has the part, the part is split back into a group and its one part +/// (named after the mesh), so the parts match by path. +fn expand_top(p: &mut ImportPayload, i: usize) { + let Some((mesh, material)) = part_of(&p.nodes[i].node) else { return }; + let mesh_name = p.meshes.iter().find(|m| m.key == mesh).map(|m| m.mesh.name.clone()).unwrap_or_else(|| p.nodes[i].node.name.clone()); + let child_id = NodeId::from_raw(run::payload_max_key(p) + 1); + let top = &mut p.nodes[i]; + let mut child = Node::new(mesh_name.clone(), NodeKind::Part { mesh, material }); + child.parent = Some(top.id); + child.metadata = top.node.metadata.clone(); + child.metadata.remove(source::OPTIONS); + child.metadata.insert(source::NODE.to_string(), source::join(source::source_node(&top.node), &mesh_name)); + top.node.kind = NodeKind::Group; + p.nodes.insert(i + 1, ImportNode { id: child_id, node: child }); +} + +/// The other way round: the document has the part and the file now has a group. The part is put under a new group +/// in its place that takes over its transform and its top-node metadata; returns the group. +fn wrap_top(st: &mut State, top: NodeId, top_path: String, outs: &mut Vec<Outcome>) -> Result<NodeId> { + let doc = st.editor.document(); + let old = doc.get_node(top)?.clone(); + if doc.is_locked(top) { + return Err(EngineError::state(format!("{} is locked, and the file now holds a group in its place", old.name))); + } + let mesh_name = part_of(&old).and_then(|(m, _)| doc.mesh(m)).map(|m| m.name.clone()).filter(|n| !n.is_empty()).unwrap_or_else(|| old.name.clone()); + let index = index_in_parent(doc, top); + let transform = serde_json::to_value(old.transform).map_err(|e| EngineError::state(e.to_string()))?; + dispatch(st, "scene.add_group", json!({"name": old.name, "parent": old.parent.map(|p| p.raw()), "index": index, "transform": transform}), outs)?; + let group = outs.last().and_then(|o| o.created.first().copied()).ok_or_else(|| EngineError::state("the group was not made"))?; + let mut meta: Vec<(&str, Value)> = vec![(source::PATH, json!(source::source_path(&old))), (source::NODE, json!(top_path))]; + if let Some(o) = old.metadata.get(source::OPTIONS) { + meta.push((source::OPTIONS, json!(o))); + } + for (k, v) in meta { + dispatch(st, "scene.set_metadata", json!({"id": group, "key": k, "value": v}), outs)?; + } + dispatch(st, "scene.reparent", json!({"ids": [top.raw()], "parent": group, "keep_world": true}), outs)?; + dispatch(st, "scene.set_metadata", json!({"id": top.raw(), "key": source::OPTIONS, "value": null}), outs)?; + dispatch(st, "scene.set_metadata", json!({"id": top.raw(), "key": source::NODE, "value": source::join(&top_path, &mesh_name)}), outs)?; + if old.name == source::file_name(&old) && mesh_name != old.name { + dispatch(st, "scene.rename", json!({"id": top.raw(), "name": mesh_name}), outs)?; + } + Ok(NodeId::from_raw(group)) +} + +fn reread(st: &mut State, top: NodeId, outs: &mut Vec<Outcome>, rep: &mut FileReport) -> Result<()> { + let doc = st.editor.document(); + let top_node = doc.get_node(top)?; + let file = source::source_path(top_node).unwrap_or_default().to_string(); + let stored: Value = top_node.metadata.get(source::OPTIONS).and_then(|s| serde_json::from_str(s).ok()).unwrap_or_else(|| json!({})); + let a = ImportArgs::parse(&stored, Some(false))?; + let mut cad_source = None; + let mut prepared = if crate::ext::cad::is_cad(Path::new(&file)) { + let (cmd, report, source) = crate::ext::cad::reread(Path::new(&file), &stored, doc, top)?; + cad_source = Some(source); + run::Prepared { path: Path::new(&file).to_path_buf(), cmd, report, textures: Default::default() } + } else { + run::prepare(Path::new(&file), &a, doc, &Watch::new())? + }; + rep.warnings.extend(prepared.report.warnings.iter().cloned()); + rep.report = Some(run::report_json(&prepared.report)); + rep.textures = Some(prepared.textures.json()); + let top_is_part = part_of(top_node).is_some(); + rep.new_textures = super::textures::keep(st, &mut prepared.textures.members); + let mut payload = payload_of(prepared.cmd)?; + let new_tops: Vec<usize> = payload.nodes.iter().enumerate().filter(|(_, n)| n.node.parent.is_none()).map(|(i, _)| i).collect(); + let mut top = top; + if let [i] = new_tops[..] { + match (top_is_part, part_of(&payload.nodes[i].node).is_some()) { + (false, true) => expand_top(&mut payload, i), + (true, false) => top = wrap_top(st, top, source::source_node(&payload.nodes[i].node).to_string(), outs)?, + _ => {} + } + } + let doc = st.editor.document(); + let p = plan(doc, top, payload)?; + let pnodes: BTreeMap<NodeId, &ImportNode> = p.payload.nodes.iter().map(|n| (n.id, n)).collect(); + let meshes: BTreeMap<MeshKey, &ImportMesh> = p.payload.meshes.iter().map(|m| (m.key, m)).collect(); + + let mut reuse: BTreeMap<MaterialKey, MaterialKey> = BTreeMap::new(); + let mut renames = Vec::new(); + let mut paths = Vec::new(); + let mut cad_tags = Vec::new(); + let mut swaps = Vec::new(); + let mut returned = Vec::new(); + for (nid, d) in &p.by_new { + let (new, old) = (&pnodes[nid].node, &doc.nodes()[d]); + rep.matched += 1; + if old.metadata.contains_key(source::MISSING) { + returned.push(*d); + } + if old.name == source::file_name(old) && new.name != old.name && *d != top { + renames.push((*d, new.name.clone())); + } + if source::source_node(new) != source::source_node(old) { + paths.push((*d, source::source_node(new).to_string())); + } + for (k, v) in new.metadata.iter().filter(|(k, _)| k.starts_with("cad.") || k.as_str() == "source.cad") { + if old.metadata.get(k) != Some(v) { + cad_tags.push((*d, k.clone(), v.clone())); + } + } + if let (Some((nm, nmat)), Some((om, omat))) = (part_of(new), part_of(old)) { + if let (Some(n), Some(o)) = (nmat, omat) { + reuse.entry(n).or_insert(o); + } + let Some(fresh) = meshes.get(&nm) else { continue }; + if doc.mesh(om).is_some_and(|m| same_shape(m, &fresh.mesh)) { + continue; + } + if doc.is_locked(*d) { + rep.warnings.push(format!("{} kept its old shape: it is locked", old.name)); + } else { + swaps.push((*d, (*fresh).clone())); + } + } + } + let mut added: BTreeMap<Option<NodeId>, Vec<ImportNode>> = BTreeMap::new(); + let mut taken: BTreeSet<NodeId> = BTreeSet::new(); + for nid in &p.new_order { + if p.by_new.contains_key(nid) { + continue; + } + let n = pnodes[nid]; + let Some(parent) = n.node.parent else { continue }; + let mut node = (*n).clone(); + let target = if taken.contains(&parent) { + Some(parent) + } else { + node.node.parent = None; + p.by_new.get(&parent).copied() + }; + let Some(doc_parent) = target else { continue }; + if !taken.contains(&parent) && doc.is_locked(doc_parent) { + rep.warnings.push(format!("{} was not added: {} is locked", n.node.name, doc.nodes()[&doc_parent].name)); + continue; + } + if taken.contains(&parent) { + if let Some(list) = added.values_mut().find(|l| l.iter().any(|x| x.id == parent)) { + list.push(node); + } + } else { + added.entry(Some(doc_parent)).or_default().push(node); + } + taken.insert(*nid); + rep.added += 1; + } + let has_matched_below = |id: NodeId| doc.subtree(id).iter().any(|x| p.matched_doc.contains(x)); + let vanished: Vec<NodeId> = doc + .subtree(top) + .into_iter() + .filter(|id| doc.node(*id).and_then(source::source_path) == Some(file.as_str())) + .filter(|id| !has_matched_below(*id)) + .collect(); + rep.hidden = vanished.iter().filter(|id| !doc.nodes()[*id].metadata.contains_key(source::MISSING)).count(); + let hide: Vec<u64> = vanished.iter().filter(|id| doc.node(**id).is_some_and(|n| n.visible)).map(|id| id.raw()).collect(); + + for (d, name) in renames { + dispatch(st, "scene.rename", json!({"id": d.raw(), "name": name}), outs)?; + } + for (d, path) in paths { + dispatch(st, "scene.set_metadata", json!({"id": d.raw(), "key": source::NODE, "value": path}), outs)?; + } + if let Some(s) = cad_source { + crate::ext::cad::keep_source(st, s); + } + for (d, k, v) in cad_tags { + dispatch(st, "scene.set_metadata", json!({"id": d.raw(), "key": k, "value": v}), outs)?; + } + if !returned.is_empty() { + let ids: Vec<u64> = returned.iter().map(|d| d.raw()).collect(); + dispatch(st, "scene.set_visible", json!({"ids": ids, "visible": true}), outs)?; + for id in ids { + dispatch(st, "scene.set_metadata", json!({"id": id, "key": source::MISSING, "value": null}), outs)?; + } + } + for (d, mesh) in swaps { + replace_mesh(st, d, &mesh, outs)?; + rep.updated += 1; + } + for (parent, nodes) in added { + let payload = subset(&p.payload, nodes, &reuse); + exec(st, Command::Import(Import { parent, payload }), outs)?; + } + if !hide.is_empty() { + dispatch(st, "scene.set_visible", json!({"ids": hide, "visible": false}), outs)?; + for id in &hide { + dispatch(st, "scene.set_metadata", json!({"id": id, "key": source::MISSING, "value": "true"}), outs)?; + } + } + Ok(()) +} + +fn abandon(st: &mut State) { + if let Ok(back) = st.editor.abandon_group() { + st.note(&back); + } +} + +/// `file.reimport`: re-reads the source files of the given nodes (every imported node when none), as one undo step. +pub(crate) fn reimport(engine: &Engine, st: &mut State, nodes: Option<Vec<NodeId>>) -> Result<Value> { + let list = tops(st.editor.document(), nodes.as_deref()); + if list.is_empty() { + return Err(EngineError::state("no imported nodes to re-import (nodes made by an import carry source.path)")); + } + let label = "Re-import"; + st.editor.begin_group(label); + st.note_begin(label); + let mut outs = Vec::new(); + let mut files: Vec<(String, FileReport)> = Vec::new(); + for top in list { + let Some(file) = st.editor.document().node(top).and_then(source::source_path).map(str::to_string) else { continue }; + let mut rep = FileReport::default(); + let before = outs.len(); + if let Err(e) = reread(st, top, &mut outs, &mut rep) { + if outs.len() > before { + abandon(st); + return Err(e); + } + rep = FileReport { error: Some(e), ..FileReport::default() }; + } + files.push((file, rep)); + } + let changed = !outs.is_empty(); + st.editor.end_group()?; + st.note_end(); + if files.iter().any(|(_, r)| r.new_textures) { + super::textures::journal_textures(st); + } + let total = |f: fn(&FileReport) -> usize| files.iter().map(|(_, r)| f(r)).sum::<usize>(); + let files_json: Vec<Value> = files + .iter() + .map(|(path, r)| { + let mut v = json!({"path": path, "matched": r.matched, "added": r.added, "hidden": r.hidden, "updated": r.updated, "warnings": r.warnings}); + if let Some(rp) = &r.report { + v["report"] = rp.clone(); + } + if let Some(t) = &r.textures { + v["textures"] = t.clone(); + } + if let Some(e) = &r.error { + v["error"] = json!({"message": e.to_string(), "code": e.code()}); + } + v + }) + .collect(); + let created: Vec<u64> = outs.iter().filter(|o| o.name == "scene.import").flat_map(|o| o.created.iter().copied()).collect(); + let mut reply = if changed { + engine.changed(st, &Outcome { name: "file.reimport".into(), level: ChangeLevel::Full, created, merged: false, command: None }, false) + } else { + json!({"ok": true, "change": "none", "revision": st.revision}) + }; + reply["name"] = json!("file.reimport"); + reply["matched"] = json!(total(|r| r.matched)); + reply["added"] = json!(total(|r| r.added)); + reply["hidden"] = json!(total(|r| r.hidden)); + reply["updated"] = json!(total(|r| r.updated)); + reply["files"] = json!(files_json); + Ok(reply) +} diff --git a/native/crates/fsh-commands/src/ext/import/run.rs b/native/crates/fsh-commands/src/ext/import/run.rs new file mode 100644 index 00000000..5be5600b --- /dev/null +++ b/native/crates/fsh-commands/src/ext/import/run.rs @@ -0,0 +1,144 @@ +use super::options::ImportArgs; +use super::source; +use super::textures::Embeds; +use crate::engine::{frame_values, has_parts, title_from, Engine, State}; +use crate::error::Result; +use fsh_core::{DocKey, NodeId}; +use fsh_io::{CleanReport, Stage, Watch}; +use fsh_scene::{ChangeLevel, Command, Document, ImportNode, ImportPayload, Node, NodeKind, Outcome}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +/// A model read, cleaned and converted, ready to apply to a document. +pub(crate) struct Prepared { + pub path: PathBuf, + pub cmd: Command, + pub report: CleanReport, + pub textures: Embeds, +} + +/// Reads, cleans and converts `path`; touches no document (`doc` only seeds the payload's keys). +pub(crate) fn prepare(path: &Path, a: &ImportArgs, doc: &Document, watch: &Watch) -> Result<Prepared> { + watch.set(Stage::Reading, 0.0); + let mut raw = fsh_io::read_model(path, watch)?; + let mut report = fsh_io::clean(&mut raw, &a.clean, watch)?; + let folder = std::fs::canonicalize(path).ok().and_then(|p| p.parent().map(Path::to_path_buf)); + let textures = super::textures::embed(&mut raw, folder.as_deref(), watch); + watch.poll(0)?; + report.warnings.extend(textures.warnings.iter().cloned()); + let roots = raw.nodes.iter().filter(|n| n.parent.is_none()).count(); + let mut cmd = fsh_io::to_import_command(&raw, doc, &a.place, watch)?; + let mut whole = Vec::new(); + if let Command::Import(imp) = &cmd { + if a.place.wrap_in_group && roots > 1 { + whole.extend(imp.payload.nodes.first().map(|n| n.id)); + } + } + if a.merge { + whole.extend(merge_under_group(&mut cmd, &raw.name)); + } + let mut kept = a.geometry.clone(); + kept.insert("units".into(), json!(report.unit.as_str())); + kept.insert("up_axis".into(), json!(report.up_axis.as_str())); + source::annotate(&mut cmd, path, &whole, Some(&Value::Object(kept).to_string())); + Ok(Prepared { path: path.to_path_buf(), cmd, report, textures }) +} + +pub(crate) fn payload_max_key(p: &ImportPayload) -> u64 { + let meshes = p.meshes.iter().map(|m| m.key.raw()); + let materials = p.materials.iter().map(|m| m.key.raw()); + let textures = p.textures.iter().map(|t| t.key.raw()); + let nodes = p.nodes.iter().map(|n| n.id.raw()); + meshes.chain(materials).chain(textures).chain(nodes).max().unwrap_or(0) +} + +/// Makes one group hold everything the import adds (a group named after the file when the file has no single +/// top group). +fn merge_under_group(cmd: &mut Command, name: &str) -> Option<NodeId> { + let Command::Import(imp) = cmd else { return None }; + let p = &mut imp.payload; + let tops: Vec<usize> = p.nodes.iter().enumerate().filter(|(_, n)| n.node.parent.is_none()).map(|(i, _)| i).collect(); + if tops.is_empty() || (tops.len() == 1 && matches!(p.nodes[tops[0]].node.kind, NodeKind::Group)) { + return None; + } + let id = NodeId::from_raw(payload_max_key(p) + 1); + for &t in &tops { + p.nodes[t].node.parent = Some(id); + } + p.nodes.insert(0, ImportNode { id, node: Node::new(name, NodeKind::Group) }); + Some(id) +} + +pub(crate) fn report_json(report: &CleanReport) -> Value { + json!({ + "triangles_dropped": report.triangles_dropped, + "vertices_welded": report.vertices_welded, + "unused_vertices_removed": report.unused_vertices_removed, + "meshes_given_normals": report.meshes_given_normals, + "instances_found": report.instances_found, + "unit": report.unit.as_str(), + "unit_guessed": report.unit_guessed, + "up_axis": report.up_axis.as_str(), + "warnings": report.warnings, + }) +} + +/// Applies a prepared import as one history group: the import, the root rename, framing. +pub(crate) fn apply(engine: &Engine, st: &mut State, mut p: Prepared, a: &ImportArgs) -> Result<Value> { + let path = p.path.as_path(); + let textures_json = p.textures.json(); + let new_textures = super::textures::keep(st, &mut p.textures.members); + let was_empty = !has_parts(st.editor.document()); + let label = format!("Import {}", a.name.clone().unwrap_or_else(|| title_from(path))); + st.editor.begin_group(&label); + st.note_begin(&label); + let cmd = p.cmd; + let result = (|| -> Result<Outcome> { + let out = st.editor.execute(cmd)?; + st.note(&out); + if let Some(name) = a.name.as_deref() { + let stem = title_from(Path::new(name)); + let roots: Vec<u64> = out + .created + .iter() + .copied() + .filter(|k| st.editor.document().node(NodeId::from_raw(*k)).is_some_and(|n| n.parent.is_none() && n.name == title_from(path))) + .collect(); + for r in roots { + let renamed = st.editor.dispatch("scene.rename", json!({"id": r, "name": stem}))?; + st.note(&renamed); + } + } + if a.frame.unwrap_or(was_empty) { + if let Ok(values) = frame_values(st.editor.document(), 1.15) { + let index = st.editor.document().active_camera_index(); + let framed = st.editor.dispatch("camera.set", json!({"index": index, "values": values}))?; + st.note(&framed); + } + } + Ok(out) + })(); + let out = match result { + Ok(o) => { + st.editor.end_group()?; + st.note_end(); + o + } + Err(e) => { + if let Ok(back) = st.editor.abandon_group() { + st.note(&back); + } + return Err(e); + } + }; + if new_textures { + super::textures::journal_textures(st); + } + let mut reply = engine.changed(st, &Outcome { level: ChangeLevel::Full, ..out }, false); + reply["name"] = json!("file.import"); + reply["report"] = report_json(&p.report); + reply["textures"] = textures_json; + reply["options"] = a.json(); + reply["source"] = json!(source::absolute(path).to_string_lossy()); + Ok(reply) +} diff --git a/native/crates/fsh-commands/src/ext/import/source.rs b/native/crates/fsh-commands/src/ext/import/source.rs new file mode 100644 index 00000000..1ff8328f --- /dev/null +++ b/native/crates/fsh-commands/src/ext/import/source.rs @@ -0,0 +1,76 @@ +use fsh_core::NodeId; +use fsh_scene::{Command, Document, Node}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// Absolute path of the file a node came from. +pub(crate) const PATH: &str = "source.path"; +/// The node's path inside that file: names from the file's top joined by `/`; empty for a group the import made +/// to hold the whole file. +pub(crate) const NODE: &str = "source.node"; +/// Set on a node a re-import hid because its file no longer has it; cleared when it comes back. +pub(crate) const MISSING: &str = "source.missing"; +/// The geometry options the import used (JSON), kept on the import's top nodes so a re-import reads alike. +pub(crate) const OPTIONS: &str = "source.options"; + +/// The absolute form of `path` (canonical when the file exists). +pub(crate) fn absolute(path: &Path) -> PathBuf { + std::fs::canonicalize(path).unwrap_or_else(|_| std::env::current_dir().map(|d| d.join(path)).unwrap_or_else(|_| path.to_path_buf())) +} + +pub(crate) fn join(parent: &str, name: &str) -> String { + if parent.is_empty() { + name.to_string() + } else { + format!("{parent}/{name}") + } +} + +/// Writes `source.path` and `source.node` on every node of an import payload; `whole` lists the groups that hold +/// the whole file (their path is empty). `options` goes on the top nodes when given. +pub(crate) fn annotate(cmd: &mut Command, path: &Path, whole: &[NodeId], options: Option<&str>) { + let Command::Import(imp) = cmd else { return }; + let file = absolute(path).to_string_lossy().into_owned(); + let mut paths: BTreeMap<NodeId, String> = BTreeMap::new(); + for n in imp.payload.nodes.iter_mut() { + let inside = if whole.contains(&n.id) { + String::new() + } else { + let parent = n.node.parent.and_then(|p| paths.get(&p)).map(String::as_str).unwrap_or(""); + join(parent, &n.node.name) + }; + paths.insert(n.id, inside.clone()); + n.node.metadata.insert(PATH.to_string(), file.clone()); + n.node.metadata.insert(NODE.to_string(), inside); + if let Some(o) = options.filter(|_| n.node.parent.is_none()) { + n.node.metadata.insert(OPTIONS.to_string(), o.to_string()); + } + } +} + +pub(crate) fn source_path(n: &Node) -> Option<&str> { + n.metadata.get(PATH).map(String::as_str) +} + +pub(crate) fn source_node(n: &Node) -> &str { + n.metadata.get(NODE).map(String::as_str).unwrap_or("") +} + +/// The name a node had in its file: the last part of `source.node`. +pub(crate) fn file_name(n: &Node) -> &str { + let p = source_node(n); + p.rsplit('/').next().unwrap_or(p) +} + +/// The top node of the import that made `id`: its highest ancestor from the same file. +pub(crate) fn import_top(doc: &Document, id: NodeId) -> Option<NodeId> { + let file = source_path(doc.node(id)?)?; + let mut top = id; + while let Some(p) = doc.node(top).and_then(|n| n.parent) { + if doc.node(p).and_then(source_path) != Some(file) { + break; + } + top = p; + } + Some(top) +} diff --git a/native/crates/fsh-commands/src/ext/import/textures.rs b/native/crates/fsh-commands/src/ext/import/textures.rs new file mode 100644 index 00000000..0a5cbf28 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/import/textures.rs @@ -0,0 +1,190 @@ +use crate::engine::State; +use fsh_format::{texture_member, EMBED_SCHEME, MAX_EMBED_TEXTURE_BYTES}; +use fsh_io::{RawScene, Watch, EMBEDDED_PREFIX}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::path::Path; + +/// Image bytes an import brings into the project, and what happened to each texture the file names. +#[derive(Default)] +pub(crate) struct Embeds { + pub members: BTreeMap<String, Vec<u8>>, + pub embedded: Vec<Value>, + pub referenced: Vec<Value>, + pub missing: Vec<Value>, + pub skipped: Vec<Value>, + pub warnings: Vec<String>, +} + +impl Embeds { + pub(crate) fn json(&self) -> Value { + json!({ + "embedded": self.embedded, + "referenced": self.referenced, + "missing": self.missing, + "skipped": self.skipped, + "members": self.members.len(), + "bytes": self.members.values().map(Vec::len).sum::<usize>(), + }) + } +} + +/// Adds the members to the project kept beside the document; true when any was new. +pub(crate) fn keep(st: &mut State, members: &mut BTreeMap<String, Vec<u8>>) -> bool { + let mut added = false; + for (name, bytes) in std::mem::take(members) { + if let std::collections::btree_map::Entry::Vacant(v) = st.kept.textures.entry(name) { + v.insert(bytes); + added = true; + } + } + added +} + +/// Hands newly kept textures to the crash journal and writes a snapshot that carries them, so a recovered session +/// holds every member its replayed commands name (recovery gathers textures from origins and snapshots). +pub(crate) fn journal_textures(st: &mut State) { + if st.editor.history().group_depth() > 0 { + return; + } + if let Some(s) = st.journal.as_mut().and_then(|j| j.session.as_mut()) { + s.set_textures(&st.kept.textures); + let _ = s.snapshot(st.editor.document()); + } +} + +/// Picture formats the engine decodes, by content: the member extension. +fn sniff(b: &[u8]) -> Option<&'static str> { + if b.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) { + Some("png") + } else if b.starts_with(&[0xFF, 0xD8, 0xFF]) { + Some("jpg") + } else if b.starts_with(b"#?RADIANCE") || b.starts_with(b"#?RGBE") { + Some("hdr") + } else if b.starts_with(&[0x76, 0x2F, 0x31, 0x01]) { + Some("exr") + } else { + None + } +} + +fn kind_of(b: &[u8]) -> &'static str { + if b.len() >= 12 && &b[..4] == b"RIFF" && &b[8..12] == b"WEBP" { + "WebP" + } else if b.starts_with(&[0xAB, b'K', b'T', b'X', b' ', b'2', b'0']) { + "KTX2" + } else if b.starts_with(b"DDS ") { + "DDS" + } else if b.starts_with(b"GIF8") { + "GIF" + } else if b.starts_with(b"BM") { + "BMP" + } else if b.starts_with(b"II*\0") || b.starts_with(b"MM\0*") { + "TIFF" + } else { + "an unknown format" + } +} + +fn file_name(uri: &str) -> String { + uri.rsplit(['/', '\\']).next().filter(|s| !s.is_empty()).unwrap_or(uri).to_string() +} + +enum Outcome { + Embed(String), + Keep, + Missing(String), + Drop, +} + +/// Where a relative reference that could not be found was expected: inside `folder`, never above it. +fn expected_at(folder: Option<&Path>, uri: &str) -> Option<String> { + let rel = uri.replace('\\', "/"); + let p = Path::new(&rel); + let plain = p.is_relative() && !rel.contains(':') && p.components().all(|c| matches!(c, std::path::Component::Normal(_) | std::path::Component::CurDir)); + plain.then(|| folder.map(|f| f.join(p).to_string_lossy().into_owned())).flatten() +} + +/// Turns every texture of `raw` into an embedded project member (`fshot:textures/<sha256>.<ext>`) where it can: +/// images inside the file and image files beside it that the engine decodes and that hold at most 256 MiB. Larger +/// files keep their path, files that cannot be found keep their reference (made absolute in `folder`, the model's +/// folder, so the slot can be pointed at the file later; the slot shows its fallback meanwhile), and images in +/// formats the engine does not read are dropped with their slots. +pub(crate) fn embed(raw: &mut RawScene, folder: Option<&Path>, watch: &Watch) -> Embeds { + let mut out = Embeds::default(); + let mut done: BTreeMap<String, Outcome> = BTreeMap::new(); + for i in 0..raw.textures.len() { + if watch.is_cancelled() { + break; + } + let uri = raw.textures[i].uri.clone(); + if uri.is_empty() || uri.starts_with(EMBED_SCHEME) { + continue; + } + if !done.contains_key(&uri) { + let outcome = resolve(raw, &uri, folder, &mut out); + done.insert(uri.clone(), outcome); + } + match &done[&uri] { + Outcome::Embed(path) | Outcome::Missing(path) => raw.textures[i].uri = path.clone(), + Outcome::Keep => {} + Outcome::Drop => raw.textures[i].uri = String::new(), + } + } + raw.images.clear(); + out +} + +fn resolve(raw: &RawScene, uri: &str, folder: Option<&Path>, out: &mut Embeds) -> Outcome { + let (name, bytes) = if uri.starts_with(EMBEDDED_PREFIX) { + let Some(img) = raw.image_of(uri) else { + out.skipped.push(json!({"name": uri, "reason": "the image is not in the file"})); + return Outcome::Drop; + }; + if img.bytes.len() > MAX_EMBED_TEXTURE_BYTES { + out.warnings.push(format!("{}: an image inside the file holds more than 256 MiB and was not kept", img.name)); + out.skipped.push(json!({"name": img.name, "reason": "larger than 256 MiB", "bytes": img.bytes.len()})); + return Outcome::Drop; + } + (img.name.clone(), std::borrow::Cow::Borrowed(img.bytes.as_slice())) + } else { + let path = Path::new(uri); + let len = match std::fs::metadata(path) { + Ok(m) if path.is_absolute() && m.is_file() => m.len(), + _ => { + return match expected_at(folder, uri) { + Some(abs) => { + out.missing.push(json!({"name": file_name(uri), "path": abs})); + Outcome::Missing(abs) + } + None => { + out.missing.push(json!({"name": file_name(uri), "path": uri})); + Outcome::Keep + } + }; + } + }; + if len > MAX_EMBED_TEXTURE_BYTES as u64 { + out.warnings.push(format!("{}: larger than 256 MiB, so it is referenced by its path and not kept in the project", file_name(uri))); + out.referenced.push(json!({"name": file_name(uri), "path": uri, "bytes": len})); + return Outcome::Keep; + } + match std::fs::read(path) { + Ok(b) => (file_name(uri), std::borrow::Cow::Owned(b)), + Err(e) => { + out.missing.push(json!({"name": file_name(uri), "path": uri, "reason": e.to_string()})); + return Outcome::Keep; + } + } + }; + let Some(ext) = sniff(&bytes) else { + let kind = kind_of(&bytes); + out.warnings.push(format!("{name}: {kind} images are not read by the engine; the texture was skipped")); + out.skipped.push(json!({"name": name, "reason": format!("{kind} is not a format the engine reads")})); + return Outcome::Drop; + }; + let Some(member) = texture_member(&bytes, ext) else { return Outcome::Drop }; + out.embedded.push(json!({"name": name, "member": member, "bytes": bytes.len(), "format": ext})); + out.members.entry(member.clone()).or_insert_with(|| bytes.into_owned()); + Outcome::Embed(format!("{EMBED_SCHEME}{member}")) +} diff --git a/native/crates/fsh-commands/src/ext/library.rs b/native/crates/fsh-commands/src/ext/library.rs new file mode 100644 index 00000000..2764d53f --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library.rs @@ -0,0 +1,363 @@ +//! The material library: presets, search, thumbnails and drops (0.6.0). + +mod apply; +mod ball; +mod locate; +mod preset; +mod search; +mod sha256; +mod state; +mod store; +mod thumbs; + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::{EngineError, Result}; +use crate::util::{base64, get_bool, get_str, get_u32}; +use fsh_scene::ChangeLevel; +use preset::{procedurals_live, GraphMode, Preset, CATEGORIES}; +use serde_json::{json, Value}; + +const SHELVES: [&str; 4] = ["all", "favorites", "recent", "user"]; + +fn id_arg(what: &str) -> Value { + json!({"type": "string", "minLength": 1, "description": what}) +} + +fn list_args() -> Value { + json!({"type": "object", "properties": { + "category": {"type": "string", "description": "Category name (Metal) or folder (metal), any case"}, + "query": {"type": "string", "description": "Words matched against name, tags, category and type, case- and accent-insensitive; results ranked"}, + "shelf": {"type": "string", "enum": SHELVES, "default": "all", "description": "all, favorites, recent (most recent first) or user (the user's own presets)"}, + "limit": {"type": "integer", "minimum": 1, "description": "At most this many presets"}, + "offset": {"type": "integer", "minimum": 0, "default": 0, "description": "Skip this many presets first"} + }, "additionalProperties": false}) +} + +fn get_args() -> Value { + json!({"type": "object", "properties": {"id": id_arg("Preset id (metal/gold-polished, user/my-red)")}, "required": ["id"], "additionalProperties": false}) +} + +fn favorite_args() -> Value { + json!({"type": "object", "properties": { + "id": id_arg("Preset id"), + "on": {"type": "boolean", "default": true, "description": "true marks it a favourite, false unmarks it"} + }, "required": ["id"], "additionalProperties": false}) +} + +fn no_args() -> Value { + json!({"type": "object", "properties": {}, "additionalProperties": false}) +} + +fn apply_args() -> Value { + json!({"type": "object", "properties": { + "id": id_arg("Preset id"), + "nodes": {"type": "array", "items": {"type": ["integer", "string"]}, "minItems": 1, "description": "Node ids the preset is dropped on (parts or groups)"}, + "scope": {"type": "string", "enum": apply::SCOPES, "default": "part", "description": "part: the parts in the given nodes; group: every part of their parent group; same_material: every part wearing the same material as a given part"} + }, "required": ["id", "nodes"], "additionalProperties": false}) +} + +fn save_args() -> Value { + json!({"type": "object", "properties": { + "material": {"type": "integer", "minimum": 1, "description": "Material key of the document material to save"}, + "name": {"type": "string", "maxLength": 48, "description": "Preset name (the material's name when absent)"}, + "category": {"type": "string", "enum": CATEGORIES.map(|c| c.0), "description": "Library category"} + }, "required": ["material", "category"], "additionalProperties": false}) +} + +fn remove_args() -> Value { + json!({"type": "object", "properties": {"id": id_arg("Id of one of the user's own presets (user/...)")}, "required": ["id"], "additionalProperties": false}) +} + +fn size_arg() -> Value { + json!({"type": "integer", "minimum": thumbs::MIN_SIZE, "maximum": thumbs::MAX_SIZE, "default": thumbs::DEFAULT_SIZE, "description": "Width and height in pixels"}) +} + +fn thumbnail_args() -> Value { + json!({"type": "object", "properties": { + "id": id_arg("Preset id"), + "size": size_arg(), + "wait": {"type": "boolean", "default": false, "description": "Wait for a missing thumbnail to be rendered (otherwise it is queued and the reply says queued)"}, + "timeout": {"type": "integer", "minimum": 1, "maximum": 600, "default": 120, "description": "Seconds to wait at most"}, + "inline": {"type": "boolean", "default": false, "description": "Add the PNG as base64 when it is ready"}, + "retry": {"type": "boolean", "default": false, "description": "Queue again a thumbnail whose render failed"} + }, "required": ["id"], "additionalProperties": false}) +} + +fn thumbnails_args() -> Value { + json!({"type": "object", "properties": { + "ids": {"type": "array", "items": {"type": "string"}, "description": "Preset ids, most wanted first"}, + "size": size_arg() + }, "required": ["ids"], "additionalProperties": false}) +} + +pub(super) static COMMANDS: &[ExtCommand] = &[ + ExtCommand { + name: "library.list", + description: "List material library presets by shelf (all, favorites, recent, user), category and search words, ranked when searching, with category counts and library warnings.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: list_args, + }, + ExtCommand { + name: "library.get", + description: "One library preset: its file, its source and the material applying it would make.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: get_args, + }, + ExtCommand { + name: "library.favorite", + description: "Mark or unmark a library preset as a favourite (kept in the user's library state).", + level: ChangeLevel::None, + mutates: false, + read_only: false, + schema: favorite_args, + }, + ExtCommand { + name: "library.recent", + description: "The library presets applied most recently, newest first.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: no_args, + }, + ExtCommand { + name: "library.apply", + description: "Apply a library preset to parts as one undo step: builds its material (or reuses an identical one) and assigns it to the parts the scope reaches (part, group or same_material).", + level: ChangeLevel::Region, + mutates: true, + read_only: false, + schema: apply_args, + }, + ExtCommand { + name: "library.save", + description: "Save a document material as one of the user's own library presets (user/<slug>).", + level: ChangeLevel::None, + mutates: false, + read_only: false, + schema: save_args, + }, + ExtCommand { + name: "library.remove", + description: "Delete one of the user's own library presets; built-in presets cannot be removed.", + level: ChangeLevel::None, + mutates: false, + read_only: false, + schema: remove_args, + }, + ExtCommand { + name: "library.thumbnail", + description: "A preset's thumbnail (the material ball under the studio, CPU path traced, cached as PNG by preset hash and size); a missing one is queued on a background worker.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: thumbnail_args, + }, + ExtCommand { + name: "library.thumbnails", + description: "Queue the thumbnails of several presets on the background worker, in the order given, and report each one's state.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: thumbnails_args, + }, +]; + +fn lib_err(e: String) -> EngineError { + if e.starts_with("no preset") || e.starts_with("no user preset") { + return EngineError::args(e); + } + EngineError::state(e) +} + +fn id_of(args: &Value) -> Result<&str> { + get_str(args, "id").map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| EngineError::args("needs id (a preset id such as metal/gold-polished)")) +} + +fn list(args: &Value) -> Result<Value> { + let shelf = get_str(args, "shelf").unwrap_or("all"); + if !SHELVES.contains(&shelf) { + return Err(EngineError::args(format!("shelf must be one of {}", SHELVES.join(", ")))); + } + let category = match get_str(args, "category").map(str::trim).filter(|s| !s.is_empty()) { + Some(c) => Some(preset::category(c).ok_or_else(|| EngineError::args(format!("unknown category \"{c}\"")))?.0), + None => None, + }; + let words = search::words(get_str(args, "query").unwrap_or("")); + let limit = get_u32(args, "limit")?.map(|n| n as usize); + let offset = get_u32(args, "offset")?.unwrap_or(0) as usize; + let (lib, presets, warnings) = store::all().map_err(lib_err)?; + let shelves = state::read(); + let fav = |p: &Preset| shelves.favorites.contains(&p.id); + let mut on_shelf: Vec<(Preset, u32)> = match shelf { + "favorites" => presets.into_iter().filter(|p| fav(p)).map(|p| (p, 0)).collect(), + "user" => presets.into_iter().filter(|p| p.user).map(|p| (p, 0)).collect(), + "recent" => shelves.recent.iter().filter_map(|(id, _)| presets.iter().find(|p| p.id == *id).cloned()).map(|p| (p, 0)).collect(), + _ => presets.into_iter().map(|p| (p, 0)).collect(), + }; + if !words.is_empty() { + on_shelf = on_shelf.into_iter().filter_map(|(p, _)| search::score(&p, &words).map(|s| (p, s))).collect(); + on_shelf.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.name.chars().count().cmp(&b.0.name.chars().count()))); + } + let categories: Vec<Value> = CATEGORIES + .iter() + .map(|(name, folder)| json!({"name": name, "folder": folder, "count": on_shelf.iter().filter(|(p, _)| p.category == *name).count()})) + .collect(); + if let Some(c) = category { + on_shelf.retain(|(p, _)| p.category == c); + } + let total = on_shelf.len(); + let page: Vec<Value> = on_shelf + .iter() + .skip(offset) + .take(limit.unwrap_or(usize::MAX)) + .map(|(p, s)| { + let mut e = p.entry(fav(p)); + if !words.is_empty() { + e["score"] = json!(s); + } + e + }) + .collect(); + Ok(json!({ + "root": lib.root.to_string_lossy(), + "origin": lib.origin.as_str(), + "shelf": shelf, + "total": total, + "count": page.len(), + "offset": offset, + "categories": categories, + "presets": page, + "warnings": warnings, + })) +} + +fn get(args: &Value) -> Result<Value> { + let id = id_of(args)?; + let p = store::find(id).map_err(lib_err)?; + let favorite = state::read().favorites.iter().any(|f| f == id); + let material = p.material(GraphMode::Type).map_err(lib_err)?; + let mut notes = Vec::new(); + let graph = if material.graph.is_none() { + "none" + } else if procedurals_live() { + "type" + } else { + notes.push("the type's procedural graph is applied, but the engine's procedural patterns are not built yet, so it renders as a flat colour".to_string()); + "flat" + }; + Ok(json!({ + "entry": p.entry(favorite), + "preset": p.raw, + "source": p.source, + "material": serde_json::to_value(&material).map_err(|e| EngineError::state(e.to_string()))?, + "file": p.file.to_string_lossy(), + "graph": graph, + "notes": notes, + })) +} + +fn favorite(args: &Value) -> Result<Value> { + let id = id_of(args)?; + store::find(id).map_err(lib_err)?; + let on = get_bool(args, "on").unwrap_or(true); + let s = state::set_favorite(id, on).map_err(lib_err)?; + Ok(json!({"id": id, "favorite": on, "favorites": s.favorites})) +} + +fn recent() -> Result<Value> { + let (_, presets, _) = store::all().map_err(lib_err)?; + let s = state::read(); + let list: Vec<Value> = s + .recent + .iter() + .filter_map(|(id, at)| { + let p = presets.iter().find(|p| p.id == *id)?; + let mut e = p.entry(s.favorites.iter().any(|f| f == id)); + e["used_at"] = json!(at); + Some(e) + }) + .collect(); + Ok(json!({"recent": list})) +} + +fn size_of(args: &Value) -> Result<u32> { + let size = get_u32(args, "size")?.unwrap_or(thumbs::DEFAULT_SIZE); + if !(thumbs::MIN_SIZE..=thumbs::MAX_SIZE).contains(&size) { + return Err(EngineError::args(format!("size must be {} to {} pixels", thumbs::MIN_SIZE, thumbs::MAX_SIZE))); + } + Ok(size) +} + +fn thumb_json(p: &Preset, size: u32, status: &thumbs::Status) -> Value { + let mut v = json!({ + "id": p.id, + "size": size, + "sha256": p.sha256, + "path": thumbs::path(&p.sha256, size).map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(), + "state": status.as_str(), + }); + if let thumbs::Status::Failed(e) = status { + v["error"] = json!(e); + } + v +} + +fn thumbnail(args: &Value) -> Result<Value> { + let id = id_of(args)?; + let size = size_of(args)?; + let p = store::find(id).map_err(lib_err)?; + let wait = get_bool(args, "wait").unwrap_or(false); + let mut status = thumbs::request(&p, size, get_bool(args, "retry").unwrap_or(false)).map_err(lib_err)?; + if wait && matches!(status, thumbs::Status::Queued | thumbs::Status::Rendering) { + let limit = get_u32(args, "timeout")?.unwrap_or(120).clamp(1, 600); + status = thumbs::wait(&p, size, std::time::Duration::from_secs(limit as u64)).map_err(lib_err)?; + } + let mut v = thumb_json(&p, size, &status); + if status == thumbs::Status::Ready && get_bool(args, "inline").unwrap_or(false) { + let file = thumbs::path(&p.sha256, size).map_err(lib_err)?; + let bytes = std::fs::read(&file).map_err(|e| EngineError::File(format!("{}: {e}", file.display())))?; + v["png_base64"] = json!(base64(&bytes)); + } + Ok(v) +} + +fn thumbnails(args: &Value) -> Result<Value> { + let size = size_of(args)?; + let ids: Vec<&str> = match args.get("ids") { + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(), + _ => return Err(EngineError::args("needs ids (a list of preset ids)")), + }; + let mut queued = 0; + let mut items = Vec::with_capacity(ids.len()); + for id in ids { + match store::find(id).and_then(|p| thumbs::request(&p, size, false).map(|s| (p, s))) { + Ok((p, s)) => { + if s == thumbs::Status::Queued { + queued += 1; + } + items.push(thumb_json(&p, size, &s)); + } + Err(e) => items.push(json!({"id": id, "size": size, "state": "failed", "error": e})), + } + } + Ok(json!({"size": size, "items": items, "queued": queued})) +} + +pub(super) fn dispatch(engine: &Engine, st: &mut State, name: &str, args: &Value) -> Option<Result<Value>> { + Some(match name { + "library.list" => list(args), + "library.get" => get(args), + "library.favorite" => favorite(args), + "library.recent" => recent(), + "library.apply" => apply::apply(engine, st, args), + "library.save" => apply::save(st, args), + "library.remove" => apply::remove(args), + "library.thumbnail" => thumbnail(args), + "library.thumbnails" => thumbnails(args), + _ => return None, + }) +} diff --git a/native/crates/fsh-commands/src/ext/library/apply.rs b/native/crates/fsh-commands/src/ext/library/apply.rs new file mode 100644 index 00000000..ae292ac6 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/apply.rs @@ -0,0 +1,267 @@ +//! Applying a preset to parts (one undo step), and the user's own presets: save and remove. + +use super::preset::{self, GraphMode, Preset}; +use super::search::fold; +use super::store::{self, USER_PREFIX}; +use super::{lib_err, locate, state}; +use crate::engine::{Engine, State}; +use crate::error::{EngineError, Result}; +use crate::util::{get_str, key_of}; +use fsh_core::{DocKey, MaterialKey, NodeId}; +use fsh_scene::{material_type, ChangeLevel, Command, Document, MaterialAssign, MaterialCreate, Outcome}; +use serde_json::{json, Map, Value}; +use std::collections::BTreeSet; + +/// The scopes `library.apply` takes. +pub(crate) const SCOPES: [&str; 3] = ["part", "group", "same_material"]; + +fn parts_under(doc: &Document, id: NodeId) -> Vec<NodeId> { + doc.subtree(id).into_iter().filter(|n| doc.node(*n).is_some_and(|n| n.mesh().is_some())).collect() +} + +/// The parts a scope reaches from the given nodes, in document order. +fn reach(doc: &Document, nodes: &[NodeId], scope: &str) -> Result<Vec<NodeId>> { + let mut found: BTreeSet<NodeId> = BTreeSet::new(); + for &n in nodes { + let node = doc.node(n).ok_or_else(|| EngineError::args(format!("no node with id {}", n.raw())))?; + match scope { + "group" => match node.parent { + Some(g) => found.extend(parts_under(doc, g)), + None => found.extend(parts_under(doc, n)), + }, + _ => found.extend(parts_under(doc, n)), + } + } + if scope == "same_material" { + let worn: BTreeSet<Option<MaterialKey>> = found.iter().filter_map(|p| doc.node(*p)).map(|n| n.material()).collect(); + found = doc.nodes().iter().filter(|(_, n)| n.mesh().is_some() && worn.contains(&n.material())).map(|(id, _)| *id).collect(); + } + if found.is_empty() { + return Err(EngineError::args("the given nodes contain no parts")); + } + Ok(found.into_iter().collect()) +} + +fn node_ids(args: &Value) -> Result<Vec<NodeId>> { + let raw = args.get("nodes").or_else(|| args.get("ids")); + let list: Vec<u64> = match raw { + Some(Value::Array(a)) => a.iter().map(|v| key_of(v).ok_or_else(|| EngineError::args("nodes must be node ids"))).collect::<Result<_>>()?, + Some(v) => vec![key_of(v).ok_or_else(|| EngineError::args("nodes must be node ids"))?], + None => return Err(EngineError::args("needs nodes (the node ids to apply the preset to)")), + }; + if list.is_empty() { + return Err(EngineError::args("nodes is empty")); + } + Ok(list.into_iter().map(NodeId::from_raw).collect()) +} + +/// `library.apply`: builds the preset's material (or reuses an identical one) and assigns it, as one undo step. +pub(crate) fn apply(engine: &Engine, st: &mut State, args: &Value) -> Result<Value> { + let id = super::id_of(args)?; + let scope = get_str(args, "scope").unwrap_or("part"); + if !SCOPES.contains(&scope) { + return Err(EngineError::args(format!("scope must be one of {}", SCOPES.join(", ")))); + } + let nodes = node_ids(args)?; + let p = store::find(id).map_err(lib_err)?; + let material = p.material(GraphMode::Type).map_err(lib_err)?; + let parts = reach(st.editor.document(), &nodes, scope)?; + let existing = st.editor.document().materials().iter().find(|(_, m)| **m == material).map(|(k, _)| *k); + let label = format!("Apply {}", p.name); + st.editor.begin_group(&label); + st.note_begin(&label); + let result = (|| -> Result<(MaterialKey, Outcome)> { + let key = match existing { + Some(k) => k, + None => { + let out = st.editor.execute(Command::MaterialCreate(MaterialCreate { key: None, material: Box::new(material), type_id: None, name: None }))?; + st.note(&out); + MaterialKey(*out.created.first().ok_or_else(|| EngineError::state("material.create made no material"))?) + } + }; + let out = st.editor.execute(Command::MaterialAssign(MaterialAssign { ids: parts.clone(), material: Some(key) }))?; + st.note(&out); + Ok((key, out)) + })(); + let (key, out) = match result { + Ok(done) => { + st.editor.end_group()?; + st.note_end(); + done + } + Err(e) => { + if let Ok(back) = st.editor.abandon_group() { + st.note(&back); + } + return Err(e); + } + }; + let mut reply = engine.changed(st, &Outcome { name: "library.apply".into(), level: ChangeLevel::Region, ..out }, false); + reply["id"] = json!(p.id); + reply["material"] = json!(key.raw()); + reply["reused"] = json!(existing.is_some()); + reply["parts"] = json!(parts.iter().map(|n| n.raw()).collect::<Vec<_>>()); + reply["scope"] = json!(scope); + if let Err(e) = state::touch_recent(&p.id) { + reply["warnings"] = json!([e]); + } + Ok(reply) +} + +fn round4(x: f64) -> f64 { + (x * 1e4).round() / 1e4 +} + +fn rounded(v: &Value) -> Value { + match v { + Value::Number(n) => n.as_f64().map(|x| json!(round4(x))).unwrap_or_else(|| v.clone()), + Value::Array(a) => Value::Array(a.iter().map(rounded).collect()), + _ => v.clone(), + } +} + +/// A slug from a display name: folded to ASCII words joined by `-`, at most 40 characters. +fn slugify(name: &str) -> String { + let mut s = String::new(); + for w in fold(name).split_whitespace() { + let w: String = w.chars().filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit()).collect(); + if w.is_empty() { + continue; + } + if !s.is_empty() && s.len() + 1 + w.len() > 40 { + break; + } + if !s.is_empty() { + s.push('-'); + } + s.push_str(&w[..w.len().min(40)]); + } + if s.is_empty() { + "preset".into() + } else { + s + } +} + +fn taken(slug: &str) -> bool { + let Some(root) = store::user_materials() else { return false }; + preset::CATEGORIES.iter().any(|(_, f)| root.join(f).join(format!("{slug}.json")).exists()) +} + +fn text(v: &Value) -> String { + match v { + Value::Array(a) => format!("[{}]", a.iter().map(text).collect::<Vec<_>>().join(", ")), + _ => serde_json::to_string(v).unwrap_or_else(|_| "null".into()), + } +} + +const SOURCE_KEYS: [&str; 5] = ["kind", "reference", "urls", "notes", "authored"]; + +/// The preset file text, keys in the format's order, two-space indent, newline at the end. +fn preset_text(fields: &[(&str, Value)], params: &Map<String, Value>) -> String { + let mut out = String::from("{\n"); + for (i, (k, v)) in fields.iter().enumerate() { + out.push_str(&format!(" \"{k}\": ")); + if *k == "params" { + if params.is_empty() { + out.push_str("{}"); + } else { + out.push_str("{\n"); + let lines: Vec<String> = params.iter().map(|(pk, pv)| format!(" \"{pk}\": {}", text(pv))).collect(); + out.push_str(&lines.join(",\n")); + out.push_str("\n }"); + } + } else if *k == "source" { + let lines: Vec<String> = SOURCE_KEYS.iter().filter_map(|sk| v.get(*sk).map(|sv| format!(" \"{sk}\": {}", text(sv)))).collect(); + out.push_str("{\n"); + out.push_str(&lines.join(",\n")); + out.push_str("\n }"); + } else { + out.push_str(&text(v)); + } + out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" }); + } + out.push_str("}\n"); + out +} + +/// `library.save`: writes a document material as one of the user's presets. +pub(crate) fn save(st: &State, args: &Value) -> Result<Value> { + let raw = args.get("material").or_else(|| args.get("key")).and_then(key_of).ok_or_else(|| EngineError::args("needs material (a material key)"))?; + let m = st.editor.document().material(MaterialKey(raw)).ok_or_else(|| EngineError::args(format!("no material with key {raw}")))?; + let name = get_str(args, "name").map(str::trim).filter(|s| !s.is_empty()).unwrap_or(m.name.as_str()).to_string(); + if name.chars().count() > 48 { + return Err(EngineError::args("name is longer than 48 characters")); + } + let cat = get_str(args, "category").ok_or_else(|| EngineError::args("needs category (Metal, Plastic, ...)"))?; + let (category, folder, _) = preset::category(cat).ok_or_else(|| EngineError::args(format!("unknown category \"{cat}\"")))?; + let t = material_type(&m.type_id).or_else(|| material_type("generic")).ok_or_else(|| EngineError::state("no generic material type"))?; + let now = serde_json::to_value(m.params).map_err(|e| EngineError::state(e.to_string()))?; + let defaults = serde_json::to_value(t.params).map_err(|e| EngineError::state(e.to_string()))?; + let mut params = Map::new(); + for (k, v) in now.as_object().into_iter().flatten() { + if defaults.get(k) != Some(v) { + params.insert(k.clone(), rounded(v)); + } + } + let base = slugify(&name); + let mut slug = base.clone(); + let mut n = 2; + while taken(&slug) { + slug = format!("{base}-{n}"); + n += 1; + } + let id = format!("{USER_PREFIX}{slug}"); + let mut notes = Vec::new(); + if !m.slots.is_empty() || !m.textures.is_empty() { + notes.push("texture slots and textures are not part of a preset file and were left out".to_string()); + } + if m.graph.is_some() { + notes.push("the material's node graph is not stored; applying the preset starts from its type's graph".to_string()); + } + let mut tags: Vec<String> = Vec::new(); + if t.graph.is_some() { + tags.push("needs-graph".into()); + } + let authored: Vec<String> = params.keys().cloned().collect(); + let fields = [ + ("format", json!(preset::FORMAT)), + ("version", json!(preset::VERSION)), + ("id", json!(id)), + ("name", json!(name)), + ("category", json!(category)), + ("type", json!(t.id)), + ("params", Value::Null), + ("tags", json!(tags)), + ("source", json!({"kind": "authored", "reference": "", "urls": [], "notes": format!("Saved from the material \"{}\" of a FormShot document.", m.name), "authored": authored})), + ("licence", json!("NOASSERTION")), + ]; + let body = preset_text(&fields, ¶ms); + let dir = store::user_materials().ok_or_else(|| EngineError::state("no user data folder (set FORMSHOT_USER_DATA)"))?.join(folder); + let file = dir.join(format!("{slug}.json")); + preset::parse(body.as_bytes(), &id, folder, file.clone(), true).map_err(lib_err)?; + locate::write_atomic(&file, body.as_bytes()).map_err(|e| EngineError::File(format!("the preset {} could not be written: {e}", file.display())))?; + let p: Preset = store::find(&id).map_err(lib_err)?; + Ok(json!({"id": id, "entry": p.entry(false), "file": file.to_string_lossy(), "notes": notes})) +} + +/// `library.remove`: deletes one of the user's presets (built-ins are refused). +pub(crate) fn remove(args: &Value) -> Result<Value> { + let id = super::id_of(args)?; + if !id.starts_with(USER_PREFIX) { + return Err(EngineError::args(format!("{id} is a built-in preset; only the user's own presets (user/...) can be removed"))); + } + let slug = &id[USER_PREFIX.len()..]; + let root = store::user_materials().ok_or_else(|| EngineError::state("no user data folder (set FORMSHOT_USER_DATA)"))?; + let file = preset::CATEGORIES + .iter() + .map(|(_, f)| root.join(f).join(format!("{slug}.json"))) + .find(|p| preset::valid_slug(slug) && p.is_file()) + .ok_or_else(|| EngineError::args(format!("no user preset \"{slug}\"")))?; + std::fs::remove_file(&file).map_err(|e| EngineError::File(format!("the preset {} could not be removed: {e}", file.display())))?; + let mut reply = json!({"id": id, "removed": true}); + if let Err(e) = state::forget(id) { + reply["warnings"] = json!([e]); + } + Ok(reply) +} diff --git a/native/crates/fsh-commands/src/ext/library/ball.rs b/native/crates/fsh-commands/src/ext/library/ball.rs new file mode 100644 index 00000000..15ba6849 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/ball.rs @@ -0,0 +1,138 @@ +//! FormShot's material ball: a sphere with an inset band, tilted, on a turned pedestal. Lathe meshes with smooth +//! normals, creased walls and UVs (u around, v along the profile), about 21k triangles in all. + +use fsh_core::{Quat, Vec2, Vec3}; +use fsh_scene::Mesh; +use std::f32::consts::{PI, TAU}; + +/// Ball radius in metres. +pub(crate) const RADIUS: f32 = 0.5; +/// Height of the ball's centre above the floor. +pub(crate) const CENTRE_Y: f32 = 0.63; +const COLUMNS: usize = 160; +const BAND: (f32, f32) = (1.22, 1.46); +const BAND_DEPTH: f32 = 0.035; +const TILT: f32 = 0.42; +const TURN: f32 = -0.5; + +/// One ring of a lathe profile: radius and height, the profile normal (radial, axial), and v. +#[derive(Clone, Copy)] +struct Ring { + r: f32, + y: f32, + nr: f32, + ny: f32, + v: f32, +} + +fn sphere_ring(phi: f32, radius: f32, v: f32) -> Ring { + Ring { r: radius * phi.sin(), y: radius * phi.cos(), nr: phi.sin(), ny: phi.cos(), v } +} + +fn arc(from: f32, to: f32, steps: usize, radius: f32, v0: f32, v1: f32) -> Vec<Ring> { + (0..=steps) + .map(|i| { + let t = i as f32 / steps as f32; + sphere_ring(from + (to - from) * t, radius, v0 + (v1 - v0) * t) + }) + .collect() +} + +/// Profile strips of the ball: cap, upper wall, groove, lower wall, bottom. Each strip is meshed on its own, so the +/// walls keep hard edges. +fn ball_strips() -> Vec<Vec<Ring>> { + let (a, b) = BAND; + let inner = RADIUS - BAND_DEPTH; + let va = a / PI; + let vb = b / PI; + let wall = |phi: f32, sign: f32, v: f32| { + let (n_r, n_y) = (sign * phi.cos(), -sign * phi.sin()); + vec![ + Ring { r: RADIUS * phi.sin(), y: RADIUS * phi.cos(), nr: n_r, ny: n_y, v }, + Ring { r: inner * phi.sin(), y: inner * phi.cos(), nr: n_r, ny: n_y, v: v + 0.004 * sign }, + ] + }; + vec![ + arc(0.0, a, 38, RADIUS, 0.0, va), + wall(a, 1.0, va), + arc(a, b, 8, inner, va + 0.004, vb - 0.004), + wall(b, -1.0, vb), + arc(b, PI, 48, RADIUS, vb, 1.0), + ] +} + +fn pedestal_strips() -> Vec<Vec<Ring>> { + let top = CENTRE_Y - RADIUS + 0.03; + let neck = 0.17; + let foot = 0.36; + let mut flank = Vec::new(); + for i in 0..=10 { + let t = i as f32 / 10.0; + let r = foot - 0.02 + (neck - foot + 0.02) * (t * t * (3.0 - 2.0 * t)); + let y = 0.05 + (top - 0.05) * t; + let dr = -(foot - 0.02 - neck) * 6.0 * t * (1.0 - t); + let dy = top - 0.05; + let len = (dr * dr + dy * dy).sqrt().max(1e-6); + flank.push(Ring { r, y, nr: dy / len, ny: -dr / len, v: 0.2 + 0.6 * t }); + } + vec![ + vec![Ring { r: 0.0, y: 0.0, nr: 0.0, ny: -1.0, v: 0.0 }, Ring { r: foot, y: 0.0, nr: 0.0, ny: -1.0, v: 0.1 }], + vec![Ring { r: foot, y: 0.0, nr: 1.0, ny: 0.0, v: 0.1 }, Ring { r: foot, y: 0.035, nr: 1.0, ny: 0.0, v: 0.14 }], + vec![Ring { r: foot, y: 0.035, nr: 0.0, ny: 1.0, v: 0.14 }, Ring { r: foot - 0.02, y: 0.05, nr: 0.0, ny: 1.0, v: 0.2 }], + flank, + vec![Ring { r: neck, y: top, nr: 0.0, ny: 1.0, v: 0.8 }, Ring { r: 0.0, y: top, nr: 0.0, ny: 1.0, v: 1.0 }], + ] +} + +fn lathe(name: &str, strips: &[Vec<Ring>], place: impl Fn(Vec3) -> Vec3) -> Mesh { + let mut positions = Vec::new(); + let mut normals = Vec::new(); + let mut uvs = Vec::new(); + let mut indices = Vec::new(); + for strip in strips { + let base = positions.len() as u32; + for ring in strip { + for c in 0..=COLUMNS { + let u = c as f32 / COLUMNS as f32; + let (s, co) = (u * TAU).sin_cos(); + positions.push(place(Vec3::new(ring.r * co, ring.y, ring.r * s))); + normals.push(place(Vec3::new(ring.nr * co, ring.ny, ring.nr * s)) - place(Vec3::ZERO)); + uvs.push(Vec2::new(u, 1.0 - ring.v)); + } + } + let row = (COLUMNS + 1) as u32; + for k in 0..strip.len().saturating_sub(1) { + for c in 0..COLUMNS as u32 { + let a = base + k as u32 * row + c; + let (b, d, e) = (a + 1, a + row, a + row + 1); + for tri in [[a, d, b], [b, d, e]] { + let [p0, p1, p2] = tri.map(|i| positions[i as usize]); + let n = (p1 - p0).cross(p2 - p0); + if n.length() < 1e-12 { + continue; + } + let avg = normals[tri[0] as usize] + normals[tri[1] as usize] + normals[tri[2] as usize]; + if n.dot(avg) < 0.0 { + indices.extend_from_slice(&[tri[0], tri[2], tri[1]]); + } else { + indices.extend_from_slice(&tri); + } + } + } + } + } + let normals = normals.into_iter().map(|n| n.normalize()).collect(); + let mut m = Mesh::new(name, positions, indices).unwrap_or_default(); + m.normals = normals; + m.uvs = vec![uvs]; + let _ = m.validate(); + m +} + +/// The ball (wears the preset) and the pedestal (neutral), in metres, standing on y = 0. +pub(crate) fn meshes() -> (Mesh, Mesh) { + let spin = Quat::from_axis_angle(Vec3::Y, TURN) * Quat::from_axis_angle(Vec3::X, TILT); + let ball = lathe("Material ball", &ball_strips(), |p| spin.rotate(p) + Vec3::new(0.0, CENTRE_Y, 0.0)); + let pedestal = lathe("Pedestal", &pedestal_strips(), |p| p); + (ball, pedestal) +} diff --git a/native/crates/fsh-commands/src/ext/library/locate.rs b/native/crates/fsh-commands/src/ext/library/locate.rs new file mode 100644 index 00000000..a709fcd1 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/locate.rs @@ -0,0 +1,146 @@ +//! Where the library lives: the built-in presets, the user's own presets and state, the thumbnail cache. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Environment variable naming the library root (the folder holding `materials/index.json`). +pub(crate) const LIBRARY_ENV: &str = "FORMSHOT_LIBRARY"; +/// Environment variable replacing the platform's user data folder. +pub(crate) const USER_DATA_ENV: &str = "FORMSHOT_USER_DATA"; +/// Environment variable replacing the platform's user cache folder (shared with the CAD worker cache). +pub(crate) const CACHE_ENV: &str = "FORMSHOT_CACHE"; +const PRODUCT: &str = "FormShot"; +const INDEX: &str = "index.json"; + +/// How the root was found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Origin { + Env, + Bundle, + Development, +} + +impl Origin { + pub(crate) fn as_str(self) -> &'static str { + match self { + Origin::Env => "env", + Origin::Bundle => "bundle", + Origin::Development => "development", + } + } +} + +fn var(k: &str) -> Option<PathBuf> { + std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from) +} + +fn home() -> Option<PathBuf> { + var("HOME").or_else(|| var("USERPROFILE")) +} + +fn has_index(root: &Path) -> bool { + root.join("materials").join(INDEX).is_file() +} + +/// Places the desktop bundle puts resources, relative to the running program (Tauri's resource folder on each +/// platform: `Contents/Resources` on macOS, beside the program on Windows, `lib/<product>` on Linux and AppImage). +fn bundle_places(exe_dir: &Path) -> Vec<PathBuf> { + let mut places = vec![ + exe_dir.join("..").join("Resources").join("library"), + exe_dir.join("library"), + exe_dir.join("resources").join("library"), + exe_dir.join("..").join("lib").join(PRODUCT).join("library"), + exe_dir.join("..").join("lib").join(PRODUCT.to_lowercase()).join("library"), + ]; + if let Some(appdir) = var("APPDIR") { + places.push(appdir.join("usr").join("lib").join(PRODUCT).join("library")); + } + places.push(PathBuf::from("/usr/lib").join(PRODUCT).join("library")); + places +} + +/// The library root: `FORMSHOT_LIBRARY`, then the app's bundled resources, then `assets/library` in a folder above +/// the running program (development builds). The error names every place looked at. +pub(crate) fn root() -> Result<(PathBuf, Origin), String> { + if let Some(p) = var(LIBRARY_ENV) { + if has_index(&p) { + return Ok((p, Origin::Env)); + } + return Err(format!("{LIBRARY_ENV} names {}, which holds no materials/{INDEX}", p.display())); + } + let exe = std::env::current_exe().ok().map(|e| e.canonicalize().unwrap_or(e)); + let Some(dir) = exe.as_deref().and_then(Path::parent) else { + return Err(format!("no material library: {LIBRARY_ENV} is not set and the running program's folder is unknown")); + }; + if let Some(p) = bundle_places(dir).into_iter().find(|p| has_index(p)) { + return Ok((p.canonicalize().unwrap_or(p), Origin::Bundle)); + } + for up in dir.ancestors() { + let p = up.join("assets").join("library"); + if has_index(&p) { + return Ok((p, Origin::Development)); + } + } + Err(format!( + "no material library: {LIBRARY_ENV} is not set, the app bundle holds none beside {} and no assets/library was found above it", + dir.display() + )) +} + +/// The platform's user data folder (`FORMSHOT_USER_DATA` replaces it): `%APPDATA%` on Windows, +/// `~/Library/Application Support` on macOS, `$XDG_DATA_HOME` or `~/.local/share` elsewhere. +pub(crate) fn user_data_dir() -> Option<PathBuf> { + if let Some(p) = var(USER_DATA_ENV) { + return Some(p); + } + if cfg!(windows) { + return var("APPDATA").or_else(|| home().map(|h| h.join("AppData").join("Roaming"))); + } + if cfg!(target_os = "macos") { + return home().map(|h| h.join("Library").join("Application Support")); + } + var("XDG_DATA_HOME").filter(|p| p.is_absolute()).or_else(|| home().map(|h| h.join(".local").join("share"))) +} + +/// The platform's user cache folder, by the same rules as the CAD worker cache (`FORMSHOT_CACHE` replaces it). +pub(crate) fn cache_dir() -> Option<PathBuf> { + if let Some(p) = var(CACHE_ENV) { + return Some(p); + } + if cfg!(windows) { + return var("LOCALAPPDATA").or_else(|| home().map(|h| h.join("AppData").join("Local"))); + } + if cfg!(target_os = "macos") { + return home().map(|h| h.join("Library").join("Caches")); + } + var("XDG_CACHE_HOME").filter(|p| p.is_absolute()).or_else(|| home().map(|h| h.join(".cache"))) +} + +/// `<user data>/formshot/library`: the user's presets (`materials/<folder>/`) and `state.json`. +pub(crate) fn user_library() -> Option<PathBuf> { + user_data_dir().map(|d| d.join("formshot").join("library")) +} + +/// `<user cache>/formshot/library/thumbs`. +pub(crate) fn thumbs_dir() -> Option<PathBuf> { + cache_dir().map(|d| d.join("formshot").join("library").join("thumbs")) +} + +/// Writes a file through a temporary sibling and a rename, so readers never see half a file. +pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file"); + static SERIAL: AtomicU64 = AtomicU64::new(0); + let n = SERIAL.fetch_add(1, Ordering::Relaxed); + let tmp = path.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id())); + std::fs::write(&tmp, bytes)?; + match std::fs::rename(&tmp, path) { + Ok(()) => Ok(()), + Err(e) => { + let _ = std::fs::remove_file(&tmp); + Err(e) + } + } +} diff --git a/native/crates/fsh-commands/src/ext/library/preset.rs b/native/crates/fsh-commands/src/ext/library/preset.rs new file mode 100644 index 00000000..93d905a2 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/preset.rs @@ -0,0 +1,315 @@ +//! One preset file (format 1 of LIBRARY_FORMAT.md): strict reading, and the material it builds. + +use super::sha256; +use fsh_core::Rgb; +use fsh_scene::{material_type, GraphNode, GraphOp, Material, MaterialGraph, MaterialInput, MathOp, SocketValue, SurfaceParams}; +use serde_json::{json, Map, Value}; +use std::path::PathBuf; + +pub(crate) const FORMAT: &str = "formshot-material-preset"; +pub(crate) const VERSION: u64 = 1; +const KEYS: [&str; 10] = ["format", "version", "id", "name", "category", "type", "params", "tags", "source", "licence"]; +const MAX_SLUG: usize = 48; +const MAX_TAGS: usize = 8; + +/// The window's twelve categories, in its order, with their folder names. +pub(crate) const CATEGORIES: [(&str, &str); 12] = [ + ("Metal", "metal"), + ("Plastic", "plastic"), + ("Glass", "glass"), + ("Paint", "paint"), + ("Rubber", "rubber"), + ("Fabric", "fabric"), + ("Wood", "wood"), + ("Stone", "stone"), + ("Ceramic", "ceramic"), + ("Liquid", "liquid"), + ("Gem", "gem"), + ("Emissive", "emissive"), +]; + +/// The category of a name or folder, any case: `(name, folder, order)`. +pub(crate) fn category(s: &str) -> Option<(&'static str, &'static str, usize)> { + let s = s.trim(); + CATEGORIES + .iter() + .enumerate() + .find(|(_, (n, f))| n.eq_ignore_ascii_case(s) || f.eq_ignore_ascii_case(s)) + .map(|(i, (n, f))| (*n, *f, i)) +} + +/// True for `[a-z0-9]+(-[a-z0-9]+)*` of at most 48 characters. +pub(crate) fn valid_slug(s: &str) -> bool { + !s.is_empty() + && s.len() <= MAX_SLUG + && !s.starts_with('-') + && !s.ends_with('-') + && !s.contains("--") + && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +/// A preset as read from its file. +#[derive(Clone, Debug)] +pub(crate) struct Preset { + pub id: String, + pub name: String, + pub category: &'static str, + pub folder: &'static str, + pub order: usize, + pub type_id: String, + pub params: Map<String, Value>, + pub tags: Vec<String>, + pub source: Value, + pub raw: Value, + pub sha256: String, + pub file: PathBuf, + pub user: bool, +} + +/// `SurfaceParams` field names with the JSON kind of each (`n` number, `b` bool, `c` colour). +pub(crate) fn param_fields() -> Vec<(String, char)> { + let Ok(Value::Object(m)) = serde_json::to_value(SurfaceParams::default()) else { return Vec::new() }; + m.into_iter() + .map(|(k, v)| { + let kind = match v { + Value::Bool(_) => 'b', + Value::Array(_) => 'c', + _ => 'n', + }; + (k, kind) + }) + .collect() +} + +fn check_params(id: &str, params: &Map<String, Value>) -> Result<(), String> { + let fields = param_fields(); + for (k, v) in params { + let Some((_, kind)) = fields.iter().find(|(f, _)| f == k) else { + return Err(format!("preset {id}: unknown params key \"{k}\" (not a SurfaceParams field)")); + }; + let ok = match kind { + 'b' => v.is_boolean(), + 'c' => v.as_array().is_some_and(|a| a.len() == 3 && a.iter().all(|x| x.as_f64().is_some_and(f64::is_finite))), + _ => v.as_f64().is_some_and(f64::is_finite), + }; + if !ok { + let want = match kind { + 'b' => "true or false", + 'c' => "an [r, g, b] array of numbers", + _ => "a number", + }; + return Err(format!("preset {id}: params.{k} must be {want}")); + } + } + Ok(()) +} + +/// The surface parameters a preset builds: `SurfaceParams::default()`, the type's defaults, then `params`. +pub(crate) fn build_params(id: &str, type_id: &str, params: &Map<String, Value>) -> Result<SurfaceParams, String> { + let t = material_type(type_id).ok_or_else(|| format!("preset {id}: unknown material type \"{type_id}\""))?; + let mut base = serde_json::to_value(t.params).map_err(|e| e.to_string())?; + if let Value::Object(b) = &mut base { + for (k, v) in params { + b.insert(k.clone(), v.clone()); + } + } + let p: SurfaceParams = serde_json::from_value(base).map_err(|e| format!("preset {id}: params: {e}"))?; + p.validate().map_err(|e| format!("preset {id}: {e}"))?; + Ok(p) +} + +fn string(id: &str, v: &Value, k: &str) -> Result<String, String> { + v.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| format!("preset {id}: \"{k}\" must be a string")) +} + +/// Reads a preset strictly. `expect_id` is the id its place gives it, `folder` the category folder it lies in. +pub(crate) fn parse(bytes: &[u8], expect_id: &str, folder: &str, file: PathBuf, user: bool) -> Result<Preset, String> { + let id = expect_id; + let raw: Value = serde_json::from_slice(bytes).map_err(|e| format!("preset {id}: not JSON: {e}"))?; + let Value::Object(obj) = &raw else { return Err(format!("preset {id}: not a JSON object")) }; + if let Some(k) = obj.keys().find(|k| !KEYS.contains(&k.as_str())) { + return Err(format!("preset {id}: unknown key \"{k}\"")); + } + if raw.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err(format!("preset {id}: \"format\" must be \"{FORMAT}\"")); + } + match raw.get("version").and_then(Value::as_u64) { + Some(VERSION) => {} + Some(v) => return Err(format!("preset {id}: format version {v} is not known (this engine reads {VERSION})")), + None => return Err(format!("preset {id}: \"version\" must be an integer")), + } + let own = string(id, &raw, "id")?; + if own != id { + return Err(format!("preset {id}: its id \"{own}\" does not match its place")); + } + let slug = id.rsplit('/').next().unwrap_or(""); + if !valid_slug(slug) { + return Err(format!("preset {id}: \"{slug}\" is not a valid slug")); + } + let name = string(id, &raw, "name")?; + if name.trim().is_empty() { + return Err(format!("preset {id}: empty name")); + } + let cat = string(id, &raw, "category")?; + let (category, cat_folder, order) = category(&cat).filter(|c| c.0 == cat).ok_or_else(|| format!("preset {id}: unknown category \"{cat}\""))?; + if cat_folder != folder { + return Err(format!("preset {id}: category {category} does not belong in folder {folder}")); + } + let type_id = string(id, &raw, "type")?; + let Some(Value::Object(params)) = raw.get("params") else { return Err(format!("preset {id}: \"params\" must be an object")) }; + check_params(id, params)?; + build_params(id, &type_id, params)?; + let tags = match raw.get("tags") { + Some(Value::Array(a)) if a.len() <= MAX_TAGS && a.iter().all(Value::is_string) => { + a.iter().filter_map(Value::as_str).map(str::to_string).collect() + } + _ => return Err(format!("preset {id}: \"tags\" must be at most {MAX_TAGS} strings")), + }; + let source = match raw.get("source") { + Some(s @ Value::Object(_)) => s.clone(), + _ => return Err(format!("preset {id}: \"source\" must be an object")), + }; + string(id, &raw, "licence")?; + Ok(Preset { + id: id.to_string(), + name, + category, + folder: cat_folder, + order, + type_id, + params: params.clone(), + tags, + source, + sha256: sha256::hex(bytes), + raw, + file, + user, + }) +} + +/// Whether the procedural patterns are in the engine yet (the wave 1 stub answers one constant everywhere). +pub(crate) fn procedurals_live() -> bool { + use fsh_scene::fsh_materials::{procedural, ProcKind}; + let at = |x: f32| { + let mut args = vec![[0.0f32; 4]; 8]; + args[0] = [x, 0.37 * x, 0.11, 0.0]; + args[1] = [1.0, 0.0, 0.0, 0.0]; + args[2] = [20.0, 0.0, 0.0, 0.0]; + args[3] = [0.5, 0.0, 0.0, 0.0]; + args[4] = [0.45, 0.28, 0.14, 0.0]; + args[5] = [0.2, 0.1, 0.05, 0.0]; + procedural(ProcKind::Wood, 0, &args) + }; + [0.013f32, 0.29, 0.61].iter().any(|x| at(*x) != at(0.83)) +} + +/// How a preset's graph is handled when building its material. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GraphMode { + /// The type's preset graph, its colour and finish inputs taken from the preset. + Type, + /// No graph: the preset's average tone and finish as constants. + Flat, +} + +fn scaled(c: Rgb, f: f32) -> [f32; 3] { + [(c.r * f).clamp(0.0, 1.0), (c.g * f).clamp(0.0, 1.0), (c.b * f).clamp(0.0, 1.0)] +} + +/// Fits the type's preset graph to a preset: wood and marble colours around the preset's average tone (light 1.3x, +/// dark 0.55x for wood; base 1.08x, vein 0.45x for marble), the flake tint around its base colour (1x between flakes, +/// 1.5x on them) and the flake lerps around its roughness and metalness. +fn tune(graph: &mut MaterialGraph, p: &SurfaceParams) { + let outputs: Vec<(MaterialInput, u32)> = graph.outputs.iter().map(|(i, s)| (*i, s.0)).collect(); + for (input, node) in outputs { + let Some(n) = graph.nodes.get_mut(&node) else { continue }; + match (&n.op, input) { + (GraphOp::Wood { .. }, MaterialInput::BaseColor) => { + n.inputs.insert("colour1".into(), SocketValue::Colour(scaled(p.base_color, 1.3))); + n.inputs.insert("colour2".into(), SocketValue::Colour(scaled(p.base_color, 0.55))); + } + (GraphOp::Marble { .. }, MaterialInput::BaseColor) => { + n.inputs.insert("colour1".into(), SocketValue::Colour(scaled(p.base_color, 1.08))); + n.inputs.insert("colour2".into(), SocketValue::Colour(scaled(p.base_color, 0.45))); + } + (GraphOp::Mix {}, MaterialInput::BaseColor) => { + n.inputs.insert("a".into(), SocketValue::Colour(scaled(p.base_color, 1.0))); + n.inputs.insert("b".into(), SocketValue::Colour(scaled(p.base_color, 1.5))); + } + (GraphOp::Math { op: MathOp::Lerp }, MaterialInput::SpecularRoughness) => { + let r = p.specular_roughness; + n.inputs.insert("a".into(), SocketValue::Float(r)); + n.inputs.insert("b".into(), SocketValue::Float(r * 0.35)); + } + (GraphOp::Math { op: MathOp::Lerp }, MaterialInput::BaseMetalness) => { + let m = p.base_metalness; + n.inputs.insert("a".into(), SocketValue::Float((m * 0.8).clamp(0.0, 1.0))); + n.inputs.insert("b".into(), SocketValue::Float((m * 1.3).clamp(0.0, 1.0))); + } + _ => {} + } + } +} + +/// The graph of a stone without veins (granite, concrete, limestone, sandstone, travertine, slate), which the stone +/// type's marble graph would draw with marble veins: granite as 4 mm grains (cell colours from 0.35x to 1.5x the +/// preset's tone), the others as a fine mottle (fractal noise from 0.8x to 1.2x, 15 features per metre). +fn granular_stone(id: &str, p: &SurfaceParams) -> MaterialGraph { + let mut g = MaterialGraph::new(); + let granite = id.contains("granite"); + let (pattern, out, lo, hi) = if granite { + let n = GraphNode::new(GraphOp::Voronoi { seed: 0, metric: Default::default(), feature: Default::default() }).with("scale", SocketValue::Float(250.0)); + (g.add(n), "colour", 0.35, 1.5) + } else { + let n = GraphNode::new(GraphOp::Fbm { seed: 0 }).with("scale", SocketValue::Float(15.0)).with("octaves", SocketValue::Float(6.0)); + (g.add(n), "value", 0.8, 1.2) + }; + let mix = g.add(GraphNode::new(GraphOp::Mix {}).with("a", SocketValue::Colour(scaled(p.base_color, lo))).with("b", SocketValue::Colour(scaled(p.base_color, hi)))); + g.link(pattern, out, mix, "factor"); + g.output(MaterialInput::BaseColor, mix, "result"); + g.nodes.entry(mix).and_modify(|n| n.position = [240.0, 0.0]); + g +} + +impl Preset { + /// True when the look depends on the type's graph (`needs-graph` tag or a type with a preset graph). + pub(crate) fn needs_graph(&self) -> bool { + self.tags.iter().any(|t| t == "needs-graph") || material_type(&self.type_id).is_some_and(|t| t.graph.is_some()) + } + + /// The surface parameters (type defaults, then `params`). + pub(crate) fn params(&self) -> Result<SurfaceParams, String> { + build_params(&self.id, &self.type_id, &self.params) + } + + /// The material applying this preset makes, named after it. + pub(crate) fn material(&self, mode: GraphMode) -> Result<Material, String> { + let params = self.params()?; + let mut m = Material::new(self.name.clone(), self.type_id.clone(), params); + if mode == GraphMode::Type { + if let Some(mut g) = material_type(&self.type_id).and_then(|t| t.graph.clone()) { + tune(&mut g, ¶ms); + if self.type_id == "stone" && !self.id.contains("marble") { + g = granular_stone(&self.id, ¶ms); + } + m.graph = Some(Box::new(g)); + } + } + Ok(m) + } + + /// The summary entry the list, recent and get replies carry. + pub(crate) fn entry(&self, favorite: bool) -> Value { + json!({ + "id": self.id, + "name": self.name, + "category": self.category, + "type": self.type_id, + "tags": self.tags, + "sha256": self.sha256, + "user": self.user, + "favorite": favorite, + "needs_graph": self.needs_graph(), + }) + } +} diff --git a/native/crates/fsh-commands/src/ext/library/search.rs b/native/crates/fsh-commands/src/ext/library/search.rs new file mode 100644 index 00000000..9c1b2778 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/search.rs @@ -0,0 +1,80 @@ +//! Library search: case- and accent-insensitive word matching over name, tags, category and type, ranked. + +use super::preset::Preset; + +const FOLDS: &[(char, &str)] = &[ + ('à', "a"), ('á', "a"), ('â', "a"), ('ã', "a"), ('ä', "a"), ('å', "a"), ('ā', "a"), ('ă', "a"), ('ą', "a"), + ('æ', "ae"), ('ç', "c"), ('ć', "c"), ('č', "c"), ('ď', "d"), ('đ', "d"), ('è', "e"), ('é', "e"), ('ê', "e"), + ('ë', "e"), ('ē', "e"), ('ė', "e"), ('ę', "e"), ('ě', "e"), ('ğ', "g"), ('ì', "i"), ('í', "i"), ('î', "i"), + ('ï', "i"), ('ī', "i"), ('į', "i"), ('ı', "i"), ('ł', "l"), ('ľ', "l"), ('ñ', "n"), ('ń', "n"), ('ň', "n"), + ('ò', "o"), ('ó', "o"), ('ô', "o"), ('õ', "o"), ('ö', "o"), ('ø', "o"), ('ō', "o"), ('ő', "o"), ('œ', "oe"), + ('ŕ', "r"), ('ř', "r"), ('ś', "s"), ('š', "s"), ('ş', "s"), ('ß', "ss"), ('ť', "t"), ('ţ', "t"), ('ù', "u"), + ('ú', "u"), ('û', "u"), ('ü', "u"), ('ū', "u"), ('ů', "u"), ('ű', "u"), ('ý', "y"), ('ÿ', "y"), ('ź', "z"), + ('ż', "z"), ('ž', "z"), ('þ', "th"), ('ð', "d"), +]; + +/// Lower case without accents; everything that is not a letter or digit becomes a space. +pub(crate) fn fold(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars().flat_map(char::to_lowercase) { + if let Some((_, r)) = FOLDS.iter().find(|(k, _)| *k == c) { + out.push_str(r); + } else if ('\u{300}'..='\u{36f}').contains(&c) { + continue; + } else if c.is_alphanumeric() { + out.push(c); + } else { + out.push(' '); + } + } + out +} + +/// The words of a query, folded. +pub(crate) fn words(query: &str) -> Vec<String> { + fold(query).split_whitespace().map(str::to_string).collect() +} + +fn word_score(w: &str, name: &str, name_words: &[&str], tags: &[String], category: &str, type_id: &str) -> u32 { + let mut s = 0; + if name.starts_with(w) { + s = s.max(100); + } + if name_words.contains(&w) { + s = s.max(80); + } else if name_words.iter().any(|n| n.starts_with(w)) { + s = s.max(60); + } else if name.contains(w) { + s = s.max(30); + } + if tags.iter().any(|t| t.split_whitespace().any(|p| p == w)) { + s = s.max(45); + } else if tags.iter().any(|t| t.split_whitespace().any(|p| p.starts_with(w))) { + s = s.max(25); + } + if category == w || type_id.split_whitespace().any(|p| p == w) { + s = s.max(40); + } else if category.starts_with(w) || type_id.split_whitespace().any(|p| p.starts_with(w)) { + s = s.max(20); + } + s +} + +/// The rank of a preset for the query words, or `None` when a word matches nothing. +pub(crate) fn score(p: &Preset, words: &[String]) -> Option<u32> { + let name = fold(&p.name); + let name_words: Vec<&str> = name.split_whitespace().collect(); + let name_joined = name_words.join(" "); + let tags: Vec<String> = p.tags.iter().map(|t| fold(t)).collect(); + let category = fold(p.category); + let type_id = fold(&p.type_id); + let mut total = 0; + for w in words { + let s = word_score(w, &name_joined, &name_words, &tags, &category, &type_id); + if s == 0 { + return None; + } + total += s; + } + Some(total) +} diff --git a/native/crates/fsh-commands/src/ext/library/sha256.rs b/native/crates/fsh-commands/src/ext/library/sha256.rs new file mode 100644 index 00000000..a4856d01 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/sha256.rs @@ -0,0 +1,72 @@ +//! SHA-256 (FIPS 180-4), for preset hashes and thumbnail cache keys. + +const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, + 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, + 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +const H0: [u32; 8] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; + +fn block(h: &mut [u32; 8], chunk: &[u8; 64]) { + let mut w = [0u32; 64]; + for (i, word) in chunk.as_chunks::<4>().0.iter().enumerate() { + w[i] = u32::from_be_bytes(*word); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = *h; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ (!e & g); + let t1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(maj); + hh = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + for (x, y) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { + *x = x.wrapping_add(y); + } +} + +/// The digest of `data` as 32 bytes. +pub(crate) fn digest(data: &[u8]) -> [u8; 32] { + let mut h = H0; + let (chunks, rest) = data.as_chunks::<64>(); + for c in chunks { + block(&mut h, c); + } + let mut tail = [0u8; 128]; + tail[..rest.len()].copy_from_slice(rest); + tail[rest.len()] = 0x80; + let n = if rest.len() < 56 { 64 } else { 128 }; + tail[n - 8..n].copy_from_slice(&((data.len() as u64) * 8).to_be_bytes()); + for c in tail[..n].as_chunks::<64>().0 { + block(&mut h, c); + } + let mut out = [0u8; 32]; + for (o, v) in out.as_chunks_mut::<4>().0.iter_mut().zip(h) { + *o = v.to_be_bytes(); + } + out +} + +/// The digest of `data` as 64 lower-case hex digits. +pub(crate) fn hex(data: &[u8]) -> String { + digest(data).iter().map(|b| format!("{b:02x}")).collect() +} diff --git a/native/crates/fsh-commands/src/ext/library/state.rs b/native/crates/fsh-commands/src/ext/library/state.rs new file mode 100644 index 00000000..1c9e4315 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/state.rs @@ -0,0 +1,113 @@ +//! Favourites and recently applied presets, kept in `<user data>/formshot/library/state.json`. + +use super::locate; +use serde_json::{json, Value}; +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::{SystemTime, UNIX_EPOCH}; + +const FORMAT: &str = "formshot-library-state"; +/// Most entries the recent list keeps. +pub(crate) const RECENT_MAX: usize = 24; +const FAVORITES_MAX: usize = 4096; + +static LOCK: Mutex<()> = Mutex::new(()); + +/// The stored state. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Shelves { + pub favorites: Vec<String>, + pub recent: Vec<(String, u64)>, +} + +fn path() -> Option<PathBuf> { + locate::user_library().map(|d| d.join("state.json")) +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +fn read_unlocked() -> Shelves { + let Some(p) = path() else { return Shelves::default() }; + let Ok(v) = std::fs::read(&p).map_err(|_| ()).and_then(|b| serde_json::from_slice::<Value>(&b).map_err(|_| ())) else { + return Shelves::default(); + }; + let favorites = v + .get("favorites") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + let recent = v + .get("recent") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|e| Some((e.get("id")?.as_str()?.to_string(), e.get("at").and_then(Value::as_u64).unwrap_or(0)))) + .take(RECENT_MAX) + .collect() + }) + .unwrap_or_default(); + Shelves { favorites, recent } +} + +fn write_unlocked(s: &Shelves) -> Result<(), String> { + let p = path().ok_or("no user data folder (set FORMSHOT_USER_DATA)")?; + let v = json!({ + "format": FORMAT, + "version": 1, + "favorites": s.favorites, + "recent": s.recent.iter().map(|(id, at)| json!({"id": id, "at": at})).collect::<Vec<_>>(), + }); + let mut text = serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?; + text.push('\n'); + locate::write_atomic(&p, text.as_bytes()).map_err(|e| format!("the library state {} could not be written: {e}", p.display())) +} + +/// The current state (read from disk each time, so several engine processes agree). +pub(crate) fn read() -> Shelves { + let _g = LOCK.lock().unwrap_or_else(|p| p.into_inner()); + read_unlocked() +} + +fn update(f: impl FnOnce(&mut Shelves)) -> Result<Shelves, String> { + let _g = LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let mut s = read_unlocked(); + let before = s.clone(); + f(&mut s); + if s != before { + write_unlocked(&s)?; + } + Ok(s) +} + +/// Marks or unmarks a favourite. +pub(crate) fn set_favorite(id: &str, on: bool) -> Result<Shelves, String> { + update(|s| { + s.favorites.retain(|f| f != id); + if on { + s.favorites.push(id.to_string()); + if s.favorites.len() > FAVORITES_MAX { + s.favorites.remove(0); + } + } + }) +} + +/// Puts an id at the front of the recent list. +pub(crate) fn touch_recent(id: &str) -> Result<Shelves, String> { + let at = now(); + update(|s| { + s.recent.retain(|(r, _)| r != id); + s.recent.insert(0, (id.to_string(), at)); + s.recent.truncate(RECENT_MAX); + }) +} + +/// Forgets an id everywhere (after a user preset is removed). +pub(crate) fn forget(id: &str) -> Result<Shelves, String> { + update(|s| { + s.favorites.retain(|f| f != id); + s.recent.retain(|(r, _)| r != id); + }) +} diff --git a/native/crates/fsh-commands/src/ext/library/store.rs b/native/crates/fsh-commands/src/ext/library/store.rs new file mode 100644 index 00000000..f7cac49a --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/store.rs @@ -0,0 +1,183 @@ +//! The built-in library (index plus preset files, checked against each other) and the user's own presets. + +use super::locate::{self, Origin}; +use super::preset::{self, Preset, CATEGORIES}; +use super::sha256; +use serde_json::Value; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::SystemTime; + +const INDEX_FORMAT: &str = "formshot-material-index"; +/// Id prefix of the user's own presets. +pub(crate) const USER_PREFIX: &str = "user/"; + +/// The built-in presets in index order, with what was wrong with the library. +#[derive(Debug)] +pub(crate) struct Library { + pub root: PathBuf, + pub origin: Origin, + pub presets: Vec<Preset>, + pub warnings: Vec<String>, + stamp: Option<SystemTime>, +} + +fn index_stamp(root: &Path) -> Option<SystemTime> { + std::fs::metadata(root.join("materials").join("index.json")).and_then(|m| m.modified()).ok() +} + +fn load(root: PathBuf, origin: Origin) -> Library { + let stamp = index_stamp(&root); + let mut lib = Library { root, origin, presets: Vec::new(), warnings: Vec::new(), stamp }; + let materials = lib.root.join("materials"); + let index: Value = match std::fs::read(materials.join("index.json")).map_err(|e| e.to_string()).and_then(|b| serde_json::from_slice(&b).map_err(|e| e.to_string())) { + Ok(v) => v, + Err(e) => { + lib.warnings.push(format!("the library index {} could not be read: {e}", materials.join("index.json").display())); + return lib; + } + }; + if index.get("format").and_then(Value::as_str) != Some(INDEX_FORMAT) || index.get("version").and_then(Value::as_u64) != Some(1) { + lib.warnings.push(format!("the library index is not a {INDEX_FORMAT} of version 1")); + return lib; + } + let listed = index.get("presets").and_then(Value::as_array).cloned().unwrap_or_default(); + for e in &listed { + let id = e.get("id").and_then(Value::as_str).unwrap_or(""); + let file = e.get("file").and_then(Value::as_str).unwrap_or(""); + let want = e.get("sha256").and_then(Value::as_str).unwrap_or(""); + let folder = file.split('/').next().unwrap_or(""); + if id.is_empty() || file.is_empty() || file.contains("..") || format!("{id}.json") != file { + lib.warnings.push(format!("index entry {id:?}: its file {file:?} does not match its id")); + continue; + } + let path = materials.join(file); + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(_) => { + lib.warnings.push(format!("preset {id}: its file {file} is missing")); + continue; + } + }; + let got = sha256::hex(&bytes); + if !want.eq_ignore_ascii_case(&got) { + lib.warnings.push(format!("preset {id}: the file's SHA-256 {got} differs from the index ({want})")); + } + match preset::parse(&bytes, id, folder, path, false) { + Ok(p) => { + let indexed = [("name", p.name.as_str()), ("category", p.category), ("type", p.type_id.as_str())]; + for (k, v) in indexed { + if e.get(k).and_then(Value::as_str) != Some(v) { + lib.warnings.push(format!("preset {id}: the index gives a different {k}")); + } + } + lib.presets.push(p); + } + Err(msg) => lib.warnings.push(msg), + } + } + for (_, folder) in CATEGORIES { + let Ok(entries) = std::fs::read_dir(materials.join(folder)) else { continue }; + let mut unlisted: Vec<String> = entries + .flatten() + .filter_map(|e| e.file_name().to_str().and_then(|n| n.strip_suffix(".json")).map(|s| format!("{folder}/{s}"))) + .filter(|id| !listed.iter().any(|e| e.get("id").and_then(Value::as_str) == Some(id.as_str()))) + .collect(); + unlisted.sort(); + for id in unlisted { + lib.warnings.push(format!("preset {id}: its file is not in the index, so it is not offered")); + } + } + if let Some(n) = index.get("count").and_then(Value::as_u64) { + if n as usize != listed.len() { + lib.warnings.push(format!("the index says {n} presets but lists {}", listed.len())); + } + } + lib +} + +/// The built-in library, read once and again whenever its root or its index changes. +pub(crate) fn library() -> Result<Arc<Library>, String> { + static CACHE: Mutex<Option<Arc<Library>>> = Mutex::new(None); + let (root, origin) = locate::root()?; + let mut cache = CACHE.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(lib) = cache.as_ref() { + if lib.root == root && lib.stamp == index_stamp(&root) { + return Ok(Arc::clone(lib)); + } + } + let lib = Arc::new(load(root, origin)); + *cache = Some(Arc::clone(&lib)); + Ok(lib) +} + +/// `<user data>/formshot/library/materials`. +pub(crate) fn user_materials() -> Option<PathBuf> { + locate::user_library().map(|d| d.join("materials")) +} + +/// The user's own presets (`user/<slug>`), category order then name, with problems found while reading them. +pub(crate) fn user_presets() -> (Vec<Preset>, Vec<String>) { + let mut out = Vec::new(); + let mut warnings = Vec::new(); + let Some(root) = user_materials() else { return (out, warnings) }; + for (_, folder) in CATEGORIES { + let Ok(entries) = std::fs::read_dir(root.join(folder)) else { continue }; + for e in entries.flatten() { + let path = e.path(); + let Some(slug) = path.file_name().and_then(|n| n.to_str()).and_then(|n| n.strip_suffix(".json")) else { continue }; + if slug.starts_with('.') { + continue; + } + let id = format!("{USER_PREFIX}{slug}"); + match std::fs::read(&path).map_err(|e| format!("preset {id}: {e}")).and_then(|b| preset::parse(&b, &id, folder, path.clone(), true)) { + Ok(p) => out.push(p), + Err(m) => warnings.push(m), + } + } + } + out.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name)).then_with(|| a.id.cmp(&b.id))); + (out, warnings) +} + +/// The built-in library, every preset and every warning, as `all` answers them. +pub(crate) type Everything = (Arc<Library>, Vec<Preset>, Vec<String>); + +/// Every preset (built-ins in index order, the user's after the built-ins of their category) and all warnings. +pub(crate) fn all() -> Result<Everything, String> { + let lib = library()?; + let (user, user_warnings) = user_presets(); + let mut presets: Vec<Preset> = Vec::with_capacity(lib.presets.len() + user.len()); + for (i, _) in CATEGORIES.iter().enumerate() { + presets.extend(lib.presets.iter().filter(|p| p.order == i).cloned()); + presets.extend(user.iter().filter(|p| p.order == i).cloned()); + } + let mut warnings = lib.warnings.clone(); + warnings.extend(user_warnings); + Ok((lib, presets, warnings)) +} + +/// One preset by id, read fresh from its file (so a corrupted file is reported, not served from memory). +pub(crate) fn find(id: &str) -> Result<Preset, String> { + let id = id.trim(); + if let Some(slug) = id.strip_prefix(USER_PREFIX) { + let (user, warnings) = user_presets(); + if let Some(p) = user.into_iter().find(|p| p.id == id) { + return Ok(p); + } + if let Some(w) = warnings.into_iter().find(|w| w.starts_with(&format!("preset {id}:"))) { + return Err(w); + } + return Err(format!("no user preset \"{slug}\"")); + } + let lib = library()?; + let Some(p) = lib.presets.iter().find(|p| p.id == id) else { + let said: Vec<&str> = lib.warnings.iter().filter(|w| w.starts_with(&format!("preset {id}:"))).map(String::as_str).collect(); + if !said.is_empty() { + return Err(said.join("; ")); + } + return Err(format!("no preset \"{id}\" in the library")); + }; + let bytes = std::fs::read(&p.file).map_err(|_| format!("preset {id}: its file {} is missing", p.file.display()))?; + preset::parse(&bytes, id, p.folder, p.file.clone(), false) +} diff --git a/native/crates/fsh-commands/src/ext/library/thumbs.rs b/native/crates/fsh-commands/src/ext/library/thumbs.rs new file mode 100644 index 00000000..00691b4f --- /dev/null +++ b/native/crates/fsh-commands/src/ext/library/thumbs.rs @@ -0,0 +1,253 @@ +//! Preset thumbnails: the material ball under the built-in studio, rendered by the CPU tracer on a background +//! worker (never the live render), cached as `<user cache>/formshot/library/thumbs/<preset sha256>-<size>.png`. + +use super::ball; +use super::locate; +use super::preset::{procedurals_live, GraphMode, Preset}; +use fsh_core::{Transform, Vec3}; +use fsh_render_cpu::Renderer; +use fsh_scene::{flatten, Command, Document, Editor, Material, MeshAdd, SurfaceParams, Trs}; +use serde_json::{json, Value}; +use std::collections::{HashMap, VecDeque}; +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +/// Smallest and largest thumbnail side in pixels, and the default. +pub(crate) const MIN_SIZE: u32 = 64; +pub(crate) const MAX_SIZE: u32 = 512; +pub(crate) const DEFAULT_SIZE: u32 = 128; +/// Samples per pixel of every thumbnail (then the denoiser). +pub(crate) const SAMPLES: u32 = 48; +const BOUNCES: u32 = 10; +const MARKER: &str = ".look"; +const EMITTER_LEVEL: f32 = 1.5; + +/// Where a thumbnail is, or is being made. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Status { + Ready, + Queued, + Rendering, + Failed(String), +} + +impl Status { + pub(crate) fn as_str(&self) -> &'static str { + match self { + Status::Ready => "ready", + Status::Queued => "queued", + Status::Rendering => "rendering", + Status::Failed(_) => "failed", + } + } +} + +type Key = (String, u32); + +struct Job { + key: Key, + preset: Preset, +} + +#[derive(Default)] +struct Queue { + jobs: VecDeque<Job>, + states: HashMap<Key, Status>, + worker: bool, +} + +fn queue() -> &'static (Mutex<Queue>, Condvar) { + static Q: OnceLock<(Mutex<Queue>, Condvar)> = OnceLock::new(); + Q.get_or_init(|| (Mutex::new(Queue::default()), Condvar::new())) +} + +/// What the cached pictures were made with; when it changes (the procedurals arrive) the old pictures are dropped. +fn look() -> &'static str { + if procedurals_live() { + "ball-4 graph" + } else { + "ball-4 flat" + } +} + +/// The cache folder, emptied of pictures made with another look the first time it is asked for. +pub(crate) fn dir() -> Result<PathBuf, String> { + static CHECKED: OnceLock<()> = OnceLock::new(); + let d = locate::thumbs_dir().ok_or("no user cache folder (set FORMSHOT_CACHE)")?; + CHECKED.get_or_init(|| { + let marker = d.join(MARKER); + if std::fs::read_to_string(&marker).ok().as_deref() != Some(look()) { + if let Ok(entries) = std::fs::read_dir(&d) { + for e in entries.flatten() { + if e.path().extension().is_some_and(|x| x == "png") { + let _ = std::fs::remove_file(e.path()); + } + } + } + let _ = locate::write_atomic(&marker, look().as_bytes()); + } + }); + Ok(d) +} + +/// `<cache>/<sha256>-<size>.png`. +pub(crate) fn path(sha256: &str, size: u32) -> Result<PathBuf, String> { + Ok(dir()?.join(format!("{sha256}-{size}.png"))) +} + +fn run(ed: &mut Editor, name: &str, args: Value) -> Result<Vec<u64>, String> { + ed.dispatch(name, args).map(|o| o.created).map_err(|e| e.to_string()) +} + +fn first(created: Vec<u64>, what: &str) -> Result<u64, String> { + created.first().copied().ok_or_else(|| format!("{what} made nothing")) +} + +/// The thumbnail scene: the ball wearing `material`, a dark pedestal, the built-in studio, one soft key light. +pub(crate) fn scene(material: Material, size: u32) -> Result<Document, String> { + let mut ed = Editor::new(Document::new()); + run(&mut ed, "environment.set", json!({"values": {"source": {"kind": "studio"}, "background": "environment", "brightness": 1.0}}))?; + run(&mut ed, "ground.set", json!({"values": {"shadow_catcher": true, "reflection": 0.0}}))?; + run(&mut ed, "render.set_settings", json!({"values": {"width": size, "height": size, "samples": SAMPLES, "max_bounces": BOUNCES, "seed": 7, "denoise": true}}))?; + let glow = material.params.emission_luminance * fsh_scene::SCENE_UNITS_PER_NIT; + if glow > EMITTER_LEVEL { + let stops = -(glow / EMITTER_LEVEL).log2(); + run(&mut ed, "image.set_style", json!({"values": {"exposure": stops.max(-20.0)}}))?; + } + let pedestal = Material::new( + "Pedestal", + "plastic", + SurfaceParams { base_color: fsh_core::Rgb::splat(0.035), specular_roughness: 0.45, ..SurfaceParams::default() }, + ); + let wear = first(run(&mut ed, "material.create", json!({"material": material}))?, "material.create")?; + let stand = first(run(&mut ed, "material.create", json!({"material": pedestal}))?, "material.create")?; + let (ball_mesh, pedestal_mesh) = ball::meshes(); + for (mesh, mat, name) in [(ball_mesh, wear, "Ball"), (pedestal_mesh, stand, "Pedestal")] { + let out = ed.execute(Command::MeshAdd(MeshAdd { key: None, mesh: Arc::new(mesh) })).map_err(|e| e.to_string())?; + let key = first(out.created, "mesh.add")?; + run(&mut ed, "scene.add_part", json!({"name": name, "mesh": key, "material": mat}))?; + } + let key = Transform::look_at(Vec3::new(-1.6, 2.2, 1.9), Vec3::new(0.0, 0.6, 0.0), Vec3::Y).map_err(|e| e.to_string())?; + let trs = serde_json::to_value(Trs::from_matrix(&key.m).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; + run( + &mut ed, + "scene.add_light", + json!({"name": "Key", "transform": trs, "light": { + "shape": {"kind": "area_rect", "width": 1.4, "height": 1.0}, + "power": 1500.0, "unit": "lumen", "colour": {"mode": "kelvin", "kelvin": 5600.0} + }}), + )?; + run( + &mut ed, + "camera.set", + json!({"index": 0, "values": {"position": [0.0, 1.0, 2.55], "target": [0.0, 0.57, 0.0], "up": [0.0, 1.0, 0.0], "focal_length_mm": 64.0, "sensor_width_mm": 36.0}}), + )?; + Ok(ed.into_document()) +} + +/// Renders a preset's thumbnail to PNG bytes. +pub(crate) fn render(preset: &Preset, size: u32) -> Result<Vec<u8>, String> { + let mode = if procedurals_live() { GraphMode::Type } else { GraphMode::Flat }; + let material = preset.material(mode)?; + let doc = scene(material, size)?; + let snapshot = flatten(&doc); + let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); + let mut r = Renderer::with_threads(snapshot, threads).map_err(|e| e.to_string())?; + let never = AtomicBool::new(false); + while r.stats().samples < SAMPLES { + let n = (SAMPLES - r.stats().samples).min(8); + r.render_pass(n, &never); + } + let image = r.develop(Some(1.0)); + fsh_io::write_png_rgba8(image.width, image.height, &image.rgba8).map_err(|e| e.to_string()) +} + +fn work() { + let (lock, cv) = queue(); + loop { + let job = { + let mut q = lock.lock().unwrap_or_else(|p| p.into_inner()); + loop { + if let Some(j) = q.jobs.pop_front() { + q.states.insert(j.key.clone(), Status::Rendering); + break j; + } + q = cv.wait(q).unwrap_or_else(|p| p.into_inner()); + } + }; + let outcome = path(&job.key.0, job.key.1).and_then(|p| { + let png = render(&job.preset, job.key.1)?; + locate::write_atomic(&p, &png).map_err(|e| format!("the thumbnail {} could not be written: {e}", p.display())) + }); + let mut q = lock.lock().unwrap_or_else(|p| p.into_inner()); + match outcome { + Ok(()) => { + q.states.remove(&job.key); + } + Err(e) => { + q.states.insert(job.key, Status::Failed(e)); + } + } + cv.notify_all(); + } +} + +fn start_worker(q: &mut Queue) -> Result<(), String> { + if q.worker { + return Ok(()); + } + if cfg!(target_arch = "wasm32") { + return Err("thumbnails are rendered by the desktop engine".into()); + } + std::thread::Builder::new() + .name("formshot-thumbnails".into()) + .spawn(work) + .map_err(|e| format!("the thumbnail worker could not start: {e}"))?; + q.worker = true; + Ok(()) +} + +/// The thumbnail's status, queueing a render when it is missing (and, with `retry`, when it failed before). +pub(crate) fn request(preset: &Preset, size: u32, retry: bool) -> Result<Status, String> { + let file = path(&preset.sha256, size)?; + let key: Key = (preset.sha256.clone(), size); + let (lock, cv) = queue(); + let mut q = lock.lock().unwrap_or_else(|p| p.into_inner()); + match q.states.get(&key) { + Some(Status::Failed(_)) if !retry => return Ok(q.states[&key].clone()), + Some(s @ (Status::Queued | Status::Rendering)) => return Ok(s.clone()), + _ => {} + } + if file.is_file() { + return Ok(Status::Ready); + } + start_worker(&mut q)?; + q.jobs.push_back(Job { key: key.clone(), preset: preset.clone() }); + q.states.insert(key, Status::Queued); + cv.notify_all(); + Ok(Status::Queued) +} + +/// Waits up to `limit` for a queued thumbnail; answers its status then. +pub(crate) fn wait(preset: &Preset, size: u32, limit: Duration) -> Result<Status, String> { + let file = path(&preset.sha256, size)?; + let key: Key = (preset.sha256.clone(), size); + let end = Instant::now() + limit; + let (lock, cv) = queue(); + let mut q = lock.lock().unwrap_or_else(|p| p.into_inner()); + loop { + match q.states.get(&key) { + Some(s @ Status::Failed(_)) => return Ok(s.clone()), + Some(s @ (Status::Queued | Status::Rendering)) => { + let left = end.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Ok(s.clone()); + } + q = cv.wait_timeout(q, left).unwrap_or_else(|p| p.into_inner()).0; + } + _ => return Ok(if file.is_file() { Status::Ready } else { Status::Failed("the thumbnail was not written".into()) }), + } + } +} diff --git a/native/crates/fsh-commands/src/ext/materials.rs b/native/crates/fsh-commands/src/ext/materials.rs new file mode 100644 index 00000000..d09dfe73 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/materials.rs @@ -0,0 +1,257 @@ +//! Material types, textures and graphs (0.6.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::{EngineError, Result}; +use crate::util::{base64, get_u32, key_of}; +use fsh_core::MaterialKey; +use fsh_scene::fsh_materials::{NoTextures, Program}; +use fsh_scene::{ + bake_preview, compile_material, graph_kinds_json, types_json, ChangeLevel, Material, MaterialInput, RenderTexture, + TextureTable, PREVIEW_MAX, PREVIEW_MIN, +}; +use serde_json::{json, Value}; + +fn no_args() -> Value { + json!({"type": "object", "properties": {}, "additionalProperties": false}) +} + +fn material_arg() -> Value { + json!({"type": "object", "properties": { + "key": {"type": "integer", "minimum": 1, "description": "Material (alias: material)"}, + "material": {"type": "integer", "minimum": 1, "description": "Same as key"} + }, "additionalProperties": false}) +} + +fn preview_args() -> Value { + let mut s = material_arg(); + s["properties"]["size"] = json!({"type": "integer", "minimum": PREVIEW_MIN, "maximum": PREVIEW_MAX, "default": 128, "description": "Map width and height in pixels"}); + s +} + +pub(super) static COMMANDS: &[ExtCommand] = &[ + ExtCommand { + name: "material.types", + description: "The material types (id, name, category, default parameters, the parameters each page shows with ranges and units, preset graph) and the measured metal colours.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: no_args, + }, + ExtCommand { + name: "material.node_kinds", + description: "Material graph node kinds with their input and output sockets, defaults and settings, and the material inputs slots and graph outputs may drive.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: no_args, + }, + ExtCommand { + name: "material.program", + description: "A material's compiled program: whether it is constant, the instructions, constants, outputs, textures it samples and its encoded size.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: material_arg, + }, + ExtCommand { + name: "material.preview_maps", + description: "Small base colour, roughness, metalness and normal maps of a material baked in uv space by the CPU interpreter (base64 PNG), for the window's raster material view.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: preview_args, + }, + ExtCommand { + name: "material.get", + description: "One material's full JSON (name, type, params, texture keys, slots, graph, labels), the document's texture references by key, and a summary of its compiled program.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: material_arg, + }, + ExtCommand { + name: "material.labels", + description: "A material's labels in print order, each with its image path and pixel size (null when unknown), for the window's label list.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: material_arg, + }, +]; + +fn image_size(path: &std::path::Path) -> Option<[u32; 2]> { + use std::io::Read; + let mut head = Vec::new(); + std::fs::File::open(path).ok()?.take(512 * 1024).read_to_end(&mut head).ok()?; + let be16 = |i: usize| head.get(i..i + 2).map(|b| u16::from_be_bytes([b[0], b[1]]) as u32); + let be32 = |i: usize| head.get(i..i + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]])); + if head.starts_with(&[0x89, b'P', b'N', b'G']) { + return Some([be32(16)?, be32(20)?]); + } + if !head.starts_with(&[0xff, 0xd8]) { + return None; + } + let mut i = 2; + while i + 9 < head.len() && head[i] == 0xff { + let marker = head[i + 1]; + if (0xc0..=0xcf).contains(&marker) && !matches!(marker, 0xc4 | 0xc8 | 0xcc) { + return Some([be16(i + 7)?, be16(i + 5)?]); + } + i += 2 + be16(i + 2)? as usize; + } + None +} + +fn labels(st: &State, args: &Value) -> Result<Value> { + let (key, m) = material(st, args)?; + let doc = st.editor.document(); + let dir = st.path.as_deref().and_then(std::path::Path::parent); + let list: Vec<Value> = m + .labels + .iter() + .map(|l| { + let mut v = serde_json::to_value(l).unwrap_or(Value::Null); + let path = l.texture.and_then(|t| doc.textures().get(&t)).map(|t| t.path.clone()); + let size = path.as_deref().and_then(|p| { + let p = std::path::Path::new(p); + image_size(p).or_else(|| dir.and_then(|d| image_size(&d.join(p)))) + }); + v["path"] = json!(path); + v["image_size"] = json!(size); + v + }) + .collect(); + Ok(json!({"key": key.raw(), "labels": list})) +} + +fn material<'a>(st: &'a State, args: &Value) -> Result<(MaterialKey, &'a Material)> { + let raw = args + .get("key") + .or_else(|| args.get("material")) + .and_then(key_of) + .ok_or_else(|| EngineError::args("needs key (a material key)"))?; + let key = MaterialKey(raw); + let m = st.editor.document().material(key).ok_or_else(|| EngineError::args(format!("no material with key {raw}")))?; + Ok((key, m)) +} + +fn textures_json(list: &[RenderTexture]) -> Value { + Value::Array( + list.iter() + .enumerate() + .map(|(i, t)| json!({"index": i, "key": t.key.raw(), "path": t.path, "colour_space": t.colour_space, "mipmaps": t.mipmaps})) + .collect(), + ) +} + +fn program_json(p: &Program) -> Value { + let rgb = |c: fsh_core::Rgb| json!([c.r, c.g, c.b]); + let b = &p.base; + json!({ + "constant": p.is_constant(), + "instructions": p.code.len(), + "registers": p.registers, + "needs": p.needs, + "constants": p.consts, + "outputs": p.outputs.iter().map(|o| json!({"field": o.field.name(), "register": o.reg})).collect::<Vec<_>>(), + "encoded_words": if p.is_constant() { 0 } else { p.encode().len() }, + "disassembly": p.disassemble(), + "base": { + "base_weight": b.base_weight, "base_color": rgb(b.base_color), "base_metalness": b.base_metalness, + "base_diffuse_roughness": b.base_diffuse_roughness, "specular_weight": b.specular_weight, + "specular_color": rgb(b.specular_color), "specular_roughness": b.specular_roughness, "specular_ior": b.specular_ior, + "specular_anisotropy": b.specular_anisotropy, "transmission_weight": b.transmission_weight, + "transmission_color": rgb(b.transmission_color), "coat_weight": b.coat_weight, "coat_color": rgb(b.coat_color), + "coat_roughness": b.coat_roughness, "coat_ior": b.coat_ior, "fuzz_weight": b.fuzz_weight, + "fuzz_color": rgb(b.fuzz_color), "fuzz_roughness": b.fuzz_roughness, "emission": rgb(b.emission), + "opacity": b.opacity, "thin_walled": b.thin_walled, + }, + }) +} + +fn get(st: &State, args: &Value) -> Result<Value> { + let (key, m) = material(st, args)?; + let doc = st.editor.document(); + let textures: serde_json::Map<String, Value> = doc + .textures() + .iter() + .map(|(k, t)| (k.raw().to_string(), serde_json::to_value(t).unwrap_or(Value::Null))) + .collect(); + let mut table = TextureTable::new(doc.textures()); + let program = match compile_material(m, &mut table) { + Ok(p) => json!({ + "ok": true, + "constant": p.is_constant(), + "instructions": p.code.len(), + "registers": p.registers, + "needs": p.needs, + "outputs": p.outputs.iter().map(|o| o.field.name()).collect::<Vec<_>>(), + "textures": table.list.iter().map(|t| t.key.raw()).collect::<Vec<_>>(), + "encoded_words": if p.is_constant() { 0 } else { p.encode().len() }, + }), + Err(e) => json!({"ok": false, "error": e.to_string()}), + }; + Ok(json!({ + "key": key.raw(), + "material": serde_json::to_value(m).map_err(|e| EngineError::state(e.to_string()))?, + "used_textures": m.texture_keys().iter().map(|k| k.raw()).collect::<Vec<_>>(), + "textures": textures, + "program": program, + })) +} + +fn png(size: u32, rgba: &[u8]) -> Result<String> { + Ok(base64(&fsh_io::write_png_rgba8(size, size, rgba)?)) +} + +fn preview(st: &mut State, args: &Value) -> Result<Value> { + let (key, m) = material(st, args)?; + let m = m.clone(); + let size = get_u32(args, "size")?.unwrap_or(128).clamp(PREVIEW_MIN, PREVIEW_MAX); + let list = { + let mut table = TextureTable::new(st.editor.document().textures()); + compile_material(&m, &mut table)?; + table.list + }; + let set = crate::textures::lookup(st, &list); + let sampler: &dyn fsh_scene::fsh_materials::TextureSampler = if list.is_empty() { &NoTextures } else { &set }; + let maps = bake_preview(&m, st.editor.document().textures(), size, sampler)?; + let b = &maps.program.base; + let lin = b.base_color.to_linear_srgb(); + Ok(json!({ + "key": key.raw(), + "size": maps.size, + "constant": maps.constant, + "values": {"base_color": lin, "roughness": b.specular_roughness, "metalness": b.base_metalness, "opacity": b.opacity}, + "maps": { + "base_color": png(maps.size, &maps.base_color)?, + "roughness": png(maps.size, &maps.roughness)?, + "metalness": png(maps.size, &maps.metalness)?, + "normal": png(maps.size, &maps.normal)?, + }, + "textures": textures_json(&maps.textures), + })) +} + +pub(super) fn dispatch(_engine: &Engine, st: &mut State, name: &str, args: &Value) -> Option<Result<Value>> { + Some(match name { + "material.types" => Ok(types_json()), + "material.node_kinds" => Ok(json!({ + "kinds": graph_kinds_json(), + "inputs": MaterialInput::ALL.iter().map(|i| json!({"name": i.name(), "colour": i.is_colour(), "slot": i.slottable(), "graph": *i != MaterialInput::Bump})).collect::<Vec<_>>(), + })), + "material.program" => material(st, args).and_then(|(key, m)| { + let mut table = TextureTable::new(st.editor.document().textures()); + let p = compile_material(m, &mut table)?; + let mut v = program_json(&p); + v["key"] = json!(key.raw()); + v["textures"] = textures_json(&table.list); + Ok(v) + }), + "material.preview_maps" => preview(st, args), + "material.labels" => labels(st, args), + "material.get" => get(st, args), + _ => return None, + }) +} diff --git a/native/crates/fsh-commands/src/ext/mod.rs b/native/crates/fsh-commands/src/ext/mod.rs new file mode 100644 index 00000000..325cb074 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/mod.rs @@ -0,0 +1,50 @@ +//! Command groups added from 0.5.0 on, one module each, so each group is written without touching the others. +//! A module lists its commands in `COMMANDS` and answers them in `dispatch`, returning `None` for any other name. + +use crate::engine::{Engine, State}; +use crate::error::Result; +use fsh_scene::ChangeLevel; +use serde_json::Value; + +pub(crate) mod cad; +mod handoff; +pub(crate) mod import; +mod library; +mod materials; + +/// One command of a group: catalogue fields and a function giving its argument schema. +pub(crate) struct ExtCommand { + pub name: &'static str, + pub description: &'static str, + pub level: ChangeLevel, + pub mutates: bool, + pub read_only: bool, + pub schema: fn() -> Value, +} + +/// Every group's commands, in catalogue order. +pub(crate) fn commands() -> impl Iterator<Item = &'static ExtCommand> { + import::COMMANDS + .iter() + .chain(cad::COMMANDS.iter()) + .chain(handoff::COMMANDS.iter()) + .chain(materials::COMMANDS.iter()) + .chain(library::COMMANDS.iter()) +} + +/// Answers `name` when one of the groups owns it. +pub(crate) fn dispatch(engine: &Engine, st: &mut State, name: &str, args: &Value) -> Option<Result<Value>> { + if let Some(r) = import::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = cad::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = handoff::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = materials::dispatch(engine, st, name, args) { + return Some(r); + } + library::dispatch(engine, st, name, args) +} diff --git a/native/crates/fsh-commands/src/gpu.rs b/native/crates/fsh-commands/src/gpu.rs index 840546a5..5fe897c1 100644 --- a/native/crates/fsh-commands/src/gpu.rs +++ b/native/crates/fsh-commands/src/gpu.rs @@ -13,6 +13,7 @@ mod native { use crate::error::{EngineError, Result}; use fsh_render_cpu::{AdaptiveSettings, EnvImage, Image, PassReport, Stats}; use fsh_render_gpu::{AdapterReport, ContextOptions, GpuContext, GpuError, GpuRenderer, LimitsReport, Refusal, Refusals, RendererOptions}; + use fsh_scene::fsh_materials::TextureSet; use fsh_scene::{ImageStyle, RenderCamera, RenderSnapshot}; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::atomic::AtomicBool; @@ -151,7 +152,7 @@ mod native { return Err(refused_note(id, &why)); } let backend = r.context().report().backend.clone(); - Ok(Box::new(GpuPreview { r, id: id.to_string(), backend, snapshot, camera: None, style: None, env, stop: None, region: None })) + Ok(Box::new(GpuPreview { r, id: id.to_string(), backend, snapshot, camera: None, style: None, env, stop: None, region: None, textures: None })) } struct GpuPreview { @@ -164,6 +165,7 @@ mod native { env: Option<EnvImage>, stop: Option<(&'static str, String)>, region: Option<[f32; 4]>, + textures: Option<TextureSet>, } fn render_error(e: GpuError) -> EngineError { @@ -215,8 +217,27 @@ mod native { } fn update_region(&mut self, snapshot: &Arc<RenderSnapshot>) -> Result<RegionReset> { - self.set_snapshot(Arc::clone(snapshot))?; - Ok(RegionReset::Full) + let ids = match crate::device::changed_instances(&self.snapshot, snapshot) { + Some(ids) if self.stop.is_none() => ids, + _ => { + self.set_snapshot(Arc::clone(snapshot))?; + return Ok(RegionReset::Full); + } + }; + let (fw, fh) = self.r.film_size(); + let next = Arc::clone(snapshot); + match self.guarded(|r| r.update_region(next, &ids, crate::device::REGION_PAD)) { + Ok(rect) => { + self.snapshot = Arc::clone(snapshot); + self.stop = describe(&effective(self.r.refusals().list.clone())).map(|why| (REFUSED, why)); + let cleared = rect.map(|q| (q.x1 - q.x0) as u64 * (q.y1 - q.y0) as u64).unwrap_or(0); + Ok(RegionReset::Region { rect, cleared, total: fw as u64 * fh as u64 }) + } + Err(_) => { + self.set_snapshot(Arc::clone(snapshot))?; + Ok(RegionReset::Full) + } + } } fn update_camera(&mut self, camera: &RenderCamera) { @@ -234,6 +255,17 @@ mod native { self.r.set_environment_image(image); } + fn set_textures(&mut self, textures: Option<TextureSet>) { + self.textures = textures.clone(); + if self.stop.as_ref().is_some_and(|(code, _)| *code == FAILED) { + return; + } + match catch_unwind(AssertUnwindSafe(|| self.r.set_textures(textures))) { + Ok(_) => self.stop = describe(&effective(self.r.refusals().list.clone())).map(|why| (REFUSED, why)), + Err(_) => self.stop = Some((FAILED, "the GPU driver stopped with an internal error".into())), + } + } + fn set_resolution_scale(&mut self, scale: f32) -> f32 { if self.stop.is_none() { let _ = self.guarded(|r| r.set_resolution_scale(scale)); @@ -293,6 +325,10 @@ mod native { } Some((Arc::new(s), self.env.clone())) } + + fn fallback_textures(&self) -> Option<TextureSet> { + self.textures.clone() + } } } diff --git a/native/crates/fsh-commands/src/journal.rs b/native/crates/fsh-commands/src/journal.rs index 62738618..9faf4c68 100644 --- a/native/crates/fsh-commands/src/journal.rs +++ b/native/crates/fsh-commands/src/journal.rs @@ -1,4 +1,4 @@ -use fsh_format::{Project, Session}; +use fsh_format::{Preserved, Project, Session}; use fsh_scene::{Editor, Outcome}; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -9,20 +9,25 @@ const SNAPSHOT_EVERY: u64 = 100; /// A write failure stops journalling for the rest of the document and is reported, never raised. pub(crate) struct CrashJournal { root: PathBuf, - session: Option<Session>, + pub(crate) session: Option<Session>, error: Option<String>, last_snapshot: u64, } impl CrashJournal { - pub(crate) fn start(root: PathBuf, editor: &Editor, textures: &BTreeMap<String, Vec<u8>>, project: Option<&Path>) -> Self { + pub(crate) fn start(root: PathBuf, editor: &Editor, kept: &Project, project: Option<&Path>) -> Self { let mut j = Self { root, session: None, error: None, last_snapshot: 0 }; - j.open(editor, textures, project); + j.open(editor, kept, project); j } - fn open(&mut self, editor: &Editor, textures: &BTreeMap<String, Vec<u8>>, project: Option<&Path>) { - let base = Project { document: editor.document().clone(), textures: textures.clone(), ..Default::default() }; + fn open(&mut self, editor: &Editor, kept: &Project, project: Option<&Path>) { + let base = Project { + document: editor.document().clone(), + textures: kept.textures.clone(), + preserved: Preserved { sources: kept.preserved.sources.clone(), ..Default::default() }, + ..Default::default() + }; match Session::start(&self.root, &base, project) { Ok(s) => { self.session = Some(s); @@ -37,11 +42,19 @@ impl CrashJournal { } /// Ends the current session cleanly and starts a new one on the editor's document (new, open, save, recover). - pub(crate) fn restart(&mut self, editor: &Editor, textures: &BTreeMap<String, Vec<u8>>, project: Option<&Path>) { + pub(crate) fn restart(&mut self, editor: &Editor, kept: &Project, project: Option<&Path>) { if let Some(s) = self.session.take() { let _ = s.close(); } - self.open(editor, textures, project); + self.open(editor, kept, project); + } + + /// Copies newly kept CAD sources into the session folder so a recovery restores them. + pub(crate) fn keep_sources(&mut self, sources: &BTreeMap<String, Vec<u8>>) { + let Some(s) = self.session.as_mut() else { return }; + if let Err(e) = s.keep_sources(sources) { + self.error = Some(format!("a kept source could not be copied into the crash journal: {e}")); + } } pub(crate) fn root(&self) -> &Path { diff --git a/native/crates/fsh-commands/src/lib.rs b/native/crates/fsh-commands/src/lib.rs index 0868765f..31d3e1b3 100644 --- a/native/crates/fsh-commands/src/lib.rs +++ b/native/crates/fsh-commands/src/lib.rs @@ -8,12 +8,14 @@ mod device; mod engine; mod error; mod export; +mod ext; mod gpu; mod journal; mod meshes; mod render; mod sample; mod summary; +pub mod textures; mod util; mod view; diff --git a/native/crates/fsh-commands/src/meshes.rs b/native/crates/fsh-commands/src/meshes.rs index b13531ef..d4f6d212 100644 --- a/native/crates/fsh-commands/src/meshes.rs +++ b/native/crates/fsh-commands/src/meshes.rs @@ -14,6 +14,24 @@ pub(crate) struct MeshView { print: Option<u64>, revision: u64, meshes: BTreeMap<u64, (Arc<Mesh>, u64)>, + materials: BTreeMap<u64, (u64, u64)>, + material_counter: u64, +} + +fn material_print(doc: &Document, m: &fsh_scene::Material) -> u64 { + let mut text = serde_json::to_string(m).unwrap_or_default(); + for k in m.texture_keys() { + if let Some(t) = doc.textures().get(&k) { + text.push('\n'); + text.push_str(&t.path); + let path = std::path::Path::new(&t.path); + if let Some(meta) = path.is_absolute().then(|| std::fs::metadata(path).ok()).flatten() { + let modified = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos()).unwrap_or(0); + text.push_str(&format!(" {} {modified}", meta.len())); + } + } + } + hash_bytes(text.as_bytes()) } fn display_colour(c: Rgb) -> Value { @@ -42,6 +60,7 @@ fn walk(ed: &Editor, id: NodeId, out: &mut Vec<Value>, used: &mut BTreeMap<u64, "metalness": metalness, "roughness": roughness, "material_params": {"base_color": colour, "metalness": metalness, "roughness": roughness}, + "tinted": n.colour.is_some(), "visible": doc.is_visible(id), "selected": sel.iter().any(|s| doc.is_same_or_ancestor(*s, id)), })); @@ -58,7 +77,8 @@ fn le_f32(values: impl Iterator<Item = f32>) -> String { } /// `{key, vertices, indices, positions_b64, normals_b64, indices_b64}`: little-endian f32 xyz positions and normals -/// (computed when the mesh has none) and u32 indices. +/// (computed when the mesh has none) and u32 indices; plus `uv0_b64` (f32 uv of set 0) and `tangents_b64` (f32 xyz and +/// handedness sign) only when the mesh carries them, one entry per vertex. pub(crate) fn mesh_data(doc: &Document, key: u64) -> Result<Value> { let mesh = doc .mesh(MeshKey::from_raw(key)) @@ -73,14 +93,22 @@ pub(crate) fn mesh_data(doc: &Document, key: u64) -> Result<Value> { &computed }; let indices: Vec<u8> = m.indices.iter().flat_map(|i| i.to_le_bytes()).collect(); - Ok(json!({ + let mut v = json!({ "key": key.to_string(), "vertices": m.positions.len(), "indices": m.indices.len(), "positions_b64": le_f32(m.positions.iter().flat_map(|p| [p.x, p.y, p.z])), "normals_b64": le_f32(m.normals.iter().flat_map(|n| [n.x, n.y, n.z])), "indices_b64": base64(&indices), - })) + }); + let count = m.positions.len(); + if let Some(uv) = m.uvs.first().filter(|uv| uv.len() == count && count > 0) { + v["uv0_b64"] = Value::String(le_f32(uv.iter().flat_map(|t| [t.x, t.y]))); + } + if m.tangents.len() == count && count > 0 { + v["tangents_b64"] = Value::String(le_f32(m.tangents.iter().flat_map(|t| [t.x, t.y, t.z, if t.w < 0.0 { -1.0 } else { 1.0 }]))); + } + Ok(v) } impl MeshView { @@ -116,6 +144,27 @@ impl MeshView { .iter() .map(|(k, (m, r))| json!({"key": k.to_string(), "vertices": m.vertex_count(), "triangles": m.triangle_count(), "revision": r})) .collect(); - json!({"meshes": meshes, "instances": instances, "revision": self.revision}) + let materials = self.material_revisions(ed.document()); + json!({"meshes": meshes, "instances": instances, "materials": materials, "revision": self.revision}) + } + + /// `[{key, revision}]` for every material: the revision moves when the material's content, or the path, length or + /// modified time of a texture it names, changes, so the window refetches only that material's preview maps. + fn material_revisions(&mut self, doc: &Document) -> Vec<Value> { + let old = std::mem::take(&mut self.materials); + let mut out = Vec::with_capacity(doc.materials().len()); + for (k, m) in doc.materials() { + let print = material_print(doc, m); + let rev = match old.get(&k.raw()) { + Some((p, r)) if *p == print => *r, + _ => { + self.material_counter += 1; + self.material_counter + } + }; + self.materials.insert(k.raw(), (print, rev)); + out.push(json!({"key": k.raw().to_string(), "revision": rev})); + } + out } } diff --git a/native/crates/fsh-commands/src/render.rs b/native/crates/fsh-commands/src/render.rs index d6863804..9ee17bb4 100644 --- a/native/crates/fsh-commands/src/render.rs +++ b/native/crates/fsh-commands/src/render.rs @@ -2,6 +2,7 @@ use crate::clock::Moment; use crate::device::{self, Failed, PreviewRenderer}; use crate::error::{EngineError, Result}; use fsh_render_cpu::{EnvImage, Image}; +use fsh_scene::fsh_materials::TextureSet; use fsh_scene::RenderSnapshot; use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; @@ -19,13 +20,20 @@ pub struct Build { pub snapshot: Arc<RenderSnapshot>, pub env: Option<EnvImage>, pub env_key: String, + pub textures: Option<TextureSet>, gen: u64, } impl Build { /// A request for `device` with this scene. pub fn new(device: &str, snapshot: Arc<RenderSnapshot>, env: Option<EnvImage>, env_key: String) -> Self { - Self { device: device.to_string(), snapshot, env, env_key, gen: 0 } + Self { device: device.to_string(), snapshot, env, env_key, textures: None, gen: 0 } + } + + /// The same request with the pixels of the snapshot's textures. + pub fn with_textures(mut self, textures: Option<TextureSet>) -> Self { + self.textures = textures; + self } } @@ -268,8 +276,12 @@ fn fall_back(shared: &Shared, g: &mut Slot, e: EngineError) -> bool { let Some(r) = g.as_deref() else { return false }; let id = r.device().to_string(); let inputs = r.inputs(); + let textures = r.fallback_textures(); let note = device::failure_note(&id, &e, &mut lock(&shared.failed)); - let cpu = inputs.and_then(|(snap, env)| device::cpu(snap, env, shared.threads).ok()); + let mut cpu = inputs.and_then(|(snap, env)| device::cpu(snap, env, shared.threads).ok()); + if let Some(c) = cpu.as_mut().filter(|_| textures.is_some()) { + c.set_textures(textures); + } let ok = cpu.is_some(); *lock(&shared.note) = Some(note); if ok { @@ -357,6 +369,13 @@ fn build_step(shared: &Shared) { } }; let mut r = opened.renderer; + let textures = match b.as_ref() { + Some(n) if n.device == req.device => n.textures.clone(), + _ => req.textures.clone(), + }; + if textures.is_some() { + r.set_textures(textures); + } match b.as_ref() { Some(n) if n.gen == req.gen => *b = None, Some(n) if n.device == req.device => { @@ -631,6 +650,13 @@ impl RenderControl { true } + /// Replaces the texture pixels of a request still waiting for the render thread. + pub fn update_request_textures(&self, textures: Option<TextureSet>) { + if let Some(req) = lock(&self.shared.build).as_mut() { + req.textures = textures; + } + } + /// The device of the request waiting for the render thread, if any. pub fn requested_device(&self) -> Option<String> { lock(&self.shared.build).as_ref().map(|b| b.device.clone()) diff --git a/native/crates/fsh-commands/src/textures.rs b/native/crates/fsh-commands/src/textures.rs new file mode 100644 index 00000000..178b5369 --- /dev/null +++ b/native/crates/fsh-commands/src/textures.rs @@ -0,0 +1,283 @@ +use crate::engine::State; +use crate::render::Held; +use fsh_core::Rgb; +use fsh_format::Project; +use fsh_io::{decode_image, ImagePixels}; +pub use fsh_render_cpu::EnvImage; +use fsh_scene::fsh_materials::{ColourSpace, TextureImage, TextureSet}; +use fsh_scene::{RenderSnapshot, RenderTexture}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +/// Decodes an image file (PNG, JPEG, Radiance HDR or OpenEXR) into a texture for `colour_space`, with its mip +/// pyramid when `mipmaps`. 8-bit files keep 8-bit texels; 16-bit files become linear floats (sRGB decoded when the +/// colour space is sRGB); float files stay as they are. +pub fn texture_image(name: &str, bytes: &[u8], colour_space: ColourSpace, mipmaps: bool) -> Result<TextureImage, String> { + let d = decode_image(name, bytes).map_err(|e| e.to_string())?; + let img = match d.pixels { + ImagePixels::Rgba8(v) => TextureImage::from_rgba8(d.width, d.height, v, colour_space, mipmaps), + ImagePixels::Rgba16(v) => TextureImage::from_rgba16(d.width, d.height, &v, colour_space, mipmaps), + ImagePixels::RgbaF32(v) => TextureImage::from_rgba_f32(d.width, d.height, v, colour_space, mipmaps), + }; + img.ok_or_else(|| format!("{name} decoded to an image of the wrong size")) +} + +/// Decodes an environment image (Radiance HDR or OpenEXR, scene-linear sRGB, top row first) into ACEScg pixels. +pub fn environment_image(name: &str, bytes: &[u8]) -> Result<EnvImage, String> { + match fsh_io::detect_picture(name, bytes) { + Some(fsh_io::PictureFormat::Hdr) => { + let p = fsh_io::read_hdr(bytes).map_err(|e| e.to_string())?; + let pixels = (0..p.height) + .flat_map(|y| (0..p.width).map(move |x| (x, y))) + .map(|(x, y)| Rgb::from_linear_srgb(p.rgb(x, y))) + .collect(); + EnvImage::new(p.width, p.height, pixels).map_err(|e| e.to_string()) + } + Some(fsh_io::PictureFormat::Exr) => { + let d = decode_image(name, bytes).map_err(|e| e.to_string())?; + let ImagePixels::RgbaF32(v) = d.pixels else { + return Err(format!("environment image {name} does not hold float pixels")); + }; + let pixels = v.as_chunks::<4>().0.iter().map(|p| Rgb::from_linear_srgb([p[0], p[1], p[2]])).collect(); + EnvImage::new(d.width, d.height, pixels).map_err(|e| e.to_string()) + } + _ => Err(format!("environment image {name} is not a Radiance .hdr or OpenEXR file")), + } +} + +/// Where a texture path points: an `fshot:` member of the project or a file (relative paths against `base`). +pub fn texture_location(path: &str, base: Option<&Path>) -> PathBuf { + let p = Path::new(path); + match base { + Some(b) if p.is_relative() => b.join(p), + _ => p.to_path_buf(), + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Key { + path: String, + colour_space: ColourSpace, + length: u64, + modified: u128, +} + +/// What one load found. +#[derive(Clone, Debug, Default)] +pub struct LoadedTextures { + /// Images in `RenderSnapshot::textures` order. + pub set: TextureSet, + /// One readable line per image that could not be read or decoded (its fallback is used). + pub warnings: Vec<String>, + /// Images decoded by this load (the others came from the cache). + pub decoded: usize, +} + +/// Decoded images by (path, colour space, file length, modified time); embedded members use their length and time 0 +/// (their names carry a content hash). +#[derive(Default)] +pub struct TextureCache { + images: BTreeMap<Key, Arc<TextureImage>>, +} + +impl TextureCache { + /// Loads every texture of a snapshot list: `fshot:` paths from `project`'s embedded members, other paths from disk + /// (relative ones against `base`, normally the document's folder). Missing or undecodable images are `None` with + /// a warning; the cache keeps only the images of this list afterwards. + pub fn load(&mut self, list: &[RenderTexture], project: &Project, base: Option<&Path>) -> LoadedTextures { + let (out, used) = self.gather(list, project, base); + self.images.retain(|k, _| used.contains(k)); + out + } + + /// `load` without dropping other cached images (for a list other than the renderer's, such as a preview's). + pub fn lookup(&mut self, list: &[RenderTexture], project: &Project, base: Option<&Path>) -> LoadedTextures { + self.gather(list, project, base).0 + } + + fn gather(&mut self, list: &[RenderTexture], project: &Project, base: Option<&Path>) -> (LoadedTextures, Vec<Key>) { + let mut out = LoadedTextures { set: TextureSet { images: Vec::with_capacity(list.len()) }, ..Default::default() }; + let mut used = Vec::with_capacity(list.len()); + for t in list { + match self.one(t, project, base, &mut out.decoded) { + Ok((key, img)) => { + used.push(key); + out.set.images.push(Some(img)); + } + Err(e) => { + out.warnings.push(format!("texture {}: {e}; its fallback value is used", t.path)); + out.set.images.push(None); + } + } + } + (out, used) + } + + fn one(&mut self, t: &RenderTexture, project: &Project, base: Option<&Path>, decoded: &mut usize) -> Result<(Key, Arc<TextureImage>), String> { + let embedded = t.path.starts_with(fsh_format::EMBED_SCHEME); + let (key, file) = if embedded { + let bytes = project.texture_bytes(&t.path).ok_or("the project has no such embedded member")?; + (Key { path: t.path.clone(), colour_space: t.colour_space, length: bytes.len() as u64, modified: 0 }, None) + } else { + let at = texture_location(&t.path, base); + let (length, modified) = file_stamp(&at).map_err(|e| format!("cannot read {}: {e}", at.display()))?; + (Key { path: at.to_string_lossy().into_owned(), colour_space: t.colour_space, length, modified }, Some(at)) + }; + if let Some(img) = self.images.get_mut(&key) { + if t.mipmaps && img.levels.len() == 1 && (img.levels[0].width > 1 || img.levels[0].height > 1) { + Arc::make_mut(img).build_mips(); + } + return Ok((key, Arc::clone(img))); + } + let img = match &file { + Some(at) => { + let bytes = std::fs::read(at).map_err(|e| format!("cannot read {}: {e}", at.display()))?; + texture_image(&t.path, &bytes, t.colour_space, t.mipmaps)? + } + None => texture_image(&t.path, project.texture_bytes(&t.path).unwrap_or_default(), t.colour_space, t.mipmaps)?, + }; + *decoded += 1; + let img = Arc::new(img); + self.images.insert(key.clone(), Arc::clone(&img)); + Ok((key, img)) + } +} + +/// Length and modified time (nanoseconds since the epoch, 0 when unknown) of a file. +fn file_stamp(at: &Path) -> std::io::Result<(u64, u128)> { + let meta = std::fs::metadata(at)?; + let modified = meta.modified().ok().and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos()); + Ok((meta.len(), modified)) +} + +/// File stamps of a texture list (`None` for embedded members and unreadable files). +fn stamps(list: &[RenderTexture], base: Option<&Path>) -> Vec<Option<(u64, u128)>> { + list.iter() + .map(|t| (!t.path.starts_with(fsh_format::EMBED_SCHEME)).then(|| file_stamp(&texture_location(&t.path, base)).ok()).flatten()) + .collect() +} + +type Given = (Vec<RenderTexture>, Option<PathBuf>, Vec<Option<(u64, u128)>>); + +/// The engine session's texture state: the cache, the list last handed to the renderer (with its folder and the +/// files' stamps) and the last warnings. +#[derive(Default)] +pub(crate) struct Textures { + cache: TextureCache, + given: Option<Given>, + warnings: Vec<String>, + loaded: usize, +} + +impl Textures { + /// Loads the list for a new renderer or a still and remembers it as given. + pub(crate) fn load(&mut self, list: &[RenderTexture], project: &Project, base: Option<&Path>, warnings: &mut Vec<String>) -> TextureSet { + let now = stamps(list, base); + let l = self.cache.load(list, project, base); + self.loaded = l.set.images.iter().filter(|i| i.is_some()).count(); + if l.decoded > 0 || !self.same(list, base, &now) { + warnings.extend(l.warnings.iter().cloned()); + } + self.warnings = l.warnings; + self.given = Some((list.to_vec(), base.map(Path::to_path_buf), now)); + l.set + } + + fn same(&self, list: &[RenderTexture], base: Option<&Path>, now: &[Option<(u64, u128)>]) -> bool { + self.given.as_ref().is_some_and(|(l, b, s)| l.as_slice() == list && b.as_deref() == base && s.as_slice() == now) + } + + /// The set to hand to the running renderer when the list, the folder relative paths start from, or a file's + /// length or modified time differs from what it has; `None` when unchanged. + pub(crate) fn changed(&mut self, list: &[RenderTexture], project: &Project, base: Option<&Path>, warnings: &mut Vec<String>) -> Option<TextureSet> { + if self.same(list, base, &stamps(list, base)) { + return None; + } + Some(self.load(list, project, base, warnings)) + } + + /// `render.status` entry: `{count, loaded, missing, warnings}`. + pub(crate) fn status(&self) -> Value { + let count = self.given.as_ref().map_or(0, |(l, _, _)| l.len()); + json!({"count": count, "loaded": self.loaded, "missing": count.saturating_sub(self.loaded), "warnings": self.warnings}) + } +} + +fn base(st: &State) -> Option<PathBuf> { + st.path.as_deref().and_then(Path::parent).map(Path::to_path_buf) +} + +/// The image path a scene command brings in: `path` of `material.set_slot`, `material.label_add` and +/// `material.label_set`, `texture.path` of `texture.add`, `values.source.path` of an `environment.set` to an HDRI. +fn command_path<'a>(name: &str, args: &'a mut Value) -> Option<&'a mut Value> { + match name { + "material.set_slot" | "material.label_add" | "material.label_set" => args.get_mut("path"), + "texture.add" => args.get_mut("texture").and_then(|t| t.get_mut("path")), + "environment.set" => args + .get_mut("values") + .and_then(|v| v.get_mut("source")) + .filter(|s| s.get("kind").and_then(Value::as_str) == Some("hdri")) + .and_then(|s| s.get_mut("path")), + _ => None, + } +} + +/// Keeps the image a scene command names by file path inside the project (`fshot:textures/<sha256-32>.<ext>`) and +/// rewrites the argument to that member before the command runs, so the document, its journal and the saved `.fshot` +/// never depend on the file staying where it was. Relative paths start at the document's folder. Missing files, +/// files above 256 MiB and formats the engine does not decode keep their path (the render reports them). True when a +/// member new to the project was kept. +pub(crate) fn embed_command_path(st: &mut State, name: &str, args: &mut Value) -> bool { + let b = base(st); + let Some(slot) = command_path(name, args) else { return false }; + let Some(path) = slot.as_str().filter(|p| !p.is_empty() && !p.starts_with(fsh_format::EMBED_SCHEME)) else { return false }; + let at = texture_location(path, b.as_deref()); + let fits = std::fs::metadata(&at).is_ok_and(|m| m.is_file() && m.len() <= fsh_format::MAX_EMBED_TEXTURE_BYTES as u64); + let Some(bytes) = fits.then(|| std::fs::read(&at).ok()).flatten() else { return false }; + let ext = match fsh_io::detect_image("", &bytes) { + Some(fsh_io::ImageFormat::Png) => "png", + Some(fsh_io::ImageFormat::Jpeg) => "jpg", + Some(fsh_io::ImageFormat::Hdr) => "hdr", + Some(fsh_io::ImageFormat::Exr) => "exr", + None => return false, + }; + let Some(member) = fsh_format::texture_member(&bytes, ext) else { return false }; + *slot = Value::String(format!("{}{member}", fsh_format::EMBED_SCHEME)); + match st.kept.textures.entry(member) { + std::collections::btree_map::Entry::Vacant(v) => { + v.insert(bytes); + true + } + std::collections::btree_map::Entry::Occupied(_) => false, + } +} + +/// The images of a texture list other than the renderer's (a material preview's) from the session's cache, which keeps +/// the renderer's images. +pub(crate) fn lookup(st: &mut State, list: &[RenderTexture]) -> TextureSet { + let b = base(st); + st.textures.cache.lookup(list, &st.kept, b.as_deref()).set +} + +/// The set for a new renderer or a still of `snap` (remembered as what the renderer has); `None` without textures. +pub(crate) fn for_snapshot(st: &mut State, snap: &RenderSnapshot, warnings: &mut Vec<String>) -> Option<TextureSet> { + let b = base(st); + let set = st.textures.load(&snap.textures, &st.kept, b.as_deref(), warnings); + (!set.images.is_empty()).then_some(set) +} + +/// Hands the held renderer a new set when `snap`'s texture list differs from the one it has; true when it did (the +/// renderer then restarted the whole film). +pub(crate) fn sync(st: &mut State, held: &mut Held, snap: &RenderSnapshot, warnings: &mut Vec<String>) -> bool { + let b = base(st); + let Some(set) = st.textures.changed(&snap.textures, &st.kept, b.as_deref(), warnings) else { return false }; + match held.renderer() { + Some(r) => { + r.set_textures((!set.images.is_empty()).then_some(set)); + true + } + None => false, + } +} diff --git a/native/crates/fsh-core/Cargo.toml b/native/crates/fsh-core/Cargo.toml index 70558b69..828003f0 100644 --- a/native/crates/fsh-core/Cargo.toml +++ b/native/crates/fsh-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-core" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false diff --git a/native/crates/fsh-format/Cargo.toml b/native/crates/fsh-format/Cargo.toml index 6c263e87..2c9707f4 100644 --- a/native/crates/fsh-format/Cargo.toml +++ b/native/crates/fsh-format/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-format" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false diff --git a/native/crates/fsh-format/src/lib.rs b/native/crates/fsh-format/src/lib.rs index c00be0cf..079877fc 100644 --- a/native/crates/fsh-format/src/lib.rs +++ b/native/crates/fsh-format/src/lib.rs @@ -8,6 +8,7 @@ pub mod meshbin; mod platform; mod project; pub mod session; +pub mod sha256; mod version; pub mod zip; @@ -15,9 +16,10 @@ pub use error::{FormatError, Result}; pub use platform::{now_ms, process_id, set_wall_clock, HAS_FILE_SYSTEM}; pub use journal::{replay, replay_editor, Journal, JournalEntry, JournalHeader}; pub use project::{ - atomic_write, fingerprint, load_bytes, load_file, material_member, mesh_member, save_bytes, save_file, LoadReport, - Preserved, Project, SaveOptions, EMBED_SCHEME, EXTENSION, FORMAT_NAME, MANIFEST_MEMBER, PREVIEW_MEMBER, - PROJECT_FILE_NAME, SCENE_MEMBER, + atomic_write, fingerprint, load_bytes, load_file, material_member, mesh_member, save_bytes, save_file, source_member, + texture_member, LoadReport, Preserved, Project, SaveOptions, EMBED_SCHEME, EXTENSION, FORMAT_NAME, MANIFEST_MEMBER, + MAX_EMBED_TEXTURE_BYTES, MAX_SOURCE_BYTES, PREVIEW_MEMBER, PROJECT_FILE_NAME, SCENE_MEMBER, SOURCES_PREFIX, + TEXTURES_PREFIX, }; pub use session::{recover, RecoverableSession, Recovered, RecoveryStrategy, Session, SnapshotDone, SnapshotJob}; pub use version::{Migration, MigrationInput, Version, FORMAT_VERSION, MIGRATIONS}; diff --git a/native/crates/fsh-format/src/project.rs b/native/crates/fsh-format/src/project.rs index cdc2c557..ecb052c1 100644 --- a/native/crates/fsh-format/src/project.rs +++ b/native/crates/fsh-format/src/project.rs @@ -44,9 +44,41 @@ pub fn material_member(k: MaterialKey) -> String { format!("materials/{}.json", k.raw()) } -/// Content that a newer writer put in the file and this build does not understand; written back unchanged. +/// Largest original CAD file kept inside a project; larger sources are referenced by path. +pub const MAX_SOURCE_BYTES: usize = 64 << 20; +/// Folder of kept source files inside a project. +pub const SOURCES_PREFIX: &str = "sources/"; + +/// Member path a source file is kept under: `sources/<fnv64 hex>.<ext>`. +pub fn source_member(bytes: &[u8], ext: &str) -> Option<String> { + let ext = sanitize_ext(ext)?; + Some(format!("{SOURCES_PREFIX}{:016x}.{ext}", hash_bytes(bytes))) +} + +pub(crate) fn check_source_member(name: &str, data: &[u8]) -> core::result::Result<(), String> { + let rest = name.strip_prefix(SOURCES_PREFIX).ok_or("is not under sources/")?; + let (hash, ext) = rest.split_once('.').ok_or("has no extension")?; + if sanitize_ext(ext).as_deref() != Some(ext) { + return Err("has an invalid extension".into()); + } + if hash.len() != 16 || !hash.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) { + return Err("is not named by a 16-digit lowercase hex hash".into()); + } + if data.len() > MAX_SOURCE_BYTES { + return Err(format!("holds {} bytes, more than the 64 MiB a kept source may have", data.len())); + } + if format!("{:016x}", hash_bytes(data)) != hash { + return Err("content does not match the hash in its name (the source file is damaged)".into()); + } + Ok(()) +} + +/// Content kept for the next save: what a newer writer put in the file and this build does not understand +/// (written back unchanged), and the original CAD files the document was imported from. #[derive(Clone, Debug, Default, PartialEq)] pub struct Preserved { + /// Kept source files by member path (`sources/<fnv64 hex>.<ext>`), at most 64 MiB each. + pub sources: BTreeMap<String, Vec<u8>>, /// Unknown top-level fields of `manifest.json`. pub manifest_fields: Map<String, Value>, /// Unknown top-level fields of `scene.json`. @@ -62,7 +94,8 @@ pub struct Preserved { pub struct Project { /// The document. pub document: Document, - /// Embedded texture files by member path (`textures/<fnv64 hex>-<length>.<ext>`). + /// Embedded texture files by member path (`textures/<sha256 prefix>.<ext>`, or the older + /// `textures/<fnv64 hex>-<length>.<ext>`). pub textures: BTreeMap<String, Vec<u8>>, /// Optional preview image (PNG bytes). pub preview_png: Option<Vec<u8>>, @@ -101,13 +134,36 @@ fn sanitize_ext(ext: &str) -> Option<String> { (!e.is_empty() && e.len() <= 8 && e.bytes().all(|b| b.is_ascii_alphanumeric())).then_some(e) } +/// Folder of embedded textures inside a project. +pub const TEXTURES_PREFIX: &str = "textures/"; +/// Largest texture embedded in a project; larger images are referenced by path. +pub const MAX_EMBED_TEXTURE_BYTES: usize = 256 << 20; +const SHA_DIGITS: usize = 32; + +/// Member path of an embedded texture: `textures/<first 32 hex digits of its SHA-256>.<ext>`; None for a bad +/// extension. +pub fn texture_member(bytes: &[u8], ext: &str) -> Option<String> { + let ext = sanitize_ext(ext)?; + Some(format!("{TEXTURES_PREFIX}{}.{ext}", crate::sha256::sha256_hex(bytes, SHA_DIGITS))) +} + +fn is_lower_hex(s: &str, digits: usize) -> bool { + s.len() == digits && s.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) +} + fn check_texture_member(name: &str, data: &[u8]) -> core::result::Result<(), String> { - let rest = name.strip_prefix("textures/").ok_or("is not under textures/")?; + let rest = name.strip_prefix(TEXTURES_PREFIX).ok_or("is not under textures/")?; let (stem, ext) = rest.rsplit_once('.').ok_or("has no extension")?; if sanitize_ext(ext).as_deref() != Some(ext) { return Err("has an invalid extension".into()); } - let (hash, len) = stem.split_once('-').ok_or("is not named <hash>-<length>")?; + if is_lower_hex(stem, SHA_DIGITS) { + if crate::sha256::sha256_hex(data, SHA_DIGITS) != stem { + return Err("content does not match the SHA-256 in its name (the texture is damaged)".into()); + } + return Ok(()); + } + let (hash, len) = stem.split_once('-').ok_or("is not named <sha256> or <hash>-<length>")?; if hash.len() != 16 || !hash.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) { return Err("is not named by a 16-digit lowercase hex hash".into()); } @@ -126,10 +182,14 @@ impl Project { Self { document, ..Default::default() } } - /// Stores texture bytes by content hash and returns the `TextureRef.path` that refers to them. + /// Stores texture bytes by content hash (`textures/<sha256 prefix>.<ext>`) and returns the `TextureRef.path` + /// that refers to them; refuses images above [`MAX_EMBED_TEXTURE_BYTES`]. pub fn embed_texture(&mut self, bytes: Vec<u8>, ext: &str) -> Result<String> { - let ext = sanitize_ext(ext).ok_or_else(|| FormatError::Document(format!("texture extension {ext:?} is not 1 to 8 letters or digits")))?; - let name = format!("textures/{:016x}-{}.{ext}", hash_bytes(&bytes), bytes.len()); + if bytes.len() > MAX_EMBED_TEXTURE_BYTES { + return Err(FormatError::Document(format!("an embedded texture may hold at most 256 MiB; this one has {} bytes", bytes.len()))); + } + let name = texture_member(&bytes, ext) + .ok_or_else(|| FormatError::Document(format!("texture extension {ext:?} is not 1 to 8 letters or digits")))?; self.textures.entry(name.clone()).or_insert(bytes); Ok(format!("{EMBED_SCHEME}{name}")) } @@ -138,6 +198,32 @@ impl Project { pub fn texture_bytes(&self, path: &str) -> Option<&[u8]> { path.strip_prefix(EMBED_SCHEME).and_then(|m| self.textures.get(m)).map(|v| v.as_slice()) } + + /// Keeps an original source file (a CAD model) by content hash and returns its reference + /// (`fshot:sources/<hash>.<ext>`); refuses files above [`MAX_SOURCE_BYTES`]. + pub fn keep_source(&mut self, bytes: Vec<u8>, ext: &str) -> Result<String> { + if bytes.len() > MAX_SOURCE_BYTES { + return Err(FormatError::Document(format!("a kept source may hold at most 64 MiB; this one has {} bytes", bytes.len()))); + } + let name = source_member(&bytes, ext) + .ok_or_else(|| FormatError::Document(format!("source extension {ext:?} is not 1 to 8 letters or digits")))?; + self.preserved.sources.entry(name.clone()).or_insert(bytes); + Ok(format!("{EMBED_SCHEME}{name}")) + } + + /// Bytes of a kept source by its reference (`fshot:sources/...`) or member path. + pub fn source_bytes(&self, reference: &str) -> Option<&[u8]> { + let member = reference.strip_prefix(EMBED_SCHEME).unwrap_or(reference); + self.preserved.sources.get(member).map(|v| v.as_slice()) + } + + /// Drops kept sources that no node of `doc` names in its metadata; returns how many were dropped. + pub fn prune_sources(&mut self, doc: &Document) -> usize { + let used = referenced_sources(doc); + let before = self.preserved.sources.len(); + self.preserved.sources.retain(|k, _| used.contains(k)); + before - self.preserved.sources.len() + } } fn keys_of<T: serde::Serialize>(v: &T) -> BTreeSet<String> { @@ -159,6 +245,17 @@ fn bytes_of(v: &Value) -> Vec<u8> { } /// Encodes a project as `.fshot` bytes; the same project always gives the same bytes. +/// Member paths of the kept sources that some node of `doc` names in its metadata (`fshot:sources/...`). +pub fn referenced_sources(doc: &Document) -> BTreeSet<String> { + doc.nodes() + .values() + .flat_map(|n| n.metadata.values()) + .filter_map(|v| v.strip_prefix(EMBED_SCHEME)) + .filter(|m| m.starts_with(SOURCES_PREFIX)) + .map(str::to_string) + .collect() +} + pub fn save_bytes(project: &Project, opts: &SaveOptions) -> Result<Vec<u8>> { encode(project, opts, true) } @@ -180,6 +277,11 @@ pub(crate) fn encode(project: &Project, opts: &SaveOptions, strict: bool) -> Res embedded.insert(m.to_string()); } } + if let fsh_scene::EnvironmentSource::Hdri { path } = &data.environment.source { + if let Some(m) = path.strip_prefix(EMBED_SCHEME).filter(|m| project.textures.contains_key(*m)) { + embedded.insert(m.to_string()); + } + } if let Some(p) = &project.preview_png { if !p.starts_with(&PNG_SIGNATURE) || p.len() > PREVIEW_LIMIT { return Err(FormatError::member(PREVIEW_MEMBER, "is not a PNG of at most 32 MiB")); @@ -209,6 +311,14 @@ pub(crate) fn encode(project: &Project, opts: &SaveOptions, strict: bool) -> Res Value::Array(data.materials.keys().map(|k| Value::from(k.raw().to_string())).collect()), ); manifest.insert("textures".into(), Value::Array(embedded.iter().map(|m| Value::from(m.as_str())).collect())); + let used = referenced_sources(doc); + let sources: Vec<(&String, &Vec<u8>)> = project.preserved.sources.iter().filter(|(k, _)| used.contains(*k)).collect(); + for (name, bytes) in &sources { + check_source_member(name, bytes).map_err(|r| FormatError::member(name, r))?; + } + if !sources.is_empty() { + manifest.insert("sources".into(), Value::Array(sources.iter().map(|(m, _)| Value::from(m.as_str())).collect())); + } manifest.insert( "preview".into(), if project.preview_png.is_some() { Value::from(PREVIEW_MEMBER) } else { Value::Null }, @@ -238,6 +348,9 @@ pub(crate) fn encode(project: &Project, opts: &SaveOptions, strict: bool) -> Res for m in &embedded { add(&mut z, m, &project.textures[m])?; } + for (name, bytes) in &sources { + add(&mut z, name, bytes)?; + } if let Some(p) = &project.preview_png { add(&mut z, PREVIEW_MEMBER, p)?; } @@ -394,6 +507,24 @@ pub(crate) fn decode(bytes: &[u8], strict: bool) -> Result<(Project, LoadReport) } Some(_) => return Err(FormatError::member(MANIFEST_MEMBER, "textures is not a list")), } + let mut sources = BTreeMap::new(); + match manifest_obj.get("sources") { + None | Some(Value::Null) => {} + Some(Value::Array(a)) => { + for s in a { + let name = s + .as_str() + .ok_or_else(|| FormatError::member(MANIFEST_MEMBER, "sources holds a value that is not a member path"))?; + let b = zip.read(name).ok_or_else(|| FormatError::member(name, "is listed in the manifest but missing"))?; + check_source_member(name, b).map_err(|r| FormatError::member(name, r))?; + if sources.insert(name.to_string(), b.to_vec()).is_some() { + return Err(FormatError::member(MANIFEST_MEMBER, format!("sources lists {name} twice"))); + } + expected.insert(name.to_string()); + } + } + Some(_) => return Err(FormatError::member(MANIFEST_MEMBER, "sources is not a list")), + } let preview_png = match manifest_obj.get("preview") { None | Some(Value::Null) => None, Some(Value::String(p)) if p == PREVIEW_MEMBER => { @@ -406,7 +537,7 @@ pub(crate) fn decode(bytes: &[u8], strict: bool) -> Result<(Project, LoadReport) } Some(_) => return Err(FormatError::member(MANIFEST_MEMBER, format!("preview must be null or \"{PREVIEW_MEMBER}\""))), }; - let mut preserved = Preserved::default(); + let mut preserved = Preserved { sources, ..Preserved::default() }; for e in zip.entries() { if e.is_dir || expected.contains(&e.name) { continue; @@ -430,7 +561,7 @@ pub(crate) fn decode(bytes: &[u8], strict: bool) -> Result<(Project, LoadReport) .unwrap_or("unknown") .to_string(); let manifest_known: BTreeSet<&str> = - ["format", "format_version", "writer", "scene", "meshes", "materials", "textures", "preview"].into(); + ["format", "format_version", "writer", "scene", "meshes", "materials", "textures", "sources", "preview"].into(); for (k, v) in object(MANIFEST_MEMBER, manifest_v)? { if !manifest_known.contains(k.as_str()) { warnings.push(format!("kept unknown manifest field {k}")); @@ -453,7 +584,7 @@ pub(crate) fn decode(bytes: &[u8], strict: bool) -> Result<(Project, LoadReport) scene_known_obj.insert("format_version".into(), Value::from(fsh_scene::FORMAT_VERSION)); let mut data: DocumentData = serde_json::from_value(Value::Object(scene_known_obj)) .map_err(|e| FormatError::member(SCENE_MEMBER, format!("does not match the document layout ({e})")))?; - let mat_known = keys_of(&Material::default()); + let mat_known: BTreeSet<String> = fsh_scene::MATERIAL_FIELDS.iter().map(|f| f.to_string()).collect(); for (k, v) in materials_v { let name = material_member(MaterialKey(k)); let mut known_obj = Map::new(); diff --git a/native/crates/fsh-format/src/session.rs b/native/crates/fsh-format/src/session.rs index 6ae89b7c..0fad96a8 100644 --- a/native/crates/fsh-format/src/session.rs +++ b/native/crates/fsh-format/src/session.rs @@ -3,9 +3,9 @@ use crate::error::{FormatError, Result}; use crate::journal::{apply_entries, entry_line, header_line, replay_editor, Journal, JournalEntry, JournalHeader}; use crate::json::to_canonical; -use crate::project::{atomic_write, decode, encode, fingerprint, Project, SaveOptions}; +use crate::project::{atomic_write, check_source_member, decode, encode, fingerprint, Project, SaveOptions, SOURCES_PREFIX}; use fsh_scene::{Document, Editor, Outcome}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Map, Value}; use std::fs::{File, OpenOptions, TryLockError}; use std::io::Write; @@ -65,6 +65,7 @@ pub struct Session { large_line_bytes: usize, shadow: Shadow, textures: BTreeMap<String, Vec<u8>>, + sources: BTreeSet<String>, } /// A snapshot prepared on the editing thread and written by `run` on any thread. @@ -129,11 +130,31 @@ impl Session { large_line_bytes: DEFAULT_LARGE_LINE_BYTES, shadow: Shadow::default(), textures: base.textures.clone(), + sources: BTreeSet::new(), }; s.write_origin(&base.document, 0)?; + s.keep_sources(&base.preserved.sources)?; Ok(s) } + /// Copies kept CAD sources (`sources/<hash>.<ext>` members) into the session folder once each, so recovery + /// gives them back; call after keeping a source. Names and contents are checked like a project's members. + pub fn keep_sources(&mut self, sources: &BTreeMap<String, Vec<u8>>) -> Result<()> { + for (name, bytes) in sources { + if self.sources.contains(name) { + continue; + } + check_source_member(name, bytes).map_err(|r| FormatError::member(name, r))?; + let path = self.dir.join(name); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| FormatError::io(parent, e))?; + } + atomic_write(&path, bytes)?; + self.sources.insert(name.clone()); + } + Ok(()) + } + /// Replaces the embedded textures that later origins and snapshots carry (call after embedding a texture). pub fn set_textures(&mut self, textures: &BTreeMap<String, Vec<u8>>) { self.textures = textures.clone(); @@ -361,6 +382,8 @@ pub struct Recovered { pub notes: Vec<String>, /// Embedded textures found in the session's origin and snapshot files. pub textures: BTreeMap<String, Vec<u8>>, + /// Kept CAD sources (`sources/<hash>.<ext>` members) the session copied, ready for `Preserved::sources`. + pub sources: BTreeMap<String, Vec<u8>>, } /// A crashed session found by `recover`; holds its lock until dropped, recovered from or discarded. @@ -425,7 +448,19 @@ impl RecoverableSession { textures.extend(p.textures); } } - Ok(Recovered { editor, strategy, notes, textures }) + let mut sources = BTreeMap::new(); + if let Ok(rd) = std::fs::read_dir(self.dir.join(SOURCES_PREFIX.trim_end_matches('/'))) { + for ent in rd.flatten() { + let name = format!("{SOURCES_PREFIX}{}", ent.file_name().to_string_lossy()); + match std::fs::read(ent.path()).map_err(|e| e.to_string()).and_then(|b| check_source_member(&name, &b).map(|_| b)) { + Ok(bytes) => { + sources.insert(name, bytes); + } + Err(e) => notes.push(format!("the kept source {name} was left out: {e}")), + } + } + } + Ok(Recovered { editor, strategy, notes, textures, sources }) } fn rebuild(&self, notes: &mut Vec<String>) -> Result<(Editor, RecoveryStrategy)> { diff --git a/native/crates/fsh-format/src/sha256.rs b/native/crates/fsh-format/src/sha256.rs new file mode 100644 index 00000000..841c964d --- /dev/null +++ b/native/crates/fsh-format/src/sha256.rs @@ -0,0 +1,77 @@ +//! SHA-256 (FIPS 180-4) for naming embedded texture members by content. + +const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, + 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, + 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +const H0: [u32; 8] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; + +fn compress(h: &mut [u32; 8], block: &[u8; 64]) { + let mut w = [0u32; 64]; + for (i, c) in block.as_chunks::<4>().0.iter().enumerate() { + w[i] = u32::from_be_bytes(*c); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = *h; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ (!e & g); + let t1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(maj); + hh = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + for (x, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { + *x = x.wrapping_add(v); + } +} + +/// SHA-256 digest of `data`. +pub fn sha256(data: &[u8]) -> [u8; 32] { + let mut h = H0; + let (blocks, rest) = data.as_chunks::<64>(); + for b in blocks { + compress(&mut h, b); + } + let mut tail = [0u8; 128]; + tail[..rest.len()].copy_from_slice(rest); + tail[rest.len()] = 0x80; + let len = if rest.len() < 56 { 64 } else { 128 }; + tail[len - 8..len].copy_from_slice(&((data.len() as u64).wrapping_mul(8)).to_be_bytes()); + for b in tail[..len].as_chunks::<64>().0 { + compress(&mut h, b); + } + let mut out = [0u8; 32]; + for (o, v) in out.as_chunks_mut::<4>().0.iter_mut().zip(h) { + *o = v.to_be_bytes(); + } + out +} + +/// Lowercase hex of the digest's first `digits` hex digits (at most 64). +pub fn sha256_hex(data: &[u8], digits: usize) -> String { + let mut s = String::with_capacity(64); + for b in sha256(data) { + s.push_str(&format!("{b:02x}")); + } + s.truncate(digits.min(64)); + s +} diff --git a/native/crates/fsh-io/Cargo.toml b/native/crates/fsh-io/Cargo.toml index 45451a0a..88328985 100644 --- a/native/crates/fsh-io/Cargo.toml +++ b/native/crates/fsh-io/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-io" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false @@ -9,3 +9,9 @@ publish = false fsh-core = { path = "../fsh-core" } fsh-scene = { path = "../fsh-scene" } serde_json = "1" +roxmltree = "0.21" +bevy_mikktspace = "1" +zune-jpeg = "0.5" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +ufbx = "0.11" diff --git a/native/crates/fsh-io/src/clean.rs b/native/crates/fsh-io/src/clean.rs index 20c66dfd..65fd7f71 100644 --- a/native/crates/fsh-io/src/clean.rs +++ b/native/crates/fsh-io/src/clean.rs @@ -1,7 +1,8 @@ use crate::error::{IoError, Result}; use crate::raw::{RawMesh, RawScene, UpAxis}; use crate::watch::{Stage, Watch}; -use fsh_core::{Aabb, LengthUnit, Mat4, Vec3}; +use crate::tangents::mikktspace; +use fsh_core::{Aabb, LengthUnit, Mat4, Vec3, Vec4}; use std::collections::HashMap; /// Choices for the clean-up pass. @@ -17,6 +18,8 @@ pub struct CleanOptions { pub weld: bool, /// Fill normals for meshes that have none. pub generate_normals: bool, + /// Fill MikkTSpace tangents for meshes with UVs and normals but no tangents. + pub generate_tangents: bool, /// Replace duplicate meshes by instances of one mesh. pub detect_instances: bool, /// Lift the model so its lowest point is at height 0. @@ -33,6 +36,7 @@ impl Default for CleanOptions { smoothing_angle_deg: 30.0, weld: true, generate_normals: true, + generate_tangents: true, detect_instances: true, stand_on_floor: true, centre: false, @@ -51,18 +55,71 @@ pub struct CleanReport { pub unused_vertices_removed: usize, /// Meshes that received generated normals. pub meshes_given_normals: usize, + /// Meshes that received generated tangents. + pub meshes_given_tangents: usize, + /// Meshes whose vertex colours were all white and were dropped. + pub white_colours_dropped: usize, + /// Meshes that keep vertex colours (their parts are flagged with [`crate::VERTEX_COLOURS_KEY`]). + pub meshes_with_vertex_colours: usize, /// Meshes replaced by an instance of an equal mesh. pub instances_found: usize, + /// Of those, instances that are rotated or mirrored copies rather than moved ones. + pub instances_turned: usize, /// Unit applied. pub unit: LengthUnit, /// True when the unit came from the bounding-box guess. pub unit_guessed: bool, + /// Unit the file declares, if any (applied unless an option overrode it). + pub unit_declared: Option<LengthUnit>, + /// How sure the unit choice is, 0..1: 1 when given or declared, lower near a guess threshold. + pub unit_confidence: f32, + /// Units worth offering when asking, most likely first (the applied unit included). + pub unit_candidates: Vec<LengthUnit>, /// Up axis that was turned to Y. pub up_axis: UpAxis, /// Reader warnings followed by clean-up warnings. pub warnings: Vec<String>, } +/// A unit chosen from a model's size when the file does not say. +#[derive(Clone, Debug, PartialEq)] +pub struct UnitGuess { + /// The unit the rule picks: diagonal under 0.5 is metres, under 50 centimetres, else millimetres. + pub unit: LengthUnit, + /// 0.5 at a threshold, rising to 0.95 one decade or more away from it. + pub confidence: f32, + /// Units that give a plausible object size (5 mm to 20 m), closest to a 25 cm object first; `unit` is always in. + pub candidates: Vec<LengthUnit>, +} + +/// Guesses the unit of a model from its bounding-box diagonal in file units. +pub fn guess_unit(diagonal: f32) -> UnitGuess { + let d = diagonal as f64; + if !d.is_finite() || d <= 0.0 { + return UnitGuess { unit: LengthUnit::Metre, confidence: 0.0, candidates: vec![LengthUnit::Metre] }; + } + let unit = if d < 0.5 { + LengthUnit::Metre + } else if d < 50.0 { + LengthUnit::Centimetre + } else { + LengthUnit::Millimetre + }; + let decades = [0.5f64, 50.0].iter().map(|t| (d / t).log10().abs()).fold(f64::INFINITY, f64::min); + let confidence = (0.5 + 0.45 * decades.min(1.0)) as f32; + let all = [LengthUnit::Millimetre, LengthUnit::Centimetre, LengthUnit::Inch, LengthUnit::Foot, LengthUnit::Metre]; + let mut scored: Vec<(f64, LengthUnit)> = all + .iter() + .map(|&u| (d * u.to_metres(), u)) + .filter(|(m, u)| (0.005..=20.0).contains(m) || *u == unit) + .map(|(m, u)| ((m / 0.25).log10().abs(), u)) + .collect(); + scored.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut candidates: Vec<LengthUnit> = vec![unit]; + candidates.extend(scored.into_iter().map(|(_, u)| u).filter(|u| *u != unit)); + UnitGuess { unit, confidence, candidates } +} + fn bad(msg: String) -> IoError { IoError::InvalidData(msg) } @@ -72,46 +129,75 @@ pub fn clean(scene: &mut RawScene, opts: &CleanOptions, watch: &Watch) -> Result let mut rep = CleanReport { warnings: std::mem::take(&mut scene.warnings), ..Default::default() }; scene.add_nodes_for_loose_meshes(); validate(scene, &mut rep, watch)?; + for m in &mut scene.meshes { + if m.colours.is_empty() { + continue; + } + if m.colours.iter().all(|c| c.x >= 0.999 && c.y >= 0.999 && c.z >= 0.999 && c.w >= 0.999) { + m.colours = Vec::new(); + rep.white_colours_dropped += 1; + } else { + rep.meshes_with_vertex_colours += 1; + } + } + let mut tans = std::mem::take(&mut scene.tangents); + tans.resize(scene.meshes.len(), Vec::new()); + for (m, t) in scene.meshes.iter().zip(tans.iter_mut()) { + if !t.is_empty() && (t.len() != m.positions.len() || m.normals.is_empty() || t.iter().any(|v| !v.is_finite())) { + rep.warnings.push(format!("{:?}: tangents did not match the vertices and were regenerated", m.name)); + t.clear(); + } + } let n = scene.meshes.len().max(1); if opts.weld { - for i in 0..scene.meshes.len() { + for (i, (m, t)) in scene.meshes.iter_mut().zip(tans.iter_mut()).enumerate() { watch.step(Stage::Welding, i as f32 / n as f32)?; - let (welded, unused) = weld(&mut scene.meshes[i]); + let (welded, unused) = weld(m, t, watch)?; rep.vertices_welded += welded; rep.unused_vertices_removed += unused; } } if opts.generate_normals { let cos = opts.smoothing_angle_deg.clamp(0.0, 180.0).to_radians().cos(); - for i in 0..scene.meshes.len() { + for (i, (m, t)) in scene.meshes.iter_mut().zip(tans.iter_mut()).enumerate() { watch.step(Stage::Normals, i as f32 / n as f32)?; - let m = &mut scene.meshes[i]; if m.normals.is_empty() && !m.indices.is_empty() { - smooth_normals(m, cos); + smooth_normals(m, cos, watch)?; + t.clear(); rep.meshes_given_normals += 1; } } } + if opts.generate_tangents { + for (i, (m, t)) in scene.meshes.iter_mut().zip(tans.iter_mut()).enumerate() { + watch.step(Stage::Tangents, i as f32 / n as f32)?; + if t.is_empty() && !m.uvs.is_empty() && !m.normals.is_empty() && !m.indices.is_empty() { + *t = mikktspace(m); + rep.meshes_given_tangents += 1; + } + } + } + scene.tangents = tans; if opts.detect_instances { - rep.instances_found = find_instances(scene, watch)?; + rep.instances_found = find_instances(scene, watch, &mut rep.instances_turned)?; } watch.step(Stage::Placing, 0.0)?; let declared = scene.unit.filter(|u| *u != LengthUnit::Unspecified); + rep.unit_declared = declared; let (unit, guessed) = match (opts.unit, declared) { (Some(u), _) => (u, false), (None, Some(u)) => (u, false), (None, None) => { - let d = world_bounds(scene).diagonal().length(); - let u = if !d.is_finite() || d < 0.5 { - LengthUnit::Metre - } else if d < 50.0 { - LengthUnit::Centimetre - } else { - LengthUnit::Millimetre - }; - (u, true) + let g = guess_unit(world_bounds(scene).diagonal().length()); + rep.unit_confidence = g.confidence; + rep.unit_candidates = g.candidates; + (g.unit, true) } }; + if !guessed { + rep.unit_confidence = 1.0; + rep.unit_candidates = vec![unit]; + } rep.unit = unit; rep.unit_guessed = guessed; if guessed { @@ -131,8 +217,14 @@ pub fn clean(scene: &mut RawScene, opts: &CleanOptions, watch: &Watch) -> Result for nrm in &mut m.normals { *nrm = r.transform_vector(*nrm).normalize_or(Vec3::Y); } + } + for t in scene.tangents.iter_mut().flatten() { + let v = r.transform_vector(Vec3::new(t.x, t.y, t.z)); + *t = Vec4::new(v.x, v.y, v.z, t.w); + } + for m in &mut scene.meshes { if let Some((_, off)) = &mut m.instance_of { - *off = c.transform_vector(*off); + *off = c * *off * c_inv; } } for node in &mut scene.nodes { @@ -179,6 +271,10 @@ fn validate(scene: &mut RawScene, rep: &mut CleanReport, watch: &Watch) -> Resul for mat in &mut scene.materials { mat.textures.retain(|&t| t < ntex); } + scene.extras.truncate(nmat); + for x in &mut scene.extras { + x.slots.retain(|s| s.texture < ntex && s.input.slottable()); + } for (mi, m) in scene.meshes.iter_mut().enumerate() { watch.step(Stage::Validating, mi as f32 / nm.max(1) as f32)?; let n = m.positions.len(); @@ -211,7 +307,8 @@ fn validate(scene: &mut RawScene, rep: &mut CleanReport, watch: &Watch) -> Resul let before = m.indices.len() / 3; let pos = &m.positions; let mut kept = Vec::with_capacity(m.indices.len()); - for t in m.indices.as_chunks::<3>().0 { + for (k, t) in m.indices.as_chunks::<3>().0.iter().enumerate() { + watch.poll(k)?; let (a, b, c) = (t[0], t[1], t[2]); if a == b || b == c || a == c { continue; @@ -240,7 +337,7 @@ fn fnv(h: u64, v: u32) -> u64 { h } -fn vertex_key(m: &RawMesh, v: usize, out: &mut Vec<u32>) { +fn vertex_key(m: &RawMesh, t: &[Vec4], v: usize, out: &mut Vec<u32>) { out.clear(); let p = m.positions[v]; out.extend_from_slice(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]); @@ -253,9 +350,12 @@ fn vertex_key(m: &RawMesh, v: usize, out: &mut Vec<u32>) { if let Some(c) = m.colours.get(v) { out.extend_from_slice(&[c.x.to_bits(), c.y.to_bits(), c.z.to_bits(), c.w.to_bits()]); } + if let Some(c) = t.get(v) { + out.extend_from_slice(&[c.x.to_bits(), c.y.to_bits(), c.z.to_bits(), c.w.to_bits()]); + } } -fn remap(m: &mut RawMesh, order: &[u32]) { +pub(crate) fn remap(m: &mut RawMesh, order: &[u32]) { m.positions = order.iter().map(|&o| m.positions[o as usize]).collect(); if !m.normals.is_empty() { m.normals = order.iter().map(|&o| m.normals[o as usize]).collect(); @@ -268,10 +368,10 @@ fn remap(m: &mut RawMesh, order: &[u32]) { } } -fn weld(m: &mut RawMesh) -> (usize, usize) { +fn weld(m: &mut RawMesh, t: &mut Vec<Vec4>, watch: &Watch) -> Result<(usize, usize)> { let n = m.positions.len(); if n == 0 { - return (0, 0); + return Ok((0, 0)); } let mut used = vec![false; n]; for &i in &m.indices { @@ -285,10 +385,11 @@ fn weld(m: &mut RawMesh) -> (usize, usize) { let mut order: Vec<u32> = Vec::new(); let mut key = Vec::new(); for v in 0..n { + watch.poll(v)?; if !used[v] { continue; } - vertex_key(m, v, &mut key); + vertex_key(m, t, v, &mut key); let h = key.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| fnv(h, x)); let mut found = u32::MAX; let mut cur = heads.get(&h).copied().unwrap_or(u32::MAX); @@ -313,10 +414,16 @@ fn weld(m: &mut RawMesh) -> (usize, usize) { *i = new_of[*i as usize]; } remap(m, &order); - (welded, unused) + if !t.is_empty() { + *t = order.iter().map(|&o| t[o as usize]).collect(); + } + Ok((welded, unused)) } -fn smooth_normals(m: &mut RawMesh, cos_limit: f32) { +const BUSY_VERTEX: usize = 256; +const MAX_CLUSTERS: usize = 64; + +fn smooth_normals(m: &mut RawMesh, cos_limit: f32, watch: &Watch) -> Result<()> { let tris = m.indices.len() / 3; let mut face = Vec::with_capacity(tris); let mut unit = Vec::with_capacity(tris); @@ -351,22 +458,58 @@ fn smooth_normals(m: &mut RawMesh, cos_limit: f32) { inc[fill[p] as usize] = (k / 3) as u32; fill[p] += 1; } + let mut busy: HashMap<usize, Vec<(Vec3, Vec3)>> = HashMap::new(); + for p in 0..np { + let list = &inc[start[p] as usize..start[p + 1] as usize]; + if list.len() <= BUSY_VERTEX { + continue; + } + watch.poll(0)?; + let mut clusters: Vec<(Vec3, Vec3)> = Vec::new(); + let mut last = u32::MAX; + for &g in list { + if g == last { + continue; + } + last = g; + let (u, f) = (unit[g as usize], face[g as usize]); + let near = clusters.iter().position(|c| c.0.dot(u) >= 0.9999); + match near { + Some(i) => clusters[i].1 += f, + None if clusters.len() < MAX_CLUSTERS => clusters.push((u, f)), + None => { + let best = (0..clusters.len()).max_by(|&a, &b| clusters[a].0.dot(u).total_cmp(&clusters[b].0.dot(u))).unwrap_or(0); + clusters[best].1 += f; + } + } + } + busy.insert(p, clusters); + } let mut map: HashMap<(u32, [u32; 3]), u32> = HashMap::new(); let mut order: Vec<u32> = Vec::new(); let mut normals: Vec<Vec3> = Vec::new(); let mut new_idx = Vec::with_capacity(m.indices.len()); for (k, &v) in m.indices.iter().enumerate() { + watch.poll(k)?; let t = k / 3; let p = pid[v as usize] as usize; let mut sum = Vec3::ZERO; - let mut last = u32::MAX; - for &g in &inc[start[p] as usize..start[p + 1] as usize] { - if g == last { - continue; + if let Some(clusters) = busy.get(&p) { + for c in clusters { + if unit[t].dot(c.0) >= cos_limit { + sum += c.1; + } } - last = g; - if unit[t].dot(unit[g as usize]) >= cos_limit { - sum += face[g as usize]; + } else { + let mut last = u32::MAX; + for &g in &inc[start[p] as usize..start[p + 1] as usize] { + if g == last { + continue; + } + last = g; + if unit[t].dot(unit[g as usize]) >= cos_limit { + sum += face[g as usize]; + } } } let n = sum.normalize_or(unit[t]); @@ -383,20 +526,41 @@ fn smooth_normals(m: &mut RawMesh, cos_limit: f32) { m.normals = Vec::new(); remap(m, &order); m.normals = normals; + Ok(()) } -fn mesh_hash(m: &RawMesh) -> u64 { +fn mesh_hash(m: &RawMesh, indices: &[u32]) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; h = fnv(h, m.positions.len() as u32); h = fnv(h, m.normals.len() as u32); h = fnv(h, m.uvs.len() as u32); h = fnv(h, m.colours.len() as u32); - for &i in &m.indices { + for &i in indices { h = fnv(h, i); } h } +/// Vertices relabelled by first appearance, reading each triangle as written or with its winding reversed; +/// returns the relabelled index list and, for each new label, the old vertex. +fn canonical(indices: &[u32], vertices: usize, flip: bool) -> (Vec<u32>, Vec<u32>) { + let mut label = vec![u32::MAX; vertices]; + let mut order = Vec::with_capacity(vertices); + let mut out = Vec::with_capacity(indices.len()); + for t in indices.as_chunks::<3>().0 { + let t = if flip { [t[0], t[2], t[1]] } else { *t }; + for v in t { + let l = &mut label[v as usize]; + if *l == u32::MAX { + *l = order.len() as u32; + order.push(v); + } + out.push(*l); + } + } + (out, order) +} + fn centroid64(m: &RawMesh) -> [f64; 3] { let mut c = [0.0f64; 3]; for p in &m.positions { @@ -408,7 +572,124 @@ fn centroid64(m: &RawMesh) -> [f64; 3] { [c[0] / n, c[1] / n, c[2] / n] } -fn same_shape(a: &RawMesh, b: &RawMesh) -> Option<Vec3> { +type D3 = [f64; 3]; + +fn sub(a: D3, b: D3) -> D3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn dot(a: D3, b: D3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: D3, b: D3) -> D3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn unit(a: D3) -> Option<D3> { + let l = dot(a, a).sqrt(); + (l > 0.0 && l.is_finite()).then(|| [a[0] / l, a[1] / l, a[2] / l]) +} + +fn d3(p: Vec3) -> D3 { + [p.x as f64, p.y as f64, p.z as f64] +} + +fn frame_vertices(a: &[Vec3], c: D3) -> Option<[usize; 3]> { + let far = |from: D3| { + a.iter().enumerate().map(|(i, p)| (dot(sub(d3(*p), from), sub(d3(*p), from)), i)).max_by(|x, y| x.0.total_cmp(&y.0)).map(|x| x.1) + }; + let i0 = far(c)?; + let i1 = far(d3(a[i0]))?; + let e = sub(d3(a[i1]), d3(a[i0])); + let i2 = a + .iter() + .enumerate() + .map(|(i, p)| { + let x = cross(e, sub(d3(*p), d3(a[i0]))); + (dot(x, x), i) + }) + .max_by(|x, y| x.0.total_cmp(&y.0))? + .1; + let span = dot(e, e); + let x = cross(e, sub(d3(a[i2]), d3(a[i0]))); + (span > 0.0 && dot(x, x) > 1.0e-12 * span * span).then_some([i0, i1, i2]) +} + +fn basis(p: &[Vec3], f: [usize; 3]) -> Option<[D3; 3]> { + let u = unit(sub(d3(p[f[1]]), d3(p[f[0]])))?; + let w = unit(cross(u, sub(d3(p[f[2]]), d3(p[f[0]]))))?; + Some([u, cross(w, u), w]) +} + +fn rigid_candidates(a: &RawMesh, b: &RawMesh, ca: D3) -> Vec<[D3; 3]> { + let Some(f) = frame_vertices(&a.positions, ca) else { return Vec::new() }; + let (Some(fa), Some(fb)) = (basis(&a.positions, f), basis(&b.positions, f)) else { return Vec::new() }; + let rot = |fb: [D3; 3]| -> [D3; 3] { + let mut r = [[0.0; 3]; 3]; + for (i, row) in r.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = (0..3).map(|k| fb[k][i] * fa[k][j]).sum(); + } + } + r + }; + let mirrored = [fb[0], fb[1], [-fb[2][0], -fb[2][1], -fb[2][2]]]; + vec![rot(fb), rot(mirrored)] +} + +fn apply(r: &[D3; 3], v: D3) -> D3 { + [dot(r[0], v), dot(r[1], v), dot(r[2], v)] +} + +fn same_shape(a: &RawMesh, b: &RawMesh, flipped: bool) -> Option<(Mat4, bool)> { + if a.indices != b.indices + || a.positions.len() != b.positions.len() + || a.normals.len() != b.normals.len() + || a.uvs != b.uvs + || a.colours != b.colours + { + return None; + } + let (ca, cb) = (centroid64(a), centroid64(b)); + let size = Aabb::from_points(&a.positions).diagonal().length() as f64; + let far = ca.iter().chain(cb.iter()).fold(0.0f64, |m, v| m.max(v.abs())); + if !flipped { + if let Some(off) = translated_copy(a, b, ca, cb, size, far) { + return Some((Mat4::translation(off), false)); + } + } + let tol = 1.0e-5 * size + 2.0e-6 * far + 1.0e-9; + 'cand: for (k, r) in rigid_candidates(a, b, ca).into_iter().enumerate() { + if flipped != (k == 1) { + continue; + } + for (pa, pb) in a.positions.iter().zip(&b.positions) { + let d = sub(apply(&r, sub(d3(*pa), ca)), sub(d3(*pb), cb)); + if d.iter().any(|x| x.abs() > tol) { + continue 'cand; + } + } + for (na, nb) in a.normals.iter().zip(&b.normals) { + let d = sub(apply(&r, d3(*na)), d3(*nb)); + if d.iter().any(|x| x.abs() > 1.0e-3) { + continue 'cand; + } + } + let t = sub(cb, apply(&r, ca)); + let f = |v: f64| v as f32; + let m = Mat4::from_rows([ + [f(r[0][0]), f(r[0][1]), f(r[0][2]), f(t[0])], + [f(r[1][0]), f(r[1][1]), f(r[1][2]), f(t[1])], + [f(r[2][0]), f(r[2][1]), f(r[2][2]), f(t[2])], + [0.0, 0.0, 0.0, 1.0], + ]); + return Some((m, true)); + } + None +} + +fn translated_copy(a: &RawMesh, b: &RawMesh, ca: D3, cb: D3, size: f64, far: f64) -> Option<Vec3> { if a.indices != b.indices || a.positions.len() != b.positions.len() || a.normals.len() != b.normals.len() @@ -420,10 +701,6 @@ fn same_shape(a: &RawMesh, b: &RawMesh) -> Option<Vec3> { if a.uvs != b.uvs || a.colours != b.colours { return None; } - let (ca, cb) = (centroid64(a), centroid64(b)); - let ba = Aabb::from_points(&a.positions); - let size = ba.diagonal().length() as f64; - let far = ca.iter().chain(cb.iter()).fold(0.0f64, |m, v| m.max(v.abs())); let tol = 1.0e-6 * size + 1.0e-6 * far + 1.0e-9; for (pa, pb) in a.positions.iter().zip(&b.positions) { let d = [ @@ -443,24 +720,61 @@ fn same_shape(a: &RawMesh, b: &RawMesh) -> Option<Vec3> { Some(Vec3::new((cb[0] - ca[0]) as f32, (cb[1] - ca[1]) as f32, (cb[2] - ca[2]) as f32)) } -fn find_instances(scene: &mut RawScene, watch: &Watch) -> Result<usize> { +fn find_instances(scene: &mut RawScene, watch: &Watch, rotated: &mut usize) -> Result<usize> { let mut buckets: HashMap<u64, Vec<usize>> = HashMap::new(); let mut found = 0; let n = scene.meshes.len(); for j in 0..n { - watch.step(Stage::Instancing, j as f32 / n.max(1) as f32)?; + watch.step(Stage::Instancing, j as f32 / n.max(1) as f32 * 0.3)?; + let m = &mut scene.meshes[j]; + if m.instance_of.is_some() || m.indices.is_empty() { + continue; + } + let (idx, order) = canonical(&m.indices, m.positions.len(), false); + m.indices = idx; + remap(m, &order); + if let Some(t) = scene.tangents.get_mut(j).filter(|t| !t.is_empty()) { + *t = order.iter().map(|&o| t[o as usize]).collect(); + } + } + for j in 0..n { + watch.step(Stage::Instancing, 0.3 + j as f32 / n.max(1) as f32 * 0.7)?; if scene.meshes[j].instance_of.is_some() || scene.meshes[j].indices.is_empty() { continue; } - let h = mesh_hash(&scene.meshes[j]); - let list = buckets.entry(h).or_default(); + let h = mesh_hash(&scene.meshes[j], &scene.meshes[j].indices); + let same_tangents = |i: usize| scene.tangents.get(i).map(Vec::len) == scene.tangents.get(j).map(Vec::len); let mut hit = None; - for &i in list.iter() { - if let Some(off) = same_shape(&scene.meshes[i], &scene.meshes[j]) { - hit = Some((i, off)); - break; + for &i in buckets.get(&h).map(Vec::as_slice).unwrap_or(&[]) { + if same_tangents(i) { + if let Some(found) = same_shape(&scene.meshes[i], &scene.meshes[j], false) { + hit = Some((i, found)); + break; + } } } + if hit.is_none() { + let mj = &scene.meshes[j]; + let (idx, order) = canonical(&mj.indices, mj.positions.len(), true); + let hf = mesh_hash(mj, &idx); + if let Some(list) = buckets.get(&hf) { + let mut flipped = mj.clone(); + flipped.indices = idx; + remap(&mut flipped, &order); + for &i in list { + if same_tangents(i) { + if let Some(found) = same_shape(&scene.meshes[i], &flipped, true) { + hit = Some((i, found)); + break; + } + } + } + } + } + if let Some((_, (_, true))) = hit { + *rotated += 1; + } + let hit = hit.map(|(i, (off, _))| (i, off)); match hit { Some((i, off)) => { let m = &mut scene.meshes[j]; @@ -470,19 +784,22 @@ fn find_instances(scene: &mut RawScene, watch: &Watch) -> Result<usize> { m.uvs = Vec::new(); m.colours = Vec::new(); m.indices = Vec::new(); + if let Some(t) = scene.tangents.get_mut(j) { + *t = Vec::new(); + } found += 1; } - None => list.push(j), + None => buckets.entry(h).or_default().push(j), } } Ok(found) } /// Local bounds of a mesh, following an instance link. -pub(crate) fn mesh_bounds(scene: &RawScene, mi: usize) -> (Aabb, Vec3) { +pub(crate) fn mesh_bounds(scene: &RawScene, mi: usize) -> (Aabb, Mat4) { match scene.meshes.get(mi).and_then(|m| m.instance_of) { - Some((src, off)) => (Aabb::from_points(&scene.meshes[src].positions), off), - None => (scene.meshes.get(mi).map(|m| Aabb::from_points(&m.positions)).unwrap_or(Aabb::EMPTY), Vec3::ZERO), + Some((src, off)) => (scene.meshes.get(src).map(|m| Aabb::from_points(&m.positions)).unwrap_or(Aabb::EMPTY), off), + None => (scene.meshes.get(mi).map(|m| Aabb::from_points(&m.positions)).unwrap_or(Aabb::EMPTY), Mat4::IDENTITY), } } @@ -499,9 +816,20 @@ pub fn world_bounds(scene: &RawScene) -> Aabb { if b.is_empty() { continue; } - let m = w * Mat4::translation(off); - for k in 0..8 { - out = out.union_point(m.transform_point(b.corner(k))); + let m = w * off; + let axis_aligned = (0..3).all(|c| (0..3).filter(|&r| m.m[r][c].abs() > 1.0e-7).count() <= 1); + let src = scene.meshes[mi].instance_of.map(|(s, _)| s).unwrap_or(mi); + match scene.meshes.get(src).filter(|_| !axis_aligned) { + Some(sm) => { + for p in &sm.positions { + out = out.union_point(m.transform_point(*p)); + } + } + None => { + for k in 0..8 { + out = out.union_point(m.transform_point(b.corner(k))); + } + } } } } diff --git a/native/crates/fsh-io/src/convert.rs b/native/crates/fsh-io/src/convert.rs index 6ca3a5f4..3ac231c2 100644 --- a/native/crates/fsh-io/src/convert.rs +++ b/native/crates/fsh-io/src/convert.rs @@ -1,16 +1,103 @@ use crate::error::Result; -use crate::raw::{RawMaterial, RawScene}; +use crate::raw::{RawMaterial, RawMaterialExtra, RawScene}; use crate::watch::{Stage, Watch}; use fsh_core::{DocKey, MaterialKey, Mat4, MeshKey, NodeId, Rgb, TextureKey, Vec3}; use fsh_scene::{ - Command, Document, Import, ImportMaterial, ImportMesh, ImportNode, ImportPayload, ImportTexture, Material, Mesh, - Node, NodeKind, SceneError, SurfaceParams, TextureRef, Trs, + Command, Document, GraphNode, GraphOp, Import, ImportMaterial, ImportMesh, ImportNode, ImportPayload, ImportTexture, + Material, MaterialGraph, MaterialInput, MathOp, Mesh, Node, NodeKind, SceneError, SocketValue, SurfaceParams, + TextureRef, TextureSlot, Trs, }; use std::sync::Arc; +/// Opacity of a masked material (glTF alphaMode MASK) as a graph: the opacity slot's texture alpha times `factor`, +/// fully opaque from `cutoff` up and fully clear below it (`clamp((a - cutoff + 1e-4) * 1e4, 0, 1)`). +fn cutoff_graph(slot: &TextureSlot, factor: f32, cutoff: f32) -> MaterialGraph { + let mut g = MaterialGraph::new(); + let tex = g.add(GraphNode::new(GraphOp::Texture { + texture: Some(slot.texture), + projection: slot.projection, + transform: slot.transform, + wrap: slot.wrap, + filter: slot.filter, + colour_space: slot.colour_space, + fallback: slot.fallback.unwrap_or([1.0; 4]), + })); + let math = |op, b: f32| GraphNode::new(GraphOp::Math { op }).with("b", SocketValue::Float(b)); + let scaled = g.add(math(MathOp::Multiply, factor)); + let shifted = g.add(math(MathOp::Subtract, cutoff - 1.0e-4)); + let steep = g.add(math(MathOp::Multiply, 1.0e4)); + let step = g.add(math(MathOp::Clamp, 0.0).with("c", SocketValue::Float(1.0))); + g.link(tex, "alpha", scaled, "a"); + g.link(scaled, "value", shifted, "a"); + g.link(shifted, "value", steep, "a"); + g.link(steep, "value", step, "a"); + g.output(MaterialInput::GeometryOpacity, step, "value"); + for (n, x) in [(scaled, 200.0), (shifted, 400.0), (steep, 600.0), (step, 800.0)] { + g.nodes.entry(n).and_modify(|node| node.position = [x, 0.0]); + } + g +} + /// Luminance in nits given to an emissive colour of 1 (glTF emissiveFactor times strength). pub const EMISSIVE_NITS_PER_UNIT: f32 = 100.0; +/// Node metadata key set on parts whose mesh carries vertex colours; its value says how the material uses them. +pub const VERTEX_COLOURS_KEY: &str = "material.vertex_colours"; + +/// The value of [`VERTEX_COLOURS_KEY`]: the vertex colour multiplies the material's base colour. +pub const VERTEX_COLOURS_MULTIPLY: &str = "multiply"; + +/// Node metadata key set on parts whose material is masked (glTF alphaMode MASK): the alpha cutoff, kept for a +/// later hard-cutoff opcode while coverage stays soft. +pub const ALPHA_CUTOFF_KEY: &str = "material.alpha_cutoff"; + +fn flag_colours(node: &mut Node, mi: usize, scene: &RawScene, source: usize) { + if !scene.meshes[source].colours.is_empty() { + node.metadata.insert(VERTEX_COLOURS_KEY.to_string(), VERTEX_COLOURS_MULTIPLY.to_string()); + } + if let Some(c) = scene.meshes[mi].material.and_then(|m| scene.extras.get(m)).and_then(|x| x.alpha_cutoff) { + node.metadata.insert(ALPHA_CUTOFF_KEY.to_string(), format!("{c}")); + } +} + +fn apply_extra(p: &mut SurfaceParams, x: &RawMaterialExtra) { + if let Some(c) = x.specular_colour { + p.specular_color = colour(c); + } + if let Some(v) = x.coat_ior.filter(|v| v.is_finite()) { + p.coat_ior = v.clamp(1.0, 3.0); + } + if let Some((c, r)) = x.sheen { + let peak = c.iter().copied().filter(|v| v.is_finite()).fold(0.0f32, f32::max); + if peak > 0.0 { + p.fuzz_weight = unit(peak, 0.0); + p.fuzz_color = colour(c.map(|v| v / peak)); + p.fuzz_roughness = unit(r, 0.5); + } + } + if let Some((c, d)) = x.attenuation { + if d.is_finite() && d > 0.0 { + p.transmission_color = colour(c); + p.transmission_depth = d; + } + } + if let Some(t) = x.thin_walled { + p.geometry_thin_walled = t; + } + if let Some([w, ior, thick]) = x.thin_film { + p.thin_film_weight = unit(w, 0.0); + p.thin_film_ior = if ior.is_finite() { ior.clamp(1.0, 3.0) } else { 1.3 }; + p.thin_film_thickness = if thick.is_finite() { thick.clamp(0.0, 10.0) } else { 0.4 }; + } + if let Some(v) = x.abbe.filter(|v| v.is_finite() && *v > 0.0) { + p.transmission_dispersion_scale = 1.0; + p.transmission_dispersion_abbe_number = v.clamp(1.0, 200.0); + } + if let Some(a) = x.anisotropy { + p.specular_roughness_anisotropy = unit(a, 0.0); + } +} + /// Where and how an import lands in the document. #[derive(Clone, Debug, Default)] pub struct ImportOptions { @@ -94,10 +181,10 @@ pub fn to_import_command(scene: &RawScene, doc: &Document, opts: &ImportOptions, } } let nm = scene.meshes.len(); - let source = |mi: usize| -> (usize, Vec3) { + let source = |mi: usize| -> (usize, Mat4) { match scene.meshes[mi].instance_of { Some((s, off)) if s < nm => (s, off), - _ => (mi, Vec3::ZERO), + _ => (mi, Mat4::IDENTITY), } }; let drawable = |mi: usize| mi < nm && !scene.meshes[source(mi).0].indices.is_empty(); @@ -137,6 +224,9 @@ pub fn to_import_command(scene: &RawScene, doc: &Document, opts: &ImportOptions, mesh.normals = r.normals.clone(); mesh.uvs = r.uvs.clone(); mesh.colours = r.colours.clone(); + if let Some(t) = scene.tangents.get(mi).filter(|t| t.len() == r.positions.len()) { + mesh.tangents = t.clone(); + } mesh.validate()?; let key: MeshKey = keys.next(); mesh_key[mi] = Some(key); @@ -166,8 +256,31 @@ pub fn to_import_command(scene: &RawScene, doc: &Document, opts: &ImportOptions, } let key: MaterialKey = keys.next(); mat_key[i] = Some(key); - let mut material = Material::new(m.name.clone(), type_id(m), surface_params(m)); + let mut params = surface_params(m); + if let Some(x) = scene.extras.get(i) { + apply_extra(&mut params, x); + } + let mut material = Material::new(m.name.clone(), type_id(m), params); material.textures = m.textures.iter().filter_map(|&t| tex_key.get(t).copied().flatten()).collect(); + material.textures.dedup(); + for rs in scene.extras.get(i).map(|x| x.slots.as_slice()).unwrap_or(&[]) { + let Some(key) = tex_key.get(rs.texture).copied().flatten() else { continue }; + if material.slots.contains_key(&rs.input) { + continue; + } + let slot = TextureSlot { texture: key, ..rs.slot.clone() }; + if slot.validate(rs.input).is_ok() { + if !material.textures.contains(&key) { + material.textures.push(key); + } + material.slots.insert(rs.input, slot); + } + } + if let Some(c) = scene.extras.get(i).and_then(|x| x.alpha_cutoff) { + if let Some(slot) = material.slots.remove(&MaterialInput::GeometryOpacity) { + material.graph = Some(Box::new(cutoff_graph(&slot, material.params.geometry_opacity, c))); + } + } payload.materials.push(ImportMaterial { key, material }); } @@ -208,8 +321,9 @@ pub fn to_import_command(scene: &RawScene, doc: &Document, opts: &ImportOptions, if parts.len() == 1 && !has_child[i] { let mi = parts[0]; let (_, off) = source(mi); - let (t, ok) = trs_or_hidden(&(n.transform * Mat4::translation(off))); + let (t, ok) = trs_or_hidden(&(n.transform * off)); let mut node = Node::new(n.name.clone(), part_of(mi)); + flag_colours(&mut node, mi, scene, source(mi).0); node.transform = t; node.visible = ok; node.parent = parent; @@ -229,7 +343,10 @@ pub fn to_import_command(scene: &RawScene, doc: &Document, opts: &ImportOptions, for mi in parts { let (_, off) = source(mi); let mut node = Node::new(scene.meshes[mi].name.clone(), part_of(mi)); - node.transform = Trs::from_translation(off); + flag_colours(&mut node, mi, scene, source(mi).0); + let (t, ok) = trs_or_hidden(&off); + node.transform = t; + node.visible = ok; node.parent = Some(gid); let id: NodeId = keys.next(); payload.nodes.push(ImportNode { id, node }); diff --git a/native/crates/fsh-io/src/family/app.rs b/native/crates/fsh-io/src/family/app.rs new file mode 100644 index 00000000..3a579a66 --- /dev/null +++ b/native/crates/fsh-io/src/family/app.rs @@ -0,0 +1,158 @@ +use crate::deflate; +use serde_json::Value; +use std::path::Path; + +/// A Form app whose exports FormShot receives. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FamilyApp { + /// FormCAD (CAD; GLB, 3MF, STEP, STL, OBJ, PLY). + FormCad, + /// FormSculpt (sculpting; GoF folder with GLB, OBJ, FBX). + FormSculpt, + /// FormSurface (texture painting; map folders and an OBJ). + FormSurface, + /// FormFabric (garments; GLB, OBJ, FBX and GoF entries). + FormFabric, +} + +impl FamilyApp { + /// Every app. + pub const ALL: [FamilyApp; 4] = [FamilyApp::FormCad, FamilyApp::FormSculpt, FamilyApp::FormSurface, FamilyApp::FormFabric]; + + /// Lower-case id as the family writes it ("formsculpt" in gof.json). + pub fn id(self) -> &'static str { + match self { + FamilyApp::FormCad => "formcad", + FamilyApp::FormSculpt => "formsculpt", + FamilyApp::FormSurface => "formsurface", + FamilyApp::FormFabric => "formfabric", + } + } + + /// Display name. + pub fn name(self) -> &'static str { + match self { + FamilyApp::FormCad => "FormCAD", + FamilyApp::FormSculpt => "FormSculpt", + FamilyApp::FormSurface => "FormSurface", + FamilyApp::FormFabric => "FormFabric", + } + } + + /// Parses an id or a display name, ignoring case. + pub fn parse(s: &str) -> Option<FamilyApp> { + let s = s.trim(); + Self::ALL.into_iter().find(|a| a.id().eq_ignore_ascii_case(s) || a.name().eq_ignore_ascii_case(s)) + } +} + +/// What a model file says about the program that wrote it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Origin { + /// The family app, when the file names one. + pub app: Option<FamilyApp>, + /// The writer as the file names it (glTF generator, OBJ first comment, 3MF Application). + pub writer: Option<String>, + /// A title the file carries (FormCAD's glTF extras and 3MF Title). + pub title: Option<String>, + /// The unit the model was designed in, when the file records it apart from its own unit (FormCAD's sourceUnit). + pub design_unit: Option<String>, +} + +fn app_of_writer(writer: &str) -> Option<FamilyApp> { + let w = writer.trim(); + let first = w.split_whitespace().next().unwrap_or(""); + FamilyApp::parse(first) +} + +pub(crate) fn glb_json(bytes: &[u8]) -> Option<Value> { + if bytes.len() < 20 || &bytes[..4] != b"glTF" { + return None; + } + let len = u32::from_le_bytes(bytes[12..16].try_into().ok()?) as usize; + if &bytes[16..20] != b"JSON" || 20 + len > bytes.len() { + return None; + } + serde_json::from_slice(&bytes[20..20 + len]).ok() +} + +fn gltf_origin(json: &Value) -> Origin { + let asset = json.get("asset"); + let writer = asset.and_then(|a| a.get("generator")).and_then(Value::as_str).map(str::to_string); + let extras = asset.and_then(|a| a.get("extras")); + let text = |k: &str| extras.and_then(|e| e.get(k)).and_then(Value::as_str).filter(|s| !s.trim().is_empty()).map(str::to_string); + Origin { app: writer.as_deref().and_then(app_of_writer), writer, title: text("title"), design_unit: text("sourceUnit") } +} + +fn obj_origin(bytes: &[u8]) -> Origin { + let head = String::from_utf8_lossy(&bytes[..bytes.len().min(512)]); + let Some(first) = head.lines().next().and_then(|l| l.strip_prefix('#')) else { return Origin::default() }; + let writer = first.trim().to_string(); + match app_of_writer(&writer) { + Some(app) => Origin { app: Some(app), writer: Some(writer), ..Origin::default() }, + None => Origin::default(), + } +} + +fn zip_member(bytes: &[u8], wanted: &str) -> Option<Vec<u8>> { + let tail = bytes.len().saturating_sub(65_557); + let eocd = (tail..bytes.len().saturating_sub(21)).rev().find(|&i| bytes[i..i + 4] == [0x50, 0x4b, 0x05, 0x06])?; + let u16_at = |i: usize| -> Option<usize> { Some(u16::from_le_bytes(bytes.get(i..i + 2)?.try_into().ok()?) as usize) }; + let u32_at = |i: usize| -> Option<usize> { Some(u32::from_le_bytes(bytes.get(i..i + 4)?.try_into().ok()?) as usize) }; + let count = u16_at(eocd + 10)?; + let mut at = u32_at(eocd + 16)?; + for _ in 0..count { + if bytes.get(at..at + 4)? != [0x50, 0x4b, 0x01, 0x02] { + return None; + } + let method = u16_at(at + 10)?; + let packed = u32_at(at + 20)?; + let size = u32_at(at + 24)?; + let (name_len, extra_len, note_len) = (u16_at(at + 28)?, u16_at(at + 30)?, u16_at(at + 32)?); + let local = u32_at(at + 42)?; + let name = String::from_utf8_lossy(bytes.get(at + 46..at + 46 + name_len)?).to_string(); + at += 46 + name_len + extra_len + note_len; + if !name.trim_start_matches('/').eq_ignore_ascii_case(wanted) || size > 64 << 20 { + continue; + } + let start = local + 30 + u16_at(local + 26)? + u16_at(local + 28)?; + let data = bytes.get(start..start + packed)?; + return match method { + 0 => Some(data.to_vec()), + 8 => deflate::inflate(data, size.max(1)).ok().map(|(out, _)| out), + _ => None, + }; + } + None +} + +fn xml_metadata(xml: &str, name: &str) -> Option<String> { + let key = format!("name=\"{name}\""); + let at = xml.find(&key)?; + let open = at + xml[at..].find('>')? + 1; + let close = open + xml[open..].find("</metadata>")?; + let value = xml[open..close].replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\""); + Some(value.trim().to_string()).filter(|v| !v.is_empty()) +} + +fn threemf_origin(bytes: &[u8]) -> Origin { + let Some(model) = zip_member(bytes, "3D/3dmodel.model") else { return Origin::default() }; + let xml = String::from_utf8_lossy(&model[..model.len().min(1 << 20)]).to_string(); + let writer = xml_metadata(&xml, "Application"); + Origin { app: writer.as_deref().and_then(app_of_writer), title: xml_metadata(&xml, "Title"), writer, design_unit: None } +} + +/// Reads who wrote a model file from its content: the glTF generator and extras, the first comment of an OBJ, the +/// Application metadata of a 3MF. +pub fn origin_of(path: &Path, bytes: &[u8]) -> Origin { + if let Some(json) = glb_json(bytes) { + return gltf_origin(&json); + } + let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); + match ext.as_str() { + "gltf" => serde_json::from_slice::<Value>(bytes).map(|j| gltf_origin(&j)).unwrap_or_default(), + "obj" => obj_origin(bytes), + "3mf" => threemf_origin(bytes), + _ => Origin::default(), + } +} diff --git a/native/crates/fsh-io/src/family/gof.rs b/native/crates/fsh-io/src/family/gof.rs new file mode 100644 index 00000000..a6f65cfb --- /dev/null +++ b/native/crates/fsh-io/src/family/gof.rs @@ -0,0 +1,193 @@ +use super::FamilyApp; +use crate::error::{IoError, Result}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +/// The manifest file name in a GoF folder. +pub const GOF_MANIFEST: &str = "gof.json"; + +/// GoF targets FormShot takes without being named: "any" and its own name. +pub const GOF_TARGETS: [&str; 2] = ["formshot", "any"]; + +const MAX_MANIFEST: u64 = 4 << 20; + +/// One object a sender put in the GoF folder. +#[derive(Clone, Debug, PartialEq)] +pub struct GofEntry { + /// Sender's object id. + pub id: i64, + /// Object name in the sender. + pub name: String, + /// File name inside the folder. + pub file: String, + /// glb, fbx, obj or package. + pub format: String, + /// The app it was sent for (blender, unreal, unity, formsurface, substance, any). + pub target: String, + /// Sender's revision of the object. + pub revision: i64, + /// Vertex count the sender wrote. + pub vertices: u64, + /// Triangle count the sender wrote. + pub triangles: u64, + /// When it was sent, Unix seconds. + pub sent: i64, + /// True when the file is a bridge the sender reads back. + pub returns: bool, + /// Unit of the file: m, cm or scene. + pub units: Option<String>, + /// Sender scene units to file units. + pub scale: Option<f64>, + /// The app that wrote the entry: the entry's own `app`, else the manifest's. + pub app: Option<FamilyApp>, + /// The writer's name as the manifest gives it, when it is not a family app. + pub writer: String, +} + +impl GofEntry { + /// The file's path in `folder`. + pub fn path_in(&self, folder: &Path) -> PathBuf { + folder.join(&self.file) + } + + /// True when FormShot is meant to take it without being named (target any or formshot). + pub fn for_formshot(&self) -> bool { + GOF_TARGETS.contains(&self.target.as_str()) + } + + /// The entry as JSON, with whether its file is present in `folder`. + pub fn to_json(&self, folder: &Path) -> Value { + json!({ + "id": self.id, "name": self.name, "file": self.file, "path": self.path_in(folder).to_string_lossy(), + "present": self.path_in(folder).is_file(), "format": self.format, "target": self.target, + "revision": self.revision, "vertices": self.vertices, "triangles": self.triangles, "sent": self.sent, + "returns": self.returns, "units": self.units, "scale": self.scale, + "app": self.app.map(FamilyApp::id), "app_name": self.app.map(FamilyApp::name).unwrap_or(self.writer.as_str()), + }) + } +} + +/// A GoF folder's manifest. +#[derive(Clone, Debug, PartialEq)] +pub struct GofManifest { + /// The folder. + pub folder: PathBuf, + /// Manifest version (1). + pub gof: i64, + /// The app that wrote the manifest last. + pub app: Option<FamilyApp>, + /// That app's name as written. + pub writer: String, + /// That app's version. + pub version: String, + /// Up axis of the files ("y"). + pub up_axis: String, + /// Sender's real size: millimetres per scene unit, when it has one. + pub mm_per_unit: Option<f64>, + /// Objects, newest last. + pub objects: Vec<GofEntry>, +} + +impl GofManifest { + /// The entry for a file name, or for an id given as text. + pub fn find(&self, item: &str) -> Option<&GofEntry> { + let item = item.trim(); + self.objects + .iter() + .rev() + .find(|e| e.file == item) + .or_else(|| item.parse::<i64>().ok().and_then(|id| self.objects.iter().rev().find(|e| e.id == id))) + .or_else(|| self.objects.iter().rev().find(|e| e.name == item)) + } + + /// The entry FormShot opens when none is named: the newest meant for FormShot whose file is present, else the + /// newest present one that FormShot can read. + pub fn newest(&self) -> Option<&GofEntry> { + let readable = |e: &&GofEntry| e.format != "package" && e.path_in(&self.folder).is_file(); + let newest = |only: bool| self.objects.iter().filter(readable).filter(|e| !only || e.for_formshot()).max_by_key(|e| e.sent); + newest(true).or_else(|| newest(false)) + } + + /// The manifest as JSON. + pub fn to_json(&self) -> Value { + json!({ + "folder": self.folder.to_string_lossy(), "gof": self.gof, "app": self.app.map(FamilyApp::id), + "app_name": self.app.map(FamilyApp::name).unwrap_or(self.writer.as_str()), "version": self.version, + "up_axis": self.up_axis, "mm_per_unit": self.mm_per_unit, + "objects": self.objects.iter().map(|e| e.to_json(&self.folder)).collect::<Vec<_>>(), + }) + } +} + +fn text(v: &Value, k: &str) -> String { + match v.get(k) { + Some(Value::String(s)) => s.clone(), + Some(Value::Number(n)) => n.to_string(), + _ => String::new(), + } +} + +fn int(v: &Value, k: &str) -> i64 { + v.get(k).and_then(|x| x.as_i64().or_else(|| x.as_f64().map(|f| f as i64))).unwrap_or(0) +} + +fn entry(v: &Value, top: Option<FamilyApp>, top_writer: &str) -> Option<GofEntry> { + let file = text(v, "file"); + if file.is_empty() || Path::new(&file).file_name().and_then(|n| n.to_str()) != Some(file.as_str()) { + return None; + } + let own = text(v, "app"); + let app = FamilyApp::parse(&own).or(if own.is_empty() { top } else { None }); + let format = match text(v, "format").to_ascii_lowercase() { + f if f.is_empty() => Path::new(&file).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(), + f => f, + }; + Some(GofEntry { + id: int(v, "id"), + name: Some(text(v, "name")).filter(|n| !n.is_empty()).unwrap_or_else(|| file.clone()), + format, + target: text(v, "target").to_ascii_lowercase(), + revision: int(v, "revision"), + vertices: int(v, "vertices").max(0) as u64, + triangles: int(v, "triangles").max(0) as u64, + sent: int(v, "sent"), + returns: v.get("returns").and_then(Value::as_bool).unwrap_or(false), + units: Some(text(v, "units")).filter(|u| !u.is_empty()), + scale: v.get("scale").and_then(Value::as_f64), + app, + writer: if own.is_empty() { top_writer.to_string() } else { own }, + file, + }) +} + +/// True when `folder` holds a GoF manifest. +pub fn is_gof_folder(folder: &Path) -> bool { + folder.join(GOF_MANIFEST).is_file() +} + +/// Reads a GoF folder's manifest; entries whose file name is not a plain name are skipped. +pub fn read_gof(folder: &Path) -> Result<GofManifest> { + let path = folder.join(GOF_MANIFEST); + let size = std::fs::metadata(&path).map_err(|e| IoError::Io(format!("{}: {e}", path.display())))?.len(); + if size > MAX_MANIFEST { + return Err(IoError::Unsupported(format!("{} is larger than 4 MB", path.display()))); + } + let bytes = std::fs::read(&path)?; + let v: Value = serde_json::from_slice(&bytes).map_err(|e| IoError::Malformed(format!("{GOF_MANIFEST}: {e}")))?; + if !v.is_object() { + return Err(IoError::Malformed(format!("{GOF_MANIFEST} is not an object"))); + } + let writer = text(&v, "app"); + let app = FamilyApp::parse(&writer); + let objects = v.get("objects").and_then(Value::as_array).map(|a| a.iter().filter_map(|o| entry(o, app, &writer)).collect()).unwrap_or_default(); + Ok(GofManifest { + folder: folder.to_path_buf(), + gof: int(&v, "gof"), + app, + writer, + version: text(&v, "version"), + up_axis: Some(text(&v, "up_axis")).filter(|u| !u.is_empty()).unwrap_or_else(|| "y".into()), + mm_per_unit: v.get("mm_per_unit").and_then(Value::as_f64), + objects, + }) +} diff --git a/native/crates/fsh-io/src/family/handoff.rs b/native/crates/fsh-io/src/family/handoff.rs new file mode 100644 index 00000000..24e307c3 --- /dev/null +++ b/native/crates/fsh-io/src/family/handoff.rs @@ -0,0 +1,403 @@ +use super::app::{origin_of, FamilyApp, Origin}; +use super::gof::{is_gof_folder, read_gof, GofEntry, GofManifest}; +use super::maps::{role_name, set_name, template_of, texture_sets, MapRef, MAP_EXTENSIONS}; +use super::surface::{is_formsurface_obj, read_surface, SurfaceExport}; +use crate::error::{IoError, Result}; +use crate::raw::{RawMaterial, RawScene, RawTexture}; +use crate::watch::Watch; +use fsh_core::LengthUnit; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +const CAD_ROOT: &str = "FormCAD Z-up to Y-up"; + +/// What a hand-off is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HandoffKind { + /// One model file. + Model, + /// A FormSurface export folder: maps by role, with or without the painted mesh. + MapFolder, + /// A GoF folder; one of its entries is read. + GofFolder, +} + +impl HandoffKind { + /// Short name. + pub fn as_str(self) -> &'static str { + match self { + HandoffKind::Model => "model", + HandoffKind::MapFolder => "map_folder", + HandoffKind::GofFolder => "gof_folder", + } + } +} + +/// What a file or folder another Form app wrote is, found without reading its geometry. +#[derive(Clone, Debug, PartialEq)] +pub struct Inspection { + /// The path as given, made absolute. + pub path: PathBuf, + /// What it is. + pub kind: HandoffKind, + /// The app that wrote it, when it can be told. + pub app: Option<FamilyApp>, + /// The writer as the file names it. + pub writer: Option<String>, + /// A name for what arrives: the sender's title or object name, else the file or folder name. + pub title: String, + /// The model file that is read, when there is one. + pub model: Option<PathBuf>, + /// The unit the model was designed in, when the file records it apart from its own unit. + pub design_unit: Option<String>, + /// The GoF manifest, for GoF folders and files inside one. + pub gof: Option<GofManifest>, + /// The GoF entry that is read. + pub entry: Option<GofEntry>, + /// The FormSurface export folder. + pub surface: Option<SurfaceExport>, + /// Notes for the person. + pub warnings: Vec<String>, +} + +fn is_map(path: &Path) -> bool { + path.extension().and_then(|e| e.to_str()).is_some_and(|e| MAP_EXTENSIONS.iter().any(|m| e.eq_ignore_ascii_case(m))) +} + +fn name_of(path: &Path) -> String { + path.file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("Hand-off").to_string() +} + +fn absolute(path: &Path) -> PathBuf { + path.canonicalize().unwrap_or_else(|_| if path.is_absolute() { path.to_path_buf() } else { std::env::current_dir().map(|d| d.join(path)).unwrap_or(path.to_path_buf()) }) +} + +fn model_origin(path: &Path) -> Origin { + use std::io::Read; + let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); + let limit: u64 = if matches!(ext.as_str(), "gltf" | "3mf") { 256 << 20 } else { 4 << 20 }; + let mut bytes = Vec::new(); + match std::fs::File::open(path) { + Ok(f) => { + let _ = f.take(limit).read_to_end(&mut bytes); + } + Err(_) => return Origin::default(), + } + origin_of(path, &bytes) +} + +fn inspect_gof(folder: &Path, item: Option<&str>) -> Result<Inspection> { + let gof = read_gof(folder)?; + let entry = match item { + Some(i) => Some(gof.find(i).cloned().ok_or_else(|| IoError::MissingSibling(format!("{i} is not an entry of {}", folder.join("gof.json").display())))?), + None => gof.newest().cloned(), + }; + let mut warnings = Vec::new(); + let model = match &entry { + Some(e) if e.format == "package" => { + warnings.push(format!("{} is a Substance package; FormShot reads the GoF entries that are model files", e.file)); + None + } + Some(e) if !e.path_in(folder).is_file() => { + warnings.push(format!("{} is listed in gof.json but is not in the folder", e.file)); + None + } + Some(e) => Some(e.path_in(folder)), + None => { + warnings.push("the GoF folder has no entry FormShot can read".into()); + None + } + }; + let origin = model.as_deref().map(model_origin).unwrap_or_default(); + let app = origin.app.or(entry.as_ref().and_then(|e| e.app)).or(gof.app); + let title = entry.as_ref().map(|e| e.name.clone()).unwrap_or_else(|| name_of(folder)); + Ok(Inspection { + path: folder.to_path_buf(), + kind: HandoffKind::GofFolder, + app, + writer: origin.writer.or_else(|| Some(gof.writer.clone()).filter(|w| !w.is_empty())), + title, + model, + design_unit: None, + gof: Some(gof), + entry, + surface: None, + warnings, + }) +} + +fn inspect_surface(surface: SurfaceExport) -> Inspection { + let mut warnings = Vec::new(); + if surface.mesh.is_none() { + warnings.push("no mesh travels with these maps; they arrive as materials only".into()); + } + Inspection { + path: surface.folder.clone(), + kind: HandoffKind::MapFolder, + app: Some(FamilyApp::FormSurface), + writer: Some("FormSurface".into()), + title: surface.stem.clone(), + model: surface.mesh.clone(), + design_unit: None, + gof: None, + entry: None, + surface: Some(surface), + warnings, + } +} + +/// Finds out what `path` is: a GoF folder (with `item` naming an entry by file, id or name; the newest meant for +/// FormShot otherwise), a FormSurface export folder or one of its files, or a model file another Form app wrote. +pub fn inspect(path: &Path, item: Option<&str>) -> Result<Inspection> { + if !path.exists() { + return Err(IoError::Io(format!("{} does not exist", path.display()))); + } + let path = absolute(path); + if path.is_dir() { + if is_gof_folder(&path) { + return inspect_gof(&path, item); + } + return read_surface(&path).map(inspect_surface).ok_or_else(|| { + IoError::Unsupported(format!("{} is neither a GoF folder nor a FormSurface export folder", path.display())) + }); + } + let parent = path.parent().map(Path::to_path_buf).unwrap_or_default(); + if is_map(&path) { + return read_surface(&parent).map(inspect_surface).ok_or_else(|| { + IoError::Unsupported(format!("{} is a picture outside a FormSurface export folder", path.display())) + }); + } + if is_formsurface_obj(&path) { + if let Some(mut s) = read_surface(&parent) { + s.mesh = Some(path.clone()); + s.mesh_from = Some("export"); + return Ok(inspect_surface(s)); + } + } + let origin = model_origin(&path); + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string(); + let (gof, entry) = match is_gof_folder(&parent).then(|| read_gof(&parent)).and_then(|g| g.ok()) { + Some(g) => { + let e = g.objects.iter().rev().find(|e| e.file == file).cloned(); + (Some(g), e) + } + None => (None, None), + }; + let app = origin.app.or(entry.as_ref().and_then(|e| e.app)); + let title = origin.title.clone().or_else(|| entry.as_ref().map(|e| e.name.clone())).unwrap_or_else(|| name_of(&path)); + Ok(Inspection { + kind: HandoffKind::Model, + app, + writer: origin.writer, + title, + model: Some(path.clone()), + design_unit: origin.design_unit, + gof, + entry, + surface: None, + warnings: Vec::new(), + path, + }) +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + let hex = |c: u8| (c as char).to_digit(16); + if b[i] == b'%' && i + 2 < b.len() { + if let (Some(h), Some(l)) = (hex(b[i + 1]), hex(b[i + 2])) { + out.push((h * 16 + l) as u8); + i += 3; + continue; + } + } + out.push(b[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn resolve_texture(uri: &str, folder: &Path) -> String { + if uri.starts_with('#') || uri.starts_with("data:") { + return uri.to_string(); + } + let decoded = percent_decode(uri).replace('\\', "/"); + let p = Path::new(&decoded); + let full = if p.is_absolute() { p.to_path_buf() } else { folder.join(p) }; + full.canonicalize().unwrap_or(full).to_string_lossy().into_owned() +} + +fn attach(material: &mut RawMaterial, textures: &mut Vec<RawTexture>, maps: &[&MapRef]) { + for m in maps { + textures.push(RawTexture { uri: m.path.to_string_lossy().into_owned(), role: m.role, uv_set: m.uv_set, colour_space: m.colour_space }); + material.textures.push(textures.len() - 1); + } +} + +fn add_maps(scene: &mut RawScene, maps: &[MapRef], stem: &str) { + let sets = texture_sets(maps); + let single = sets.len() == 1 && sets[0].is_empty(); + if scene.materials.is_empty() { + for s in &sets { + let name = if s.is_empty() { stem.to_string() } else { s.clone() }; + scene.materials.push(RawMaterial { name, ..RawMaterial::default() }); + } + if single { + for mesh in scene.meshes.iter_mut().filter(|m| m.material.is_none()) { + mesh.material = Some(0); + } + } + } + let mut used = vec![false; sets.len()]; + for i in 0..scene.materials.len() { + let wanted = set_name(&scene.materials[i].name); + let chosen: Vec<&MapRef> = maps.iter().filter(|m| single || m.texture_set == wanted).collect(); + if let Some(k) = sets.iter().position(|s| single || *s == wanted) { + used[k] = true; + } + let mut material = std::mem::take(&mut scene.materials[i]); + attach(&mut material, &mut scene.textures, &chosen); + scene.materials[i] = material; + } + for (k, s) in sets.iter().enumerate().filter(|(k, _)| !used[*k]) { + scene.warnings.push(format!("the maps of texture set {s} match no material of the mesh; they arrive as material {s}")); + let mut material = RawMaterial { name: s.clone(), ..RawMaterial::default() }; + let chosen: Vec<&MapRef> = maps.iter().filter(|m| m.texture_set == sets[k]).collect(); + attach(&mut material, &mut scene.textures, &chosen); + scene.materials.push(material); + } +} + +impl Inspection { + /// The maps that travel with the hand-off. + pub fn maps(&self) -> &[MapRef] { + self.surface.as_ref().map(|s| s.maps.as_slice()).unwrap_or(&[]) + } + + /// The file that is read: the model, else the folder. + pub fn source_path(&self) -> &Path { + self.model.as_deref().unwrap_or(&self.path) + } + + /// The unit the sender declares for the file apart from the file itself (a GoF entry's units). + pub fn declared_unit(&self) -> Option<LengthUnit> { + match self.entry.as_ref()?.units.as_deref()? { + "m" => Some(LengthUnit::Metre), + "cm" => Some(LengthUnit::Centimetre), + "mm" => Some(LengthUnit::Millimetre), + _ => None, + } + } + + /// True when only materials arrive (maps without a mesh). + pub fn materials_only(&self) -> bool { + self.model.is_none() && !self.maps().is_empty() + } + + /// Reads the hand-off into a raw scene: the model through fsh-io's readers with what its app adds (FormCAD's title + /// on the root, texture paths made absolute), and FormSurface's maps as texture references by role on the + /// materials they belong to. Maps without a mesh give a scene with materials and no meshes. + pub fn read(&self, watch: &Watch) -> Result<RawScene> { + let mut scene = match &self.model { + Some(model) => crate::read_model(model, watch)?, + None if !self.maps().is_empty() => RawScene::named(self.title.clone()), + None => return Err(IoError::Unsupported(format!("{} holds nothing FormShot can read", self.path.display()))), + }; + let folder = self.model.as_deref().and_then(Path::parent).map(Path::to_path_buf).unwrap_or_else(|| self.path.clone()); + let mut found = Vec::new(); + for t in &mut scene.textures { + let resolved = resolve_texture(&t.uri, &folder); + if resolved != t.uri && Path::new(&resolved).is_file() { + found.push(t.uri.clone()); + } + t.uri = resolved; + } + scene.warnings.retain(|w| !found.iter().any(|uri| w.contains(uri.as_str()) && w.contains("not found"))); + if self.app == Some(FamilyApp::FormSurface) { + scene.warnings.retain(|w| !(w.starts_with("material ") && w.ends_with("is not defined in any library; a default was used"))); + } + if self.app == Some(FamilyApp::FormCad) { + for n in scene.nodes.iter_mut().filter(|n| n.parent.is_none() && n.name == CAD_ROOT) { + n.name = self.title.clone(); + } + } + if let Some(s) = &self.surface { + add_maps(&mut scene, &s.maps, &s.stem); + } + scene.name = self.title.clone(); + Ok(scene) + } + + /// Metadata FormShot records on the nodes that arrive, besides `source.path` and `source.node`. + pub fn metadata(&self) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = vec![("source.handoff".into(), self.kind.as_str().into())]; + if let Some(app) = self.app { + out.push(("source.app".into(), app.id().into())); + } + if let Some(w) = self.writer.as_ref().filter(|w| !w.is_empty()) { + out.push(("source.writer".into(), w.clone())); + } + out.push(("source.title".into(), self.title.clone())); + if self.path != self.source_path() { + out.push(("source.folder".into(), self.path.to_string_lossy().into_owned())); + } + if let Some(u) = &self.design_unit { + out.push(("source.design_unit".into(), u.clone())); + } + if let Some(e) = &self.entry { + out.push(("source.gof.id".into(), e.id.to_string())); + out.push(("source.gof.target".into(), e.target.clone())); + out.push(("source.gof.revision".into(), e.revision.to_string())); + out.push(("source.gof.sent".into(), e.sent.to_string())); + if let Some(u) = &e.units { + out.push(("source.gof.units".into(), u.clone())); + } + if let Some(s) = e.scale { + out.push(("source.gof.scale".into(), s.to_string())); + } + } + if let Some(mm) = self.gof.as_ref().and_then(|g| g.mm_per_unit) { + out.push(("source.gof.mm_per_unit".into(), mm.to_string())); + } + if let Some(s) = &self.surface { + if let Some(t) = template_of(&s.maps) { + out.push(("source.template".into(), t.into())); + } + if !s.maps.is_empty() { + let maps: Vec<Value> = s.maps.iter().map(MapRef::to_json).collect(); + out.push(("source.maps".into(), Value::Array(maps).to_string())); + } + } + out + } + + /// The inspection as JSON. + pub fn to_json(&self) -> Value { + let maps = self.maps(); + json!({ + "path": self.path.to_string_lossy(), + "kind": self.kind.as_str(), + "app": self.app.map(FamilyApp::id), + "app_name": self.app.map(FamilyApp::name), + "writer": self.writer, + "title": self.title, + "model": self.model.as_ref().map(|m| m.to_string_lossy()), + "format": self.model.as_ref().and_then(|m| m.extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase), + "design_unit": self.design_unit, + "materials_only": self.materials_only(), + "gof": self.gof.as_ref().map(GofManifest::to_json), + "entry": match (&self.entry, &self.gof) { + (Some(e), Some(g)) => e.to_json(&g.folder), + _ => Value::Null, + }, + "mesh_from": self.surface.as_ref().and_then(|s| s.mesh_from), + "template": template_of(maps), + "texture_sets": texture_sets(maps), + "maps": maps.iter().map(MapRef::to_json).collect::<Vec<_>>(), + "roles": maps.iter().map(|m| role_name(m.role)).collect::<std::collections::BTreeSet<_>>(), + "warnings": self.warnings, + }) + } +} diff --git a/native/crates/fsh-io/src/family/maps.rs b/native/crates/fsh-io/src/family/maps.rs new file mode 100644 index 00000000..1daa0055 --- /dev/null +++ b/native/crates/fsh-io/src/family/maps.rs @@ -0,0 +1,243 @@ +use fsh_scene::TextureRole; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +/// Picture extensions FormSurface writes maps in. +pub const MAP_EXTENSIONS: [&str; 8] = ["png", "tif", "tiff", "exr", "hdr", "jpg", "jpeg", "psd"]; + +const SRGB: &str = "srgb"; +const LINEAR: &str = "linear"; + +struct Known { + name: &'static str, + source: &'static str, + role: TextureRole, + colour: bool, +} + +const fn k(name: &'static str, source: &'static str, role: TextureRole, colour: bool) -> Known { + Known { name, source, role, colour } +} + +use TextureRole::{BaseColour, Bump, Emission, Metalness, Normal, OcclusionRoughnessMetalness as Orm, Opacity, Other, Roughness}; + +const KNOWN: &[Known] = &[ + k("basecolor", "basecolor", BaseColour, true), + k("baseColor", "basecolor", BaseColour, true), + k("BaseColor", "basecolor", BaseColour, true), + k("BaseMap", "basecolor", BaseColour, true), + k("albedo", "basecolor", BaseColour, true), + k("diffuseColor", "basecolor", BaseColour, true), + k("Albedo", "diffuse", BaseColour, true), + k("Diffuse", "diffuse", BaseColour, true), + k("roughness", "roughness", Roughness, false), + k("Roughness", "roughness", Roughness, false), + k("SpecularRoughness", "roughness", Roughness, false), + k("metallic", "metallic", Metalness, false), + k("Metallic", "metallic", Metalness, false), + k("Metalness", "metallic", Metalness, false), + k("height", "height", Bump, false), + k("Height", "height", Bump, false), + k("displacement", "height", Bump, false), + k("normal", "normal_gl", Normal, false), + k("Normal", "normal_gl", Normal, false), + k("occlusionRoughnessMetallic", "ao_roughness_metallic", Orm, false), + k("OcclusionRoughnessMetallic", "ao_roughness_metallic", Orm, false), + k("orm", "ao_roughness_metallic", Orm, false), + k("opacity", "opacity", Opacity, false), + k("emissive", "emissive", Emission, true), + k("Emissive", "emissive", Emission, true), + k("ambient_occlusion", "ao", Other, false), + k("occlusion", "ao", Other, false), + k("Occlusion", "ao", Other, false), + k("AO", "ao", Other, false), + k("ambient_occlusion_high", "ao_high", Other, false), + k("height_high", "height_high", Other, false), + k("MaskMap", "metallic_ao_smoothness", Other, false), + k("MetallicSmoothness", "metallic_smoothness", Other, false), + k("SpecularSmoothness", "specular_smoothness", Other, true), + k("Specular", "specular", Other, true), + k("Glossiness", "smoothness", Other, false), + k("curvature", "curvature", Other, false), + k("thickness", "thickness", Other, false), + k("position", "position", Other, false), + k("world_normal", "world_normal", Other, false), + k("bent_normal", "bent_normal", Other, false), + k("normal_baked", "normal_baked", Other, false), + k("id", "id", Other, false), +]; + +/// One map file of a map set, with what it drives. +#[derive(Clone, Debug, PartialEq)] +pub struct MapRef { + /// Absolute path. + pub path: PathBuf, + /// File name. + pub file: String, + /// The map's name as written in the file name ("basecolor", "BaseColor", "OcclusionRoughnessMetallic"). + pub map: String, + /// What FormSurface packed into it: basecolor, diffuse, roughness, metallic, height, normal_gl, normal_dx, + /// ao_roughness_metallic, metallic_ao_smoothness, ao, opacity, emissive, or the map's own name. + pub source: String, + /// The texture slot role in FormShot's document. + pub role: TextureRole, + /// "srgb" for colour maps in 8 and 16 bit files, "linear" for data maps and float files. + pub colour_space: &'static str, + /// UV set (FormSurface paints UV0; its uv_channel 1 export is not told apart by the files). + pub uv_set: u32, + /// Texture set (material) name; empty when the folder holds one set. + pub texture_set: String, + /// UDIM tile, for tiled sets. + pub udim: Option<u32>, + /// File extension, lower case. + pub format: String, +} + +impl MapRef { + /// The map as JSON. + pub fn to_json(&self) -> Value { + json!({ + "path": self.path.to_string_lossy(), "file": self.file, "map": self.map, "source": self.source, + "role": role_name(self.role), "colour_space": self.colour_space, "uv_set": self.uv_set, + "texture_set": self.texture_set, "udim": self.udim, "format": self.format, + }) + } +} + +/// The document's name for a texture role. +pub fn role_name(role: TextureRole) -> &'static str { + match role { + BaseColour => "base_colour", + Roughness => "roughness", + Metalness => "metalness", + Normal => "normal", + Bump => "bump", + Opacity => "opacity", + Emission => "emission", + Orm => "occlusion_roughness_metalness", + Other => "other", + } +} + +fn is_map_file(path: &Path) -> bool { + path.is_file() + && path + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| MAP_EXTENSIONS.iter().any(|m| e.eq_ignore_ascii_case(m))) +} + +fn split_udim(name: &str) -> (&str, Option<u32>) { + if let Some((rest, tile)) = name.rsplit_once('.') { + if tile.len() == 4 && tile.bytes().all(|b| b.is_ascii_digit()) { + if let Ok(n) = tile.parse::<u32>() { + if (1001..=1999).contains(&n) { + return (rest, Some(n)); + } + } + } + } + (name, None) +} + +fn known_for(rest: &str) -> Option<(&'static Known, String)> { + let mut order: Vec<&Known> = KNOWN.iter().collect(); + order.sort_by_key(|k| std::cmp::Reverse(k.name.len())); + let pick = |exact: bool| { + order.iter().copied().find_map(|k| { + let same = |a: &str, b: &str| if exact { a == b } else { a.eq_ignore_ascii_case(b) }; + if same(rest, k.name) { + return Some((k, String::new())); + } + let cut = rest.len().checked_sub(k.name.len() + 1)?; + let (head, tail) = (rest.get(..cut)?, rest.get(cut..)?); + (tail.starts_with('_') && same(&tail[1..], k.name) && !head.is_empty()).then(|| (k, head.to_string())) + }) + }; + pick(true).or_else(|| pick(false)) +} + +/// Cleans a material name the way FormSurface names a texture set's files (letters, digits, dash, underscore). +pub fn set_name(material: &str) -> String { + material.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect() +} + +/// Reads the maps in a FormSurface export folder: `<stem>_[<set>_]<map>[.<udim>].<ext>`. Files that name no known +/// map are skipped. The unreal template's `Normal` is DirectX (green down), every other normal OpenGL. +pub fn read_maps(folder: &Path, stem: &str) -> Vec<MapRef> { + let Ok(dir) = std::fs::read_dir(folder) else { return Vec::new() }; + let mut files: Vec<PathBuf> = dir.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| is_map_file(p)).collect(); + files.sort(); + let mut maps = Vec::new(); + for path in files { + let Some(file) = path.file_name().and_then(|n| n.to_str()).map(str::to_string) else { continue }; + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + let base = &file[..file.len() - ext.len() - 1]; + let (base, udim) = split_udim(base); + let prefix = format!("{stem}_"); + let rest = base.strip_prefix(prefix.as_str()).unwrap_or(base); + let Some((known, texture_set)) = known_for(rest) else { continue }; + let float = matches!(ext.as_str(), "exr" | "hdr"); + let map = rest[rest.len() - known.name.len()..].to_string(); + maps.push(MapRef { + path: path.canonicalize().unwrap_or(path.clone()), + file, + map, + source: known.source.to_string(), + role: known.role, + colour_space: if known.colour && !float { SRGB } else { LINEAR }, + uv_set: 0, + texture_set, + udim, + format: ext, + }); + } + let unreal = maps.iter().any(|m| m.map == "OcclusionRoughnessMetallic"); + for m in maps.iter_mut().filter(|m| m.map == "Normal" && unreal) { + m.source = "normal_dx".into(); + } + maps +} + +/// The texture sets the maps name, in file order; one empty name when the folder holds a single set. +pub fn texture_sets(maps: &[MapRef]) -> Vec<String> { + let mut sets: Vec<String> = Vec::new(); + for m in maps { + if !sets.contains(&m.texture_set) { + sets.push(m.texture_set.clone()); + } + } + sets +} + +/// The template a set of map names matches, when it matches one of FormSurface's built-in templates. +pub fn template_of(maps: &[MapRef]) -> Option<&'static str> { + let has = |n: &str| maps.iter().any(|m| m.map == n); + Some(if has("OcclusionRoughnessMetallic") { + "unreal" + } else if has("occlusionRoughnessMetallic") { + "gltf" + } else if has("MaskMap") { + "unity_hdrp" + } else if has("MetallicSmoothness") { + "unity_urp" + } else if has("SpecularSmoothness") { + "unity_standard_specular" + } else if has("orm") { + "godot" + } else if has("diffuseColor") { + "usd" + } else if has("Glossiness") { + "spec_gloss" + } else if has("SpecularRoughness") { + "arnold" + } else if has("basecolor") { + "pbr" + } else if has("BaseColor") && has("AO") { + "sketchfab" + } else if has("BaseColor") { + "blender" + } else { + return None; + }) +} diff --git a/native/crates/fsh-io/src/family/mod.rs b/native/crates/fsh-io/src/family/mod.rs new file mode 100644 index 00000000..64f91459 --- /dev/null +++ b/native/crates/fsh-io/src/family/mod.rs @@ -0,0 +1,13 @@ +//! What other Form apps hand over: their export folders and files, read into the same raw scene as any model. + +mod app; +mod gof; +mod handoff; +mod maps; +mod surface; + +pub use app::{origin_of, FamilyApp, Origin}; +pub use handoff::{inspect, HandoffKind, Inspection}; +pub use gof::{is_gof_folder, read_gof, GofEntry, GofManifest, GOF_MANIFEST, GOF_TARGETS}; +pub use maps::{read_maps, role_name, set_name, template_of, texture_sets, MapRef, MAP_EXTENSIONS}; +pub use surface::{is_formsurface_obj, read_surface, SurfaceExport}; diff --git a/native/crates/fsh-io/src/family/surface.rs b/native/crates/fsh-io/src/family/surface.rs new file mode 100644 index 00000000..e7cdbd5d --- /dev/null +++ b/native/crates/fsh-io/src/family/surface.rs @@ -0,0 +1,71 @@ +use super::maps::{read_maps, MapRef}; +use std::path::{Path, PathBuf}; + +const OBJ_MARK: &[u8] = b"# FormSurface"; +const MESH_EXTENSIONS: [&str; 4] = ["glb", "gltf", "obj", "fbx"]; + +/// A FormSurface export folder: `<data>/exports/<stem>/` with maps and, when exported, the painted mesh. +#[derive(Clone, Debug, PartialEq)] +pub struct SurfaceExport { + /// The folder. + pub folder: PathBuf, + /// Its name, the stem every file starts with. + pub stem: String, + /// Maps found. + pub maps: Vec<MapRef>, + /// The mesh: the OBJ FormSurface wrote beside the maps, else the mesh it painted, from its workspace's meshes folder. + pub mesh: Option<PathBuf>, + /// "export" when the mesh is the OBJ in the folder, "workspace" when it is the mesh FormSurface loaded. + pub mesh_from: Option<&'static str>, +} + +/// True when the file is an OBJ FormSurface wrote (its first line starts `# FormSurface`). +pub fn is_formsurface_obj(path: &Path) -> bool { + use std::io::Read; + let mut head = [0u8; 13]; + std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && head == OBJ_MARK +} + +fn folder_stem(folder: &Path) -> String { + folder.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string() +} + +fn painted_mesh(folder: &Path, stem: &str) -> Option<PathBuf> { + let exports = folder.parent()?; + if exports.file_name().and_then(|n| n.to_str()) != Some("exports") { + return None; + } + let meshes = exports.parent()?.join("meshes"); + MESH_EXTENSIONS.iter().map(|e| meshes.join(format!("{stem}.{e}"))).find(|p| p.is_file()) +} + +/// Reads a FormSurface export folder; `None` when the folder holds neither a known map named after it nor a +/// FormSurface OBJ. +pub fn read_surface(folder: &Path) -> Option<SurfaceExport> { + if !folder.is_dir() { + return None; + } + let stem = folder_stem(folder); + let maps: Vec<MapRef> = read_maps(folder, &stem).into_iter().filter(|m| m.file.starts_with(&format!("{stem}_"))).collect(); + let own = folder.join(format!("{stem}.obj")); + let obj = if own.is_file() && is_formsurface_obj(&own) { + Some(own) + } else { + std::fs::read_dir(folder) + .ok()? + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("obj"))) + .find(|p| is_formsurface_obj(p)) + }; + if maps.is_empty() && obj.is_none() { + return None; + } + let (mesh, mesh_from) = match obj { + Some(p) => (Some(p), Some("export")), + None => match painted_mesh(folder, &stem) { + Some(p) => (Some(p), Some("workspace")), + None => (None, None), + }, + }; + Some(SurfaceExport { folder: folder.to_path_buf(), stem, maps, mesh, mesh_from }) +} diff --git a/native/crates/fsh-io/src/fbx.rs b/native/crates/fsh-io/src/fbx.rs new file mode 100644 index 00000000..e598c198 --- /dev/null +++ b/native/crates/fsh-io/src/fbx.rs @@ -0,0 +1,445 @@ +use crate::error::{IoError, Result}; +use crate::obj::roughness_from_phong; +use crate::paths::Siblings; +use crate::raw::{RawMaterial, RawMesh, RawNode, RawScene, RawSlot, RawTexture, UpAxis}; +use crate::watch::{Stage, Watch}; +use fsh_core::{srgb_decode, LengthUnit, Mat4, Vec2, Vec3, Vec4}; +use fsh_scene::fsh_materials::Wrap; +use fsh_scene::{Channel, MapProjection, MaterialInput, TextureRole, TextureSlot, UvTransform}; +use std::collections::HashMap; + +const MEMORY_LIMIT: usize = 3 << 30; + +fn unit_of(m: f64) -> (LengthUnit, f32) { + let known = [ + (0.001, LengthUnit::Millimetre), + (0.01, LengthUnit::Centimetre), + (1.0, LengthUnit::Metre), + (0.0254, LengthUnit::Inch), + (0.3048, LengthUnit::Foot), + ]; + if !(m.is_finite() && m > 0.0) { + return (LengthUnit::Centimetre, 1.0); + } + for (v, u) in known { + if ((m - v) / v).abs() < 1e-4 { + return (u, 1.0); + } + } + (LengthUnit::Metre, m as f32) +} + +fn matrix(m: &ufbx::Matrix, scale: f32) -> Mat4 { + let f = |v: f64| v as f32; + Mat4::from_rows([ + [f(m.m00), f(m.m01), f(m.m02), f(m.m03) * scale], + [f(m.m10), f(m.m11), f(m.m12), f(m.m13) * scale], + [f(m.m20), f(m.m21), f(m.m22), f(m.m23) * scale], + [0.0, 0.0, 0.0, 1.0], + ]) +} + +fn map_value(m: &ufbx::MaterialMap, default: f32) -> f32 { + if m.has_value { + let v = m.value_vec4.x as f32; + if v.is_finite() { + return v; + } + } + default +} + +fn map_colour(m: &ufbx::MaterialMap, default: [f32; 3]) -> [f32; 3] { + if m.has_value { + let c = [m.value_vec4.x as f32, m.value_vec4.y as f32, m.value_vec4.z as f32]; + if c.iter().all(|v| v.is_finite()) { + return c; + } + } + default +} + +fn texture_uri(t: &ufbx::Texture, siblings: &Siblings) -> Option<String> { + let rel: &str = &t.relative_filename; + let abs: &str = &t.filename; + let base = abs.rsplit(['/', '\\']).next().unwrap_or(""); + for c in [rel, base] { + if c.is_empty() { + continue; + } + if let Ok(p) = siblings.resolve(c) { + return Some(p.to_string_lossy().into_owned()); + } + } + [rel, abs].into_iter().find(|s| !s.is_empty()).map(str::to_string) +} + +fn file_texture(t: &ufbx::Texture) -> &ufbx::Texture { + if t.has_file || t.content.size > 0 { + return t; + } + t.file_textures.iter().next().map(|f| &**f).unwrap_or(t) +} + +fn slot_of(t: &ufbx::Texture, sets: &[String], name: &str, warnings: &mut Vec<String>) -> TextureSlot { + let set = if t.uv_set.is_empty() { + 0 + } else { + match sets.iter().position(|s| *s == *t.uv_set) { + Some(i) => i as u32, + None => { + warnings.push(format!("{name}: uv set {:?} is not on the mesh; the first set is used", &*t.uv_set)); + 0 + } + } + }; + let mut slot = TextureSlot { projection: MapProjection::Uv { set: set.min(3) }, ..TextureSlot::default() }; + if t.wrap_u != t.wrap_v { + warnings.push(format!("{name}: a texture wraps differently along u and v; its u wrapping is used for both")); + } + if t.wrap_u == ufbx::WrapMode::Clamp { + slot.wrap = Wrap::Clamp; + } + if t.has_uv_transform { + let m = &t.uv_to_texture; + let (a, b, c, d) = (m.m00 as f32, m.m01 as f32, m.m10 as f32, m.m11 as f32); + let rotation = c.atan2(a); + let (s, co) = rotation.sin_cos(); + let tr = UvTransform { + offset: [m.m03 as f32, m.m13 as f32], + scale: [(a * a + c * c).sqrt(), -s * b + co * d], + rotation, + ..UvTransform::default() + }; + if tr.validate("transform").is_ok() { + slot.transform = tr; + } + if (a * b + c * d).abs() > 1e-4 * ((a * a + c * c) * (b * b + d * d)).sqrt() { + warnings.push(format!("{name}: a texture transform rotates a non-uniform scale; its shear was dropped")); + } + } + slot +} + +type MapUse<'a> = (Option<&'a ufbx::Ref<ufbx::Texture>>, bool, TextureRole, &'static str, MaterialInput); + +fn material(m: &ufbx::Material, scene: &mut RawScene, siblings: &Siblings, sets: &[String], images: &mut HashMap<u32, String>) -> (RawMaterial, Vec<RawSlot>) { + let mut r = RawMaterial { name: m.element.name.to_string(), ..Default::default() }; + if r.name.trim().is_empty() { + r.name = "Material".into(); + } + let classic = matches!(m.shader_type, ufbx::ShaderType::FbxLambert | ufbx::ShaderType::FbxPhong | ufbx::ShaderType::Unknown | ufbx::ShaderType::BlenderPhong); + let p = &m.pbr; + if classic && !m.features.pbr.enabled { + let d = map_colour(&m.fbx.diffuse_color, [0.8; 3]); + let k = map_value(&m.fbx.diffuse_factor, 1.0); + r.base_colour = d.map(|v| (v * k).clamp(0.0, 1.0)); + if m.shader_type == ufbx::ShaderType::FbxLambert { + r.roughness = 0.9; + r.specular = 0.5; + } else { + r.roughness = roughness_from_phong(map_value(&m.fbx.specular_exponent, 20.0)); + let s = map_colour(&m.fbx.specular_color, [0.2; 3]); + r.specular = (s[0].max(s[1]).max(s[2]) * map_value(&m.fbx.specular_factor, 1.0)).clamp(0.0, 1.0); + } + let e = map_colour(&m.fbx.emission_color, [0.0; 3]); + let ek = map_value(&m.fbx.emission_factor, 1.0); + r.emissive = e.map(|v| (v * ek).max(0.0)); + } else { + let b = map_colour(&p.base_color, [0.8; 3]); + let k = map_value(&p.base_factor, 1.0); + r.base_colour = b.map(|v| (v * k).clamp(0.0, 1.0)); + r.metallic = map_value(&p.metalness, 0.0).clamp(0.0, 1.0); + let rough = map_value(&p.roughness, 0.5); + r.roughness = if m.features.roughness_as_glossiness.enabled { 1.0 - rough } else { rough }.clamp(0.0, 1.0); + r.specular = map_value(&p.specular_factor, 1.0).clamp(0.0, 1.0); + r.ior = map_value(&p.specular_ior, 1.5); + r.transmission = map_value(&p.transmission_factor, 0.0).clamp(0.0, 1.0); + r.clearcoat = map_value(&p.coat_factor, 0.0).clamp(0.0, 1.0); + r.clearcoat_roughness = map_value(&p.coat_roughness, 0.0).clamp(0.0, 1.0); + let e = map_colour(&p.emission_color, [0.0; 3]); + let ek = map_value(&p.emission_factor, 1.0); + r.emissive = e.map(|v| (v * ek).max(0.0)); + } + r.opacity = map_value(&p.opacity, 1.0).clamp(0.0, 1.0); + r.double_sided = m.features.double_sided.enabled; + let glossy = m.features.roughness_as_glossiness.enabled; + let specular = p.specular_color.texture.as_ref().or(p.specular_factor.texture.as_ref()).or(m.fbx.specular_color.texture.as_ref()).or(m.fbx.specular_factor.texture.as_ref()); + let bump = m.fbx.bump.texture.as_ref().filter(|_| p.normal_map.texture.is_none() && m.fbx.normal_map.texture.is_none()); + let maps: [MapUse; 9] = [ + (p.base_color.texture.as_ref().or(m.fbx.diffuse_color.texture.as_ref()), false, TextureRole::BaseColour, "srgb", MaterialInput::BaseColor), + (p.roughness.texture.as_ref(), glossy, TextureRole::Roughness, "linear", MaterialInput::SpecularRoughness), + (p.glossiness.texture.as_ref().filter(|_| p.roughness.texture.is_none()), true, TextureRole::Roughness, "linear", MaterialInput::SpecularRoughness), + (p.metalness.texture.as_ref(), false, TextureRole::Metalness, "linear", MaterialInput::BaseMetalness), + (p.normal_map.texture.as_ref().or(m.fbx.normal_map.texture.as_ref()), false, TextureRole::Normal, "linear", MaterialInput::Normal), + (p.emission_color.texture.as_ref().or(m.fbx.emission_color.texture.as_ref()), false, TextureRole::Emission, "srgb", MaterialInput::EmissionColor), + (specular, false, TextureRole::Other, "srgb", MaterialInput::SpecularWeight), + (bump, false, TextureRole::Bump, "linear", MaterialInput::Bump), + (m.fbx.displacement.texture.as_ref(), false, TextureRole::Other, "linear", MaterialInput::Displacement), + ]; + let mut out = Vec::new(); + let opacity = match (p.opacity.texture.as_ref(), m.fbx.transparency_factor.texture.as_ref().or(m.fbx.transparency_color.texture.as_ref())) { + (Some(t), _) => Some((t, false)), + (None, Some(t)) => Some((t, true)), + _ => None, + }; + let all = maps.into_iter().chain(opacity.map(|(t, inv)| (Some(t), inv, TextureRole::Opacity, "linear", MaterialInput::GeometryOpacity))); + for (t, invert, role, space, input) in all { + let Some(t) = t else { continue }; + let t = file_texture(t); + let uri = if let Some(u) = images.get(&t.element.element_id) { + Some(u.clone()) + } else if t.content.size > 0 { + let name = [&*t.relative_filename, &*t.filename, &*t.element.name].into_iter().find(|s| !s.is_empty()).unwrap_or("embedded image").to_string(); + let u = scene.add_image(name, t.content.to_vec()); + images.insert(t.element.element_id, u.clone()); + Some(u) + } else { + texture_uri(t, siblings) + }; + let Some(uri) = uri else { + scene.warnings.push(format!("{}: a texture without a file name was skipped", r.name)); + continue; + }; + let mut slot = slot_of(t, sets, &r.name, &mut scene.warnings); + slot.invert = invert; + match input { + MaterialInput::Bump => slot.strength = 0.001 * map_value(&m.fbx.bump_factor, 1.0).clamp(0.0, 1000.0), + MaterialInput::Displacement => slot.strength = 0.01 * map_value(&m.fbx.displacement_factor, 1.0).clamp(0.0, 1000.0), + MaterialInput::GeometryOpacity => { + let alpha = scene.image_of(&uri).map(|i| crate::obj::png_has_alpha(&i.bytes)).unwrap_or_else(|| crate::obj::has_alpha(&uri)); + slot.channel = if alpha { Channel::A } else { Channel::Luminance }; + if invert && alpha { + slot.invert = false; + } + } + MaterialInput::EmissionColor if r.emissive.iter().all(|v| *v <= 0.0) => r.emissive = [1.0; 3], + _ => {} + } + scene.textures.push(RawTexture { uri, role, uv_set: slot_uv(&slot), colour_space: space }); + let ti = scene.textures.len() - 1; + r.textures.push(ti); + out.push(RawSlot { input, texture: ti, slot }); + } + (r, out) +} + +fn slot_uv(s: &TextureSlot) -> u32 { + match s.projection { + MapProjection::Uv { set } => set, + _ => 0, + } +} + +struct Builder<'a> { + scene: RawScene, + siblings: &'a Siblings, + watch: &'a Watch, + scale: f32, + materials: HashMap<u32, usize>, + images: HashMap<u32, String>, + meshes: HashMap<(u32, u32, Option<usize>), usize>, + tris: usize, + total_tris: usize, +} + +impl Builder<'_> { + fn material_slot(&mut self, m: &ufbx::Material, mesh: &ufbx::Mesh) -> usize { + let id = m.element.element_id; + if let Some(&s) = self.materials.get(&id) { + return s; + } + let sets: Vec<String> = mesh.uv_sets.iter().filter(|s| s.vertex_uv.exists).map(|s| s.name.to_string()).collect(); + let (r, slots) = material(m, &mut self.scene, self.siblings, &sets, &mut self.images); + self.scene.materials.push(r); + let s = self.scene.materials.len() - 1; + self.scene.extra_mut(s).slots = slots; + self.materials.insert(id, s); + s + } + + fn part(&mut self, mesh: &ufbx::Mesh, part: &ufbx::MeshPart, mat: Option<usize>) -> Result<Option<usize>> { + if let Some(&i) = self.meshes.get(&key_of(mesh, part, mat)) { + return Ok(Some(i)); + } + if part.num_triangles == 0 { + return Ok(None); + } + let mut out = RawMesh { name: mesh.element.name.to_string(), material: mat, ..Default::default() }; + if out.name.trim().is_empty() { + out.name = "Mesh".into(); + } + let has_n = mesh.vertex_normal.exists; + let has_c = mesh.vertex_color.exists; + let sets: Vec<&ufbx::UvSet> = mesh.uv_sets.iter().filter(|s| s.vertex_uv.exists).collect(); + out.uvs = vec![Vec::new(); sets.len()]; + let mut map: HashMap<Vec<u32>, u32> = HashMap::new(); + let mut key = Vec::with_capacity(3 + sets.len()); + let mut corners = vec![0u32; mesh.max_face_triangles.max(1) * 3]; + let ni = mesh.num_indices; + for (fi, &face_ix) in part.face_indices.iter().enumerate() { + if fi % 16384 == 0 { + let f = self.tris as f32 / self.total_tris.max(1) as f32; + self.watch.step(Stage::Reading, 0.6 + 0.4 * f.min(1.0))?; + } + let Some(&face) = mesh.faces.get(face_ix as usize) else { continue }; + if face.num_indices < 3 { + continue; + } + let n = mesh.triangulate_face(&mut corners, face) as usize; + self.tris += n; + for &ix in &corners[..n * 3] { + let ix = ix as usize; + if ix >= ni { + return Err(IoError::InvalidData(format!("{}: corner {ix} is out of range", out.name))); + } + key.clear(); + key.push(mesh.vertex_position.indices[ix]); + if has_n { + key.push(mesh.vertex_normal.indices[ix]); + } + for s in &sets { + key.push(s.vertex_uv.indices[ix]); + } + if has_c { + key.push(mesh.vertex_color.indices[ix]); + } + let next = out.positions.len() as u32; + let id = match map.get(&key) { + Some(&id) => id, + None => { + let p = mesh.vertex_position[ix]; + out.positions.push(Vec3::new(p.x as f32, p.y as f32, p.z as f32) * self.scale); + if has_n { + let v = mesh.vertex_normal[ix]; + out.normals.push(Vec3::new(v.x as f32, v.y as f32, v.z as f32).normalize_or(Vec3::Y)); + } + for (k, s) in sets.iter().enumerate() { + let t = s.vertex_uv[ix]; + out.uvs[k].push(Vec2::new(t.x as f32, t.y as f32)); + } + if has_c { + let c = mesh.vertex_color[ix]; + let lin = |v: f64| srgb_decode((v as f32).clamp(0.0, 1.0)); + out.colours.push(Vec4::new(lin(c.x), lin(c.y), lin(c.z), (c.w as f32).clamp(0.0, 1.0))); + } + map.insert(key.clone(), next); + next + } + }; + out.indices.push(id); + } + } + if out.indices.is_empty() { + return Ok(None); + } + self.scene.meshes.push(out); + let i = self.scene.meshes.len() - 1; + self.meshes.insert(key_of(mesh, part, mat), i); + Ok(Some(i)) + } + + fn node(&mut self, n: &ufbx::Node, parent: Option<usize>) -> Result<usize> { + let mut meshes = Vec::new(); + if let Some(mesh) = n.mesh.as_ref() { + for part in mesh.material_parts.iter() { + let m = n.materials.get(part.index as usize).or_else(|| mesh.materials.get(part.index as usize)); + let mat = m.map(|m| self.material_slot(m, mesh)); + if let Some(i) = self.part(mesh, part, mat)? { + meshes.push(i); + } + } + } + let name = if n.element.name.trim().is_empty() { "Node".to_string() } else { n.element.name.to_string() }; + let mut raw = RawNode::new(name, parent, meshes); + raw.transform = matrix(&n.node_to_parent, self.scale); + self.scene.nodes.push(raw); + Ok(self.scene.nodes.len() - 1) + } +} + +fn key_of(mesh: &ufbx::Mesh, part: &ufbx::MeshPart, mat: Option<usize>) -> (u32, u32, Option<usize>) { + (mesh.element.element_id, part.index, mat) +} + +fn load_error(e: ufbx::Error) -> IoError { + match e.type_ { + ufbx::ErrorType::Cancelled => IoError::Cancelled, + ufbx::ErrorType::OutOfMemory | ufbx::ErrorType::MemoryLimit | ufbx::ErrorType::AllocationLimit => { + IoError::Unsupported(format!("the FBX file needs more memory than allowed ({})", e.description.as_ref() as &str)) + } + ufbx::ErrorType::UnsupportedVersion | ufbx::ErrorType::FeatureDisabled => IoError::Unsupported(format!("FBX: {}", e.description.as_ref() as &str)), + _ => { + let info = e.info(); + let d: &str = e.description.as_ref(); + IoError::Malformed(if info.is_empty() { format!("FBX: {d}") } else { format!("FBX: {d} ({info})") }) + } + } +} + +/// Reads binary or ASCII FBX through ufbx: hierarchy, meshes split by material, normals, UV sets, vertex colours, +/// materials and texture paths; axes turned to Y up, the file's unit kept. +pub fn read_fbx(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) -> Result<RawScene> { + watch.step(Stage::Reading, 0.0)?; + let mut progress = |p: &ufbx::Progress| { + let f = if p.bytes_total > 0 { p.bytes_read as f32 / p.bytes_total as f32 } else { 0.0 }; + watch.set(Stage::Reading, 0.6 * f.min(1.0)); + if watch.is_cancelled() { + ufbx::ProgressResult::Cancel + } else { + ufbx::ProgressResult::Continue + } + }; + let mut refuse = |_: &str, _: &ufbx::OpenFileInfo| -> Option<ufbx::Stream> { None }; + let mut opts = ufbx::LoadOpts { + ignore_animation: true, + ignore_embedded: false, + load_external_files: false, + target_axes: ufbx::CoordinateAxes::right_handed_y_up(), + space_conversion: ufbx::SpaceConversion::ModifyGeometry, + geometry_transform_handling: ufbx::GeometryTransformHandling::ModifyGeometry, + progress_cb: ufbx::ProgressCb::Mut(&mut progress), + progress_interval_hint: 1 << 20, + open_file_cb: ufbx::OpenFileCb::Mut(&mut refuse), + ..Default::default() + }; + opts.temp_allocator.memory_limit = MEMORY_LIMIT; + opts.result_allocator.memory_limit = MEMORY_LIMIT; + let fbx = ufbx::load_memory(bytes, opts).map_err(load_error)?; + watch.step(Stage::Reading, 0.6)?; + let (unit, scale) = unit_of(fbx.settings.unit_meters); + let mut b = Builder { + scene: RawScene::named(name), + siblings, + watch, + scale, + materials: HashMap::new(), + images: HashMap::new(), + meshes: HashMap::new(), + tris: 0, + total_tris: fbx.meshes.iter().map(|m| m.num_triangles).sum(), + }; + b.scene.unit = Some(unit); + b.scene.up_axis = Some(UpAxis::Y); + let mut stack: Vec<(&ufbx::Node, Option<usize>)> = fbx.root_node.children.iter().rev().map(|c| (&**c, None)).collect(); + while let Some((n, parent)) = stack.pop() { + let me = b.node(n, parent)?; + for c in n.children.iter().rev() { + stack.push((c, Some(me))); + } + } + let skipped = [ + (fbx.cameras.len(), "cameras"), + (fbx.lights.len(), "lights"), + (fbx.skin_deformers.len(), "skins (meshes kept in their bind pose)"), + (fbx.blend_deformers.len(), "blend shapes"), + (fbx.nurbs_surfaces.len(), "NURBS surfaces"), + ]; + for (n, what) in skipped { + if n > 0 { + b.scene.warnings.push(format!("{n} {what} ignored")); + } + } + watch.step(Stage::Reading, 1.0)?; + Ok(b.scene) +} diff --git a/native/crates/fsh-io/src/glb_write.rs b/native/crates/fsh-io/src/glb_write.rs index a2d4dcc5..6a3b945f 100644 --- a/native/crates/fsh-io/src/glb_write.rs +++ b/native/crates/fsh-io/src/glb_write.rs @@ -1,6 +1,6 @@ use crate::error::{IoError, Result}; use crate::raw::{RawMaterial, RawScene}; -use fsh_core::{Aabb, Vec3}; +use fsh_core::{Aabb, Mat4}; use serde_json::{json, Map, Value}; use std::collections::BTreeMap; @@ -98,7 +98,7 @@ pub fn write_glb(scene: &RawScene) -> Result<Vec<u8>> { attrs.insert("NORMAL".into(), json!(bin.floats(&f, "VEC3", n, None))); } for (s, set) in m.uvs.iter().enumerate() { - let f: Vec<f32> = set.iter().flat_map(|p| [p.x, p.y]).collect(); + let f: Vec<f32> = set.iter().flat_map(|p| [p.x, 1.0 - p.y]).collect(); attrs.insert(format!("TEXCOORD_{s}"), json!(bin.floats(&f, "VEC2", n, None))); } if !m.colours.is_empty() { @@ -113,9 +113,9 @@ pub fn write_glb(scene: &RawScene) -> Result<Vec<u8>> { } prim_of[i] = Some(p); } - let prim = |mi: usize| -> Option<(Value, Vec3)> { + let prim = |mi: usize| -> Option<(Value, Mat4)> { let m = scene.meshes.get(mi)?; - let (src, off) = m.instance_of.unwrap_or((mi, Vec3::ZERO)); + let (src, off) = m.instance_of.unwrap_or((mi, Mat4::IDENTITY)); let mut p = prim_of.get(src)?.clone()?; match m.material.filter(|&x| x < scene.materials.len()) { Some(mat) => p["material"] = json!(mat), @@ -135,11 +135,11 @@ pub fn write_glb(scene: &RawScene) -> Result<Vec<u8>> { let mut roots = Vec::new(); for (i, n) in scene.nodes.iter().enumerate() { let mut node = json!({"name": n.name, "matrix": n.transform.to_cols_array()}); - let parts: Vec<(usize, Value, Vec3)> = n.meshes.iter().filter_map(|&mi| prim(mi).map(|(p, o)| (mi, p, o))).collect(); + let parts: Vec<(usize, Value, Mat4)> = n.meshes.iter().filter_map(|&mi| prim(mi).map(|(p, o)| (mi, p, o))).collect(); let me = nodes.len(); let mut extra_children = Vec::new(); if !parts.is_empty() { - if parts.iter().all(|(_, _, o)| *o == Vec3::ZERO) { + if parts.iter().all(|(_, _, o)| *o == Mat4::IDENTITY) { let key: Vec<usize> = parts.iter().map(|(mi, _, _)| *mi).collect(); let mesh = *mesh_cache.entry(key).or_insert_with(|| { meshes.push(json!({"name": n.name, "primitives": parts.iter().map(|(_, p, _)| p.clone()).collect::<Vec<_>>()})); @@ -149,7 +149,7 @@ pub fn write_glb(scene: &RawScene) -> Result<Vec<u8>> { } else { for (k, (mi, p, o)) in parts.into_iter().enumerate() { meshes.push(json!({"name": scene.meshes[mi].name, "primitives": [p]})); - extra_children.push(json!({"name": format!("{} {k}", n.name), "mesh": meshes.len() - 1, "translation": [o.x, o.y, o.z]})); + extra_children.push(json!({"name": format!("{} {k}", n.name), "mesh": meshes.len() - 1, "matrix": o.to_cols_array()})); } } } diff --git a/native/crates/fsh-io/src/gltf.rs b/native/crates/fsh-io/src/gltf.rs index d0b38139..0ad48366 100644 --- a/native/crates/fsh-io/src/gltf.rs +++ b/native/crates/fsh-io/src/gltf.rs @@ -1,9 +1,10 @@ use crate::error::{malformed, IoError, Result}; use crate::paths::Siblings; -use crate::raw::{RawMaterial, RawMesh, RawNode, RawScene, RawTexture, UpAxis}; +use crate::raw::{RawMaterial, RawMaterialExtra, RawMesh, RawNode, RawScene, RawSlot, RawTexture, UpAxis}; use crate::watch::{Stage, Watch}; use fsh_core::{LengthUnit, Mat4, Quat, Vec2, Vec3, Vec4}; -use fsh_scene::TextureRole; +use fsh_scene::fsh_materials::{ColourSpace, Filter, Wrap}; +use fsh_scene::{Channel, MapProjection, MaterialInput, TextureRole, TextureSlot, UvTransform}; use serde_json::Value; use std::borrow::Cow; use std::collections::BTreeMap; @@ -19,6 +20,10 @@ const SUPPORTED_REQUIRED: &[&str] = &[ "KHR_materials_emissive_strength", "KHR_materials_specular", "KHR_materials_volume", + "KHR_materials_sheen", + "KHR_materials_iridescence", + "KHR_materials_dispersion", + "KHR_materials_anisotropy", "KHR_texture_transform", "KHR_mesh_quantization", "KHR_texture_basisu", @@ -447,109 +452,9 @@ pub fn read_gltf(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) - let total_bytes: usize = buffers.iter().map(|b| b.len()).sum::<usize>() + json_bytes.len(); let reader = Reader { json: &json, buffers, views, budget: total_bytes.saturating_mul(4).saturating_add(4096) }; - let images = arr(&json, "images"); - let textures_json = arr(&json, "textures"); - let mut tex_cache: BTreeMap<(usize, u8, u32), usize> = BTreeMap::new(); + let mut tex = Textures { json: &json, uris: BTreeMap::new(), cache: BTreeMap::new() }; for (mi, m) in arr(&json, "materials").iter().enumerate() { - let mut mat = RawMaterial { - name: m.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("Material {mi}")), - roughness: 1.0, - metallic: 1.0, - base_colour: [1.0; 3], - ..Default::default() - }; - let mut tex_refs: Vec<(&Value, TextureRole, &'static str)> = Vec::new(); - if let Some(pbr) = m.get("pbrMetallicRoughness") { - if let Some(c) = floats::<4>(pbr, "baseColorFactor")? { - mat.base_colour = [c[0], c[1], c[2]]; - if m.get("alphaMode").and_then(Value::as_str) == Some("BLEND") { - mat.opacity = c[3]; - } - } - mat.metallic = num(pbr, "metallicFactor", 1.0); - mat.roughness = num(pbr, "roughnessFactor", 1.0); - if let Some(t) = pbr.get("baseColorTexture") { - tex_refs.push((t, TextureRole::BaseColour, "srgb")); - } - if let Some(t) = pbr.get("metallicRoughnessTexture") { - tex_refs.push((t, TextureRole::OcclusionRoughnessMetalness, "linear")); - } - } - if let Some(t) = m.get("normalTexture") { - tex_refs.push((t, TextureRole::Normal, "linear")); - } - if let Some(t) = m.get("emissiveTexture") { - tex_refs.push((t, TextureRole::Emission, "srgb")); - } - if let Some(t) = m.get("occlusionTexture") { - tex_refs.push((t, TextureRole::Other, "linear")); - } - if let Some(e) = floats::<3>(m, "emissiveFactor")? { - mat.emissive = e; - } - mat.double_sided = m.get("doubleSided").and_then(Value::as_bool).unwrap_or(false); - if let Some(ext) = m.get("extensions") { - if let Some(x) = ext.get("KHR_materials_transmission") { - mat.transmission = num(x, "transmissionFactor", 0.0); - } - if let Some(x) = ext.get("KHR_materials_ior") { - mat.ior = num(x, "ior", 1.5); - } - if let Some(x) = ext.get("KHR_materials_clearcoat") { - mat.clearcoat = num(x, "clearcoatFactor", 0.0); - mat.clearcoat_roughness = num(x, "clearcoatRoughnessFactor", 0.0); - } - if let Some(x) = ext.get("KHR_materials_emissive_strength") { - mat.emissive_strength = num(x, "emissiveStrength", 1.0); - } - if let Some(x) = ext.get("KHR_materials_specular") { - mat.specular = num(x, "specularFactor", 1.0); - } - } - for (info, role, space) in tex_refs { - let Some(ti) = idx(info, "index")? else { continue }; - let uv = idx(info, "texCoord")?.unwrap_or(0) as u32; - let Some(t) = textures_json.get(ti) else { - scene.warnings.push(format!("material {} names missing texture {ti}", mat.name)); - continue; - }; - let mut source = idx(t, "source")?; - if let Some(ext) = t.get("extensions").and_then(Value::as_object) { - for v in ext.values() { - if let Some(s) = idx(v, "source")? { - source.get_or_insert(s); - } - } - } - let Some(si) = source else { continue }; - let key = (si, role as u8, uv); - let slot = if let Some(&s) = tex_cache.get(&key) { - s - } else { - let Some(img) = images.get(si) else { - scene.warnings.push(format!("texture {ti} names missing image {si}")); - continue; - }; - let uri = match img.get("uri").and_then(Value::as_str) { - Some(u) if !u.starts_with("data:") => match siblings.resolve(u) { - Ok(p) => p.to_string_lossy().into_owned(), - Err(_) => { - scene.warnings.push(format!("texture file {u} was not found beside the model")); - u.to_string() - } - }, - _ => format!("#image{si}"), - }; - scene.textures.push(RawTexture { uri, role, uv_set: uv, colour_space: space }); - tex_cache.insert(key, scene.textures.len() - 1); - scene.textures.len() - 1 - }; - mat.textures.push(slot); - } - scene.materials.push(mat); - } - if scene.textures.iter().any(|t| t.uri.starts_with("#image")) { - scene.warnings.push("embedded images are recorded as references only (#image<n>)".into()); + read_material(&reader, siblings, m, mi, &mut tex, &mut scene)?; } let meshes_json = arr(&json, "meshes"); @@ -613,7 +518,7 @@ pub fn read_gltf(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) - }; if mesh_map[mi].is_none() { watch.step(Stage::Reading, done as f32 / meshes_json.len().max(1) as f32)?; - let list = read_mesh(&reader, mj, mi, &mut scene)?; + let list = read_mesh(&reader, mj, mi, &mut scene, watch)?; mesh_map[mi] = Some(list); done += 1; } @@ -640,11 +545,12 @@ pub fn read_gltf(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) - Ok(scene) } -fn read_mesh(r: &Reader, mj: &Value, mi: usize, scene: &mut RawScene) -> Result<Vec<usize>> { +fn read_mesh(r: &Reader, mj: &Value, mi: usize, scene: &mut RawScene, watch: &Watch) -> Result<Vec<usize>> { let mesh_name = mj.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("Mesh {mi}")); let prims = arr(mj, "primitives"); let mut out = Vec::new(); for (pi, p) in prims.iter().enumerate() { + watch.poll(0)?; let mode = p.get("mode").and_then(Value::as_u64).unwrap_or(4); if !(4..=6).contains(&mode) { scene.warnings.push(format!("{mesh_name}: primitive {pi} draws points or lines and was skipped")); @@ -676,7 +582,7 @@ fn read_mesh(r: &Reader, mj: &Value, mi: usize, scene: &mut RawScene) -> Result< if c != 2 || f.len() / 2 != n { return malformed(format!("{mesh_name}: TEXCOORD_{set} must be VEC2 with one entry per vertex")); } - m.uvs.push(f.as_chunks::<2>().0.iter().map(|c| Vec2::new(c[0], c[1])).collect()); + m.uvs.push(f.as_chunks::<2>().0.iter().map(|c| Vec2::new(c[0], 1.0 - c[1])).collect()); set += 1; } if let Some(ci) = idx(attrs, "COLOR_0")? { @@ -722,8 +628,317 @@ fn read_mesh(r: &Reader, mj: &Value, mi: usize, scene: &mut RawScene) -> Result< scene.warnings.push(format!("{mesh_name}: missing material {mat}")); } } + if let Some(ti) = idx(attrs, "TANGENT")? { + let (f, c) = r.floats(ti)?; + if c != 4 || f.len() / 4 != n { + return malformed(format!("{mesh_name}: TANGENT must be VEC4 with one entry per vertex")); + } + let t: Vec<Vec4> = f.as_chunks::<4>().0.iter().map(|v| Vec4::new(v[0], v[1], v[2], if v[3] < 0.0 { -1.0 } else { 1.0 })).collect(); + scene.tangents.resize(scene.meshes.len(), Vec::new()); + scene.tangents.push(t); + } scene.meshes.push(m); out.push(scene.meshes.len() - 1); } Ok(out) } + +struct Textures<'a> { + json: &'a Value, + uris: BTreeMap<usize, String>, + cache: BTreeMap<(usize, u8, u32), usize>, +} + +fn wrap_of(code: u64) -> Wrap { + match code { + 33071 => Wrap::Clamp, + 33648 => Wrap::Mirror, + _ => Wrap::Repeat, + } +} + +fn filter_of(mag: Option<u64>, min: Option<u64>) -> Filter { + match (mag, min) { + (Some(9728), None | Some(9728) | Some(9984) | Some(9986)) => Filter::Nearest, + (_, Some(9728) | Some(9729)) => Filter::Bilinear, + _ => Filter::Trilinear, + } +} + +/// glTF's `KHR_texture_transform` (`T * R(-r) * S` on uvs whose v grows downwards) as a slot transform on uvs whose +/// v grows upwards, the convention the texture sampler reads (row 0 at v = 1). +pub fn gltf_texture_transform(offset: [f32; 2], rotation: f32, scale: [f32; 2]) -> UvTransform { + let (s, c) = rotation.sin_cos(); + UvTransform { + offset: [offset[0] + scale[1] * s, 1.0 - offset[1] - scale[1] * c], + scale, + rotation, + ..UvTransform::default() + } +} + +fn image_uri(r: &Reader, siblings: &Siblings, si: usize, tex: &mut Textures, scene: &mut RawScene) -> Result<Option<String>> { + if let Some(u) = tex.uris.get(&si) { + return Ok(Some(u.clone())); + } + let Some(img) = arr(tex.json, "images").get(si) else { + scene.warnings.push(format!("a texture names missing image {si}")); + return Ok(None); + }; + let name = img.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("image {si}")); + let uri = match (img.get("uri").and_then(Value::as_str), idx(img, "bufferView")?) { + (Some(u), _) if u.starts_with("data:") => match data_uri(u) { + Some(Ok(bytes)) => scene.add_image(name, bytes), + _ => { + scene.warnings.push(format!("{name}: its data URI could not be decoded; the texture was skipped")); + return Ok(None); + } + }, + (Some(u), _) => match siblings.resolve(u) { + Ok(p) => p.to_string_lossy().into_owned(), + Err(IoError::OutsideFolder(_)) => { + scene.warnings.push(format!("texture file {u} lies outside the model's folder and was not read")); + u.to_string() + } + Err(_) => { + scene.warnings.push(format!("texture file {u} was not found beside the model")); + u.to_string() + } + }, + (None, Some(bv)) => { + let v = r.views.get(bv).ok_or_else(|| IoError::Malformed(format!("image {si} names missing bufferView {bv}")))?; + let bytes = r.buffers[v.buffer][v.offset..v.offset + v.length].to_vec(); + scene.add_image(name, bytes) + } + (None, None) => { + scene.warnings.push(format!("{name} has neither a uri nor a bufferView; the texture was skipped")); + return Ok(None); + } + }; + tex.uris.insert(si, uri.clone()); + Ok(Some(uri)) +} + +fn texture_slot( + r: &Reader, + siblings: &Siblings, + info: &Value, + role: TextureRole, + space: &'static str, + tex: &mut Textures, + scene: &mut RawScene, +) -> Result<Option<(usize, TextureSlot)>> { + let Some(ti) = idx(info, "index")? else { return Ok(None) }; + let tt = info.get("extensions").and_then(|e| e.get("KHR_texture_transform")); + let uv = match tt.map(|t| idx(t, "texCoord")).transpose()?.flatten() { + Some(set) => set, + None => idx(info, "texCoord")?.unwrap_or(0), + } as u32; + let Some(t) = arr(tex.json, "textures").get(ti) else { + scene.warnings.push(format!("a material names missing texture {ti}")); + return Ok(None); + }; + let mut source = idx(t, "source")?; + if let Some(ext) = t.get("extensions").and_then(Value::as_object) { + for v in ext.values() { + if let Some(s) = idx(v, "source")? { + source.get_or_insert(s); + } + } + } + let Some(si) = source else { return Ok(None) }; + let key = (si, role as u8, uv); + let index = match tex.cache.get(&key) { + Some(&i) => i, + None => { + let Some(uri) = image_uri(r, siblings, si, tex, scene)? else { return Ok(None) }; + scene.textures.push(RawTexture { uri, role, uv_set: uv, colour_space: space }); + tex.cache.insert(key, scene.textures.len() - 1); + scene.textures.len() - 1 + } + }; + let mut slot = TextureSlot { projection: MapProjection::Uv { set: uv }, ..TextureSlot::default() }; + if let Some(t) = tt { + let offset = floats::<2>(t, "offset")?.unwrap_or([0.0, 0.0]); + let scale = floats::<2>(t, "scale")?.unwrap_or([1.0, 1.0]); + slot.transform = gltf_texture_transform(offset, num(t, "rotation", 0.0), scale); + } + if let Some(sampler) = idx(t, "sampler")?.and_then(|s| arr(tex.json, "samplers").get(s)) { + let code = |k: &str| sampler.get(k).and_then(Value::as_u64); + let (ws, wt) = (code("wrapS").unwrap_or(10497), code("wrapT").unwrap_or(10497)); + if ws != wt { + scene.warnings.push(format!("texture {ti} wraps differently along u and v; its u wrapping is used for both")); + } + slot.wrap = wrap_of(ws); + slot.filter = filter_of(code("magFilter"), code("minFilter")); + } + Ok(Some((index, slot))) +} + +struct Want<'a> { + info: &'a Value, + what: &'static str, + role: TextureRole, + space: &'static str, + inputs: &'a [(MaterialInput, Channel, Option<ColourSpace>)], + strength: f32, +} + +fn want<'a>( + parent: Option<&'a Value>, + key: &'static str, + role: TextureRole, + space: &'static str, + inputs: &'a [(MaterialInput, Channel, Option<ColourSpace>)], +) -> Option<Want<'a>> { + let info = parent?.get(key)?; + let strength = info.get("scale").and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite()).unwrap_or(1.0); + Some(Want { info, what: key, role, space, inputs, strength }) +} + +const BASE: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[(MaterialInput::BaseColor, Channel::Rgb, Some(ColourSpace::Srgb))]; +const BASE_ALPHA: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[ + (MaterialInput::BaseColor, Channel::Rgb, Some(ColourSpace::Srgb)), + (MaterialInput::GeometryOpacity, Channel::A, Some(ColourSpace::Srgb)), +]; +const METAL_ROUGH: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[ + (MaterialInput::SpecularRoughness, Channel::G, Some(ColourSpace::Data)), + (MaterialInput::BaseMetalness, Channel::B, Some(ColourSpace::Data)), +]; +const NORMAL: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[(MaterialInput::Normal, Channel::Rgb, Some(ColourSpace::Data))]; +const EMISSION: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[(MaterialInput::EmissionColor, Channel::Rgb, Some(ColourSpace::Srgb))]; +const COAT: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[(MaterialInput::CoatWeight, Channel::R, Some(ColourSpace::Data))]; +const COAT_ROUGH: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[(MaterialInput::CoatRoughness, Channel::G, Some(ColourSpace::Data))]; +const SPECULAR: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[(MaterialInput::SpecularWeight, Channel::A, Some(ColourSpace::Data))]; +const NONE_INPUTS: &[(MaterialInput, Channel, Option<ColourSpace>)] = &[]; + +fn read_material(r: &Reader, siblings: &Siblings, m: &Value, mi: usize, tex: &mut Textures, scene: &mut RawScene) -> Result<()> { + let mut mat = RawMaterial { + name: m.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("Material {mi}")), + roughness: 1.0, + metallic: 1.0, + base_colour: [1.0; 3], + ..Default::default() + }; + let mut extra = RawMaterialExtra::default(); + let alpha_mode = m.get("alphaMode").and_then(Value::as_str).unwrap_or("OPAQUE"); + let cutoff = num(m, "alphaCutoff", 0.5); + let pbr = m.get("pbrMetallicRoughness"); + let mut alpha = 1.0; + if let Some(pbr) = pbr { + if let Some(c) = floats::<4>(pbr, "baseColorFactor")? { + mat.base_colour = [c[0], c[1], c[2]]; + alpha = c[3]; + } + mat.metallic = num(pbr, "metallicFactor", 1.0); + mat.roughness = num(pbr, "roughnessFactor", 1.0); + } + let alpha_textured = pbr.and_then(|p| p.get("baseColorTexture")).is_some(); + match alpha_mode { + "BLEND" => mat.opacity = alpha, + "MASK" => { + mat.opacity = if alpha_textured { alpha } else if alpha >= cutoff { 1.0 } else { 0.0 }; + extra.alpha_cutoff = Some(cutoff); + } + _ => {} + } + if let Some(e) = floats::<3>(m, "emissiveFactor")? { + mat.emissive = e; + } + mat.double_sided = m.get("doubleSided").and_then(Value::as_bool).unwrap_or(false); + let ext = m.get("extensions"); + let x = |name: &str| ext.and_then(|e| e.get(name)); + let mut has_volume = false; + if let Some(v) = x("KHR_materials_volume") { + has_volume = num(v, "thicknessFactor", 0.0) > 0.0; + let c = floats::<3>(v, "attenuationColor")?.unwrap_or([1.0; 3]); + extra.attenuation = Some((c, num(v, "attenuationDistance", f32::INFINITY))); + } + if let Some(v) = x("KHR_materials_transmission") { + mat.transmission = num(v, "transmissionFactor", 0.0); + extra.thin_walled = Some(!has_volume && mat.transmission > 0.0); + } else if has_volume { + extra.thin_walled = Some(false); + } + if let Some(v) = x("KHR_materials_ior") { + mat.ior = num(v, "ior", 1.5); + } + if let Some(v) = x("KHR_materials_clearcoat") { + mat.clearcoat = num(v, "clearcoatFactor", 0.0); + mat.clearcoat_roughness = num(v, "clearcoatRoughnessFactor", 0.0); + extra.coat_ior = Some(1.5); + } + if let Some(v) = x("KHR_materials_emissive_strength") { + mat.emissive_strength = num(v, "emissiveStrength", 1.0); + } + if let Some(v) = x("KHR_materials_specular") { + mat.specular = num(v, "specularFactor", 1.0); + extra.specular_colour = floats::<3>(v, "specularColorFactor")?; + } + if let Some(v) = x("KHR_materials_sheen") { + let c = floats::<3>(v, "sheenColorFactor")?.unwrap_or([0.0; 3]); + extra.sheen = Some((c, num(v, "sheenRoughnessFactor", 0.0))); + } + if let Some(v) = x("KHR_materials_iridescence") { + let max = num(v, "iridescenceThicknessMaximum", 400.0); + let min = num(v, "iridescenceThicknessMinimum", 100.0); + let nm = if v.get("iridescenceThicknessTexture").is_some() { 0.5 * (min + max) } else { max }; + extra.thin_film = Some([num(v, "iridescenceFactor", 0.0), num(v, "iridescenceIor", 1.3), nm / 1000.0]); + } + if let Some(v) = x("KHR_materials_dispersion") { + let d = num(v, "dispersion", 0.0); + if d > 0.0 { + extra.abbe = Some(20.0 / d); + } + } + if let Some(v) = x("KHR_materials_anisotropy") { + extra.anisotropy = Some(num(v, "anisotropyStrength", 0.0)); + } + let base = if matches!(alpha_mode, "BLEND" | "MASK") { BASE_ALPHA } else { BASE }; + let wants: Vec<Want> = [ + want(pbr, "baseColorTexture", TextureRole::BaseColour, "srgb", base), + want(pbr, "metallicRoughnessTexture", TextureRole::OcclusionRoughnessMetalness, "linear", METAL_ROUGH), + want(Some(m), "normalTexture", TextureRole::Normal, "linear", NORMAL), + want(Some(m), "emissiveTexture", TextureRole::Emission, "srgb", EMISSION), + want(Some(m), "occlusionTexture", TextureRole::Other, "linear", NONE_INPUTS), + want(x("KHR_materials_clearcoat"), "clearcoatTexture", TextureRole::Other, "linear", COAT), + want(x("KHR_materials_clearcoat"), "clearcoatRoughnessTexture", TextureRole::Roughness, "linear", COAT_ROUGH), + want(x("KHR_materials_clearcoat"), "clearcoatNormalTexture", TextureRole::Normal, "linear", NONE_INPUTS), + want(x("KHR_materials_transmission"), "transmissionTexture", TextureRole::Other, "linear", NONE_INPUTS), + want(x("KHR_materials_specular"), "specularTexture", TextureRole::Other, "linear", SPECULAR), + want(x("KHR_materials_specular"), "specularColorTexture", TextureRole::Other, "srgb", NONE_INPUTS), + want(x("KHR_materials_sheen"), "sheenColorTexture", TextureRole::Other, "srgb", NONE_INPUTS), + want(x("KHR_materials_sheen"), "sheenRoughnessTexture", TextureRole::Other, "linear", NONE_INPUTS), + want(x("KHR_materials_volume"), "thicknessTexture", TextureRole::Other, "linear", NONE_INPUTS), + want(x("KHR_materials_iridescence"), "iridescenceTexture", TextureRole::Other, "linear", NONE_INPUTS), + want(x("KHR_materials_iridescence"), "iridescenceThicknessTexture", TextureRole::Other, "linear", NONE_INPUTS), + want(x("KHR_materials_anisotropy"), "anisotropyTexture", TextureRole::Other, "linear", NONE_INPUTS), + ] + .into_iter() + .flatten() + .collect(); + let mut unused = Vec::new(); + for w in wants { + let Some((index, slot)) = texture_slot(r, siblings, w.info, w.role, w.space, tex, scene)? else { continue }; + if !mat.textures.contains(&index) { + mat.textures.push(index); + } + if w.inputs.is_empty() && w.what != "occlusionTexture" { + unused.push(w.what); + } + for &(input, channel, colour_space) in w.inputs { + let mut s = TextureSlot { channel, colour_space, multiply: input != MaterialInput::Normal, ..slot.clone() }; + if input == MaterialInput::Normal { + s.strength = w.strength; + } + extra.slots.push(RawSlot { input, texture: index, slot: s }); + } + } + if !unused.is_empty() { + scene.warnings.push(format!("{}: {} kept with the material but drive no input yet", mat.name, unused.join(", "))); + } + scene.materials.push(mat); + let i = scene.materials.len() - 1; + *scene.extra_mut(i) = extra; + Ok(()) +} diff --git a/native/crates/fsh-io/src/jpeg.rs b/native/crates/fsh-io/src/jpeg.rs new file mode 100644 index 00000000..56540f43 --- /dev/null +++ b/native/crates/fsh-io/src/jpeg.rs @@ -0,0 +1,44 @@ +use crate::error::{IoError, Result}; +use crate::picture::{Picture, Samples}; +use zune_jpeg::zune_core::bytestream::ZCursor; +use zune_jpeg::zune_core::colorspace::ColorSpace; +use zune_jpeg::zune_core::options::DecoderOptions; +use zune_jpeg::JpegDecoder; + +/// Largest width or height accepted. +pub const JPEG_MAX_SIDE: usize = 16384; + +/// True when the bytes start like a JPEG file (SOI then a marker). +pub fn is_jpeg(bytes: &[u8]) -> bool { + bytes.len() >= 3 && bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff +} + +/// Decodes a baseline or progressive JPEG (greyscale, YCbCr, RGB, CMYK or YCCK) into an 8-bit picture with 1 +/// (grey) or 3 (RGB) channels, top row first; the EXIF orientation is ignored. +pub fn read_jpeg(bytes: &[u8]) -> Result<Picture> { + if !is_jpeg(bytes) { + return Err(IoError::Malformed("not a JPEG file".into())); + } + let options = DecoderOptions::default().set_max_width(JPEG_MAX_SIDE).set_max_height(JPEG_MAX_SIDE).set_strict_mode(false); + let mut probe = JpegDecoder::new_with_options(ZCursor::new(bytes), options); + probe.decode_headers().map_err(|e| IoError::Malformed(format!("JPEG header: {e:?}")))?; + let grey = matches!(probe.input_colorspace(), Some(ColorSpace::Luma)); + let out = if grey { ColorSpace::Luma } else { ColorSpace::RGB }; + let mut decoder = JpegDecoder::new_with_options(ZCursor::new(bytes), options.jpeg_set_out_colorspace(out)); + let data = decoder.decode().map_err(|e| IoError::Malformed(format!("JPEG data: {e:?}")))?; + let info = decoder.info().ok_or_else(|| IoError::Malformed("JPEG without a frame header".into()))?; + let (w, h) = (info.width as u32, info.height as u32); + let px = w as usize * h as usize; + if px == 0 { + return Err(IoError::Malformed("JPEG of zero size".into())); + } + let channels = data.len() / px; + match channels { + 1 | 3 if data.len() == px * channels => Picture::new(w, h, channels as u8, Samples::U8(data)), + 4 if data.len() == px * 4 => { + let rgb = data.as_chunks::<4>().0.iter().flat_map(|c| [c[0], c[1], c[2]]).collect(); + Picture::new(w, h, 3, Samples::U8(rgb)) + } + _ => Err(IoError::Malformed(format!("JPEG decoded to {} bytes for {w}x{h}", data.len()))), + } +} diff --git a/native/crates/fsh-io/src/lib.rs b/native/crates/fsh-io/src/lib.rs index 767dc6bf..73f443c0 100644 --- a/native/crates/fsh-io/src/lib.rs +++ b/native/crates/fsh-io/src/lib.rs @@ -5,10 +5,14 @@ mod clean; mod convert; pub mod deflate; mod error; +#[cfg(not(target_arch = "wasm32"))] +mod fbx; mod exr; +pub mod family; mod glb_write; mod gltf; mod hdr; +mod jpeg; mod obj; mod paths; mod picture; @@ -16,22 +20,35 @@ mod ply; mod png; mod raw; mod stl; +mod tangents; +mod threemf; +mod triangulate; mod watch; +mod zip; -pub use clean::{clean, world_bounds, CleanOptions, CleanReport}; -pub use convert::{surface_params, to_import_command, ImportOptions, EMISSIVE_NITS_PER_UNIT}; +pub use clean::{clean, guess_unit, world_bounds, CleanOptions, CleanReport, UnitGuess}; +pub use convert::{ + surface_params, to_import_command, ImportOptions, ALPHA_CUTOFF_KEY, EMISSIVE_NITS_PER_UNIT, VERTEX_COLOURS_KEY, + VERTEX_COLOURS_MULTIPLY, +}; pub use error::{IoError, Result}; pub use exr::write_exr; pub use glb_write::write_glb; -pub use gltf::read_gltf; +pub use gltf::{gltf_texture_transform, read_gltf}; pub use hdr::{read_hdr, write_hdr}; +pub use jpeg::{is_jpeg, read_jpeg, JPEG_MAX_SIDE}; pub use obj::{read_obj, roughness_from_phong}; pub use paths::Siblings; -pub use picture::{FloatPicture, Picture, Samples}; +pub use picture::{decode_image, detect_image, half_to_f32, DecodedImage, FloatPicture, ImageFormat, ImagePixels, Picture, Samples}; pub use ply::read_ply; pub use png::{read_png, write_png, write_png_rgb16, write_png_rgba8}; -pub use raw::{RawMaterial, RawMesh, RawNode, RawScene, RawTexture, UpAxis}; +pub use raw::{ + RawImage, RawMaterial, RawMaterialExtra, RawMesh, RawNode, RawScene, RawSlot, RawTexture, UpAxis, EMBEDDED_PREFIX, +}; +#[cfg(not(target_arch = "wasm32"))] +pub use fbx::read_fbx; pub use stl::read_stl; +pub use threemf::read_3mf; pub use watch::{Stage, Watch}; use std::path::Path; @@ -49,11 +66,32 @@ pub enum ModelFormat { Stl, /// PLY, ASCII or binary. Ply, + /// 3D Manufacturing Format package. + ThreeMf, + /// Autodesk FBX, binary or ASCII (not in the wasm32 build). + Fbx, + /// STEP (ISO 10303-21); read by the CAD worker through fsh-cad, not by this crate. + Step, + /// IGES; read by the CAD worker through fsh-cad, not by this crate. + Iges, } +/// Short name used by the import commands. +pub type Format = ModelFormat; + impl ModelFormat { /// Every format. - pub const ALL: [ModelFormat; 5] = [ModelFormat::Gltf, ModelFormat::Glb, ModelFormat::Obj, ModelFormat::Stl, ModelFormat::Ply]; + pub const ALL: [ModelFormat; 9] = [ + ModelFormat::Gltf, + ModelFormat::Glb, + ModelFormat::Obj, + ModelFormat::Stl, + ModelFormat::Ply, + ModelFormat::ThreeMf, + ModelFormat::Fbx, + ModelFormat::Step, + ModelFormat::Iges, + ]; /// Lower-case extension. pub fn extension(self) -> &'static str { @@ -63,6 +101,10 @@ impl ModelFormat { ModelFormat::Obj => "obj", ModelFormat::Stl => "stl", ModelFormat::Ply => "ply", + ModelFormat::ThreeMf => "3mf", + ModelFormat::Fbx => "fbx", + ModelFormat::Step => "step", + ModelFormat::Iges => "iges", } } @@ -74,9 +116,31 @@ impl ModelFormat { "obj" => ModelFormat::Obj, "stl" => ModelFormat::Stl, "ply" => ModelFormat::Ply, + "3mf" => ModelFormat::ThreeMf, + "fbx" => ModelFormat::Fbx, + "step" | "stp" => ModelFormat::Step, + "iges" | "igs" => ModelFormat::Iges, _ => return None, }) } + + /// True for formats this crate reads itself; false for the B-rep formats the CAD worker reads. + pub fn read_here(self) -> bool { + !matches!(self, ModelFormat::Step | ModelFormat::Iges) + } +} + +fn looks_like_fbx(bytes: &[u8]) -> bool { + bytes.starts_with(b"Kaydara FBX Binary") || bytes[..bytes.len().min(4096)].windows(18).any(|w| w == b"FBXHeaderExtension") +} + +fn looks_like_step(bytes: &[u8]) -> bool { + let trimmed = bytes.iter().position(|b| !b.is_ascii_whitespace()).map(|i| &bytes[i..]).unwrap_or(&[]); + trimmed.starts_with(b"ISO-10303-21;") +} + +fn looks_like_iges(bytes: &[u8]) -> bool { + bytes.len() >= 80 && bytes[72] == b'S' && bytes[73..80].iter().all(|b| b.is_ascii_digit() || *b == b' ') } fn looks_like_obj(bytes: &[u8]) -> bool { @@ -95,9 +159,21 @@ pub fn detect_model(name: &str, bytes: &[u8]) -> Option<ModelFormat> { if ply::is_ply(bytes) { return Some(ModelFormat::Ply); } + if threemf::is_3mf(bytes) { + return Some(ModelFormat::ThreeMf); + } + if looks_like_fbx(bytes) { + return Some(ModelFormat::Fbx); + } if stl::is_binary_stl(bytes) || stl::is_ascii_stl(bytes) { return Some(ModelFormat::Stl); } + if looks_like_step(bytes) { + return Some(ModelFormat::Step); + } + if looks_like_iges(bytes) { + return Some(ModelFormat::Iges); + } let ext = Path::new(name).extension().and_then(|e| e.to_str()).and_then(ModelFormat::from_extension); let trimmed = bytes.iter().position(|b| !b.is_ascii_whitespace()).map(|i| &bytes[i..]).unwrap_or(&[]); if trimmed.starts_with(b"{") && (ext == Some(ModelFormat::Gltf) || bytes.windows(7).take(1 << 16).any(|w| w == b"\"asset\"")) { @@ -119,6 +195,15 @@ pub fn read_model_bytes(format: ModelFormat, bytes: &[u8], name: &str, siblings: ModelFormat::Obj => read_obj(bytes, name, siblings, watch), ModelFormat::Stl => read_stl(bytes, name, watch), ModelFormat::Ply => read_ply(bytes, name, watch), + ModelFormat::ThreeMf => read_3mf(bytes, name, watch), + #[cfg(not(target_arch = "wasm32"))] + ModelFormat::Fbx => read_fbx(bytes, name, siblings, watch), + #[cfg(target_arch = "wasm32")] + ModelFormat::Fbx => Err(IoError::Unsupported("FBX files are read by the desktop engine, not in the browser".into())), + ModelFormat::Step | ModelFormat::Iges => Err(IoError::Unsupported(format!( + "{} files are read by the CAD worker (fsh-cad), not by the mesh readers", + format.extension().to_ascii_uppercase() + ))), } } @@ -130,6 +215,68 @@ pub fn read_model(path: &Path, watch: &Watch) -> Result<RawScene> { read_model_bytes(format, &bytes, &paths::stem(path), &Siblings::of(path), watch) } +/// Same as [`detect_model`]. +pub fn detect(name: &str, bytes: &[u8]) -> Option<ModelFormat> { + detect_model(name, bytes) +} + +/// Same as [`read_model`]: reads any model file this crate reads; STEP and IGES answer that the CAD worker reads them. +pub fn read_any(path: &Path, watch: &Watch) -> Result<RawScene> { + read_model(path, watch) +} + +/// What a model file holds, read without cleaning or touching any document (for `import.probe`). +#[derive(Clone, Debug, PartialEq)] +pub struct Probe { + /// Detected format. + pub format: ModelFormat, + /// Unit the file declares, if any. + pub units_declared: Option<fsh_core::LengthUnit>, + /// The size-based guess (always filled, so the window can offer it even when the file declares a unit). + pub units_guess: UnitGuess, + /// True when no unit is declared, so an import would use the guess. + pub unit_guessed: bool, + /// Up axis the file declares, if any. + pub up_axis: Option<UpAxis>, + /// World bounds in file units and file axes. + pub bounds: fsh_core::Aabb, + /// Triangles drawn by the nodes (instanced meshes counted once per use). + pub triangles: usize, + /// Meshes in the file. + pub meshes: usize, + /// Nodes in the file. + pub nodes: usize, + /// Materials in the file. + pub materials: usize, + /// Reader warnings. + pub warnings: Vec<String>, +} + +/// Reads a model file and summarises it; STEP and IGES answer that the CAD worker reads them. +pub fn probe(path: &Path, watch: &Watch) -> Result<Probe> { + let bytes = std::fs::read(path)?; + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let format = detect_model(name, &bytes).ok_or_else(|| IoError::UnknownFormat(name.to_string()))?; + let mut raw = read_model_bytes(format, &bytes, &paths::stem(path), &Siblings::of(path), watch)?; + raw.add_nodes_for_loose_meshes(); + let bounds = world_bounds(&raw); + let triangles = raw.nodes.iter().flat_map(|n| n.meshes.iter()).filter_map(|&m| raw.meshes.get(m)).map(RawMesh::triangle_count).sum(); + let units_declared = raw.unit.filter(|u| *u != fsh_core::LengthUnit::Unspecified); + Ok(Probe { + format, + units_declared, + units_guess: guess_unit(bounds.diagonal().length()), + unit_guessed: units_declared.is_none(), + up_axis: raw.up_axis, + bounds, + triangles, + meshes: raw.meshes.len(), + nodes: raw.nodes.len(), + materials: raw.materials.len(), + warnings: raw.warnings, + }) +} + /// Reads, cleans and converts a model file into one `scene.import` command plus the clean-up report. pub fn import_file( path: &Path, diff --git a/native/crates/fsh-io/src/obj.rs b/native/crates/fsh-io/src/obj.rs index 0d9272eb..aa550bed 100644 --- a/native/crates/fsh-io/src/obj.rs +++ b/native/crates/fsh-io/src/obj.rs @@ -1,9 +1,11 @@ use crate::error::{malformed, IoError, Result}; use crate::paths::Siblings; -use crate::raw::{RawMaterial, RawMesh, RawNode, RawScene, RawTexture}; +use crate::raw::{RawMaterial, RawMesh, RawNode, RawScene, RawSlot, RawTexture}; +use crate::triangulate::triangulate; use crate::watch::{Stage, Watch}; use fsh_core::{Vec2, Vec3, Vec4}; -use fsh_scene::TextureRole; +use fsh_scene::fsh_materials::Wrap; +use fsh_scene::{Channel, MaterialInput, TextureRole, TextureSlot, UvTransform}; use std::collections::HashMap; const NONE: u32 = u32::MAX; @@ -97,7 +99,7 @@ pub fn read_obj(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) -> "vt" => { let u = nums::<1>(rest, "vt", line)?[0]; let v = rest.get(1).and_then(|t| t.parse::<f32>().ok()).unwrap_or(0.0); - tex.push(Vec2::new(u, 1.0 - v)); + tex.push(Vec2::new(u, v)); } "vn" => nor.push(Vec3::from(nums::<3>(rest, "vn", line)?)), "f" | "fo" => { @@ -117,8 +119,13 @@ pub fn read_obj(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) -> poly.push([v, vt, vn]); } let part = parts.last_mut().expect("parts is never empty"); - for i in 1..poly.len() - 1 { - part.corners.extend_from_slice(&[poly[0], poly[i], poly[i + 1]]); + if poly.len() == 3 { + part.corners.extend_from_slice(&poly); + } else { + let pts: Vec<Vec3> = poly.iter().map(|c| pos[c[0] as usize]).collect(); + for t in triangulate(&pts) { + part.corners.extend_from_slice(&[poly[t[0]], poly[t[1]], poly[t[2]]]); + } } } "g" | "o" => { @@ -152,11 +159,37 @@ pub fn read_obj(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) -> if any_colour { col.resize(pos.len(), Vec3::ONE); } - let mut root = RawNode::new(name, None, Vec::new()); + scene.nodes.push(RawNode::new(name, None, Vec::new())); + let mut groups: Vec<&str> = Vec::new(); + for p in parts.iter().filter(|p| !p.corners.is_empty()) { + if !groups.contains(&p.name.as_str()) { + groups.push(&p.name); + } + } + let nested = groups.len() > 1; + let multi: Vec<bool> = groups.iter().map(|g| parts.iter().filter(|p| !p.corners.is_empty() && p.name == *g).count() > 1).collect(); + let group_node: Vec<usize> = if nested { + groups + .iter() + .map(|g| { + scene.nodes.push(RawNode::new(*g, Some(0), Vec::new())); + scene.nodes.len() - 1 + }) + .collect() + } else { + vec![0] + }; + let names: Vec<String> = groups.iter().map(|g| g.to_string()).collect(); for (pi, part) in parts.into_iter().enumerate() { if part.corners.is_empty() { continue; } + let gi = names.iter().position(|g| *g == part.name).unwrap_or(0); + let node = group_node[gi.min(group_node.len() - 1)]; + let mesh_name = match (&part.material, multi[gi]) { + (Some(m), true) => m.clone(), + _ => part.name.clone(), + }; if pi % 64 == 0 { watch.step(Stage::Reading, 1.0)?; } @@ -166,9 +199,10 @@ pub fn read_obj(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) -> scene.warnings.push(format!("{}: some corners lack texture coordinates; UVs dropped", part.name)); } let mut map: HashMap<[u32; 3], u32> = HashMap::new(); - let mut m = RawMesh { name: part.name.clone(), ..Default::default() }; + let mut m = RawMesh { name: mesh_name, ..Default::default() }; let mut uv = Vec::new(); - for c in &part.corners { + for (ci, c) in part.corners.iter().enumerate() { + watch.poll(ci)?; let key = [c[0], if has_uv { c[1] } else { NONE }, if has_n { c[2] } else { NONE }]; let next = m.positions.len() as u32; let id = *map.entry(key).or_insert_with(|| { @@ -203,9 +237,9 @@ pub fn read_obj(bytes: &[u8], name: &str, siblings: &Siblings, watch: &Watch) -> m.material = Some(slot); } scene.meshes.push(m); - root.meshes.push(scene.meshes.len() - 1); + let mi = scene.meshes.len() - 1; + scene.nodes[node].meshes.push(mi); } - scene.nodes.push(root); watch.step(Stage::Reading, 1.0)?; Ok(scene) } @@ -240,7 +274,7 @@ fn read_mtl(bytes: &[u8], siblings: &Siblings, scene: &mut RawScene, index: &mut let Some(ci) = cur else { continue }; let f1 = || rest.first().and_then(|t| t.parse::<f32>().ok()).filter(|v| v.is_finite()); let f3 = || nums::<3>(rest, kw, ln + 1).ok().filter(|v| v.iter().all(|x| x.is_finite())); - let mut texture: Option<(TextureRole, &'static str)> = None; + let mut texture: Option<(TextureRole, &'static str, MaterialInput)> = None; let m = &mut scene.materials[ci]; match kw { "Kd" => { @@ -300,27 +334,137 @@ fn read_mtl(bytes: &[u8], siblings: &Siblings, scene: &mut RawScene, index: &mut m.opacity = (1.0 - v).clamp(0.0, 1.0); } } - "map_Kd" => texture = Some((TextureRole::BaseColour, "srgb")), - "map_Pr" | "map_Ns" => texture = Some((TextureRole::Roughness, "linear")), - "map_Pm" => texture = Some((TextureRole::Metalness, "linear")), - "map_Bump" | "map_bump" | "bump" => texture = Some((TextureRole::Bump, "linear")), - "norm" | "map_Kn" => texture = Some((TextureRole::Normal, "linear")), - "map_d" => texture = Some((TextureRole::Opacity, "linear")), - "map_Ke" => texture = Some((TextureRole::Emission, "srgb")), + "map_Kd" => texture = Some((TextureRole::BaseColour, "srgb", MaterialInput::BaseColor)), + "map_Ks" => texture = Some((TextureRole::Other, "srgb", MaterialInput::SpecularWeight)), + "map_Pr" => texture = Some((TextureRole::Roughness, "linear", MaterialInput::SpecularRoughness)), + "map_Ns" => texture = Some((TextureRole::Roughness, "linear", MaterialInput::SpecularRoughness)), + "map_Pm" => texture = Some((TextureRole::Metalness, "linear", MaterialInput::BaseMetalness)), + "map_Bump" | "map_bump" | "bump" => texture = Some((TextureRole::Bump, "linear", MaterialInput::Bump)), + "norm" | "map_Kn" => texture = Some((TextureRole::Normal, "linear", MaterialInput::Normal)), + "map_d" => texture = Some((TextureRole::Opacity, "linear", MaterialInput::GeometryOpacity)), + "map_Ke" => texture = Some((TextureRole::Emission, "srgb", MaterialInput::EmissionColor)), + "disp" => texture = Some((TextureRole::Other, "linear", MaterialInput::Displacement)), _ => {} } - if let Some((role, space)) = texture { - let Some(file) = rest.last() else { continue }; + if let Some((role, space, input)) = texture { + let o = map_options(rest); + if o.file.is_empty() { + continue; + } + let file = o.file.as_str(); let uri = match siblings.resolve(file) { Ok(p) => p.to_string_lossy().into_owned(), + Err(IoError::OutsideFolder(_)) => { + scene.warnings.push(format!("texture file {file} lies outside the model's folder and was not read")); + file.to_string() + } Err(_) => { scene.warnings.push(format!("texture file {file} was not found beside the model")); file.to_string() } }; + let channel = match (o.channel, input) { + (Some(c), _) => c, + (None, MaterialInput::GeometryOpacity) if has_alpha(&uri) => Channel::A, + (None, MaterialInput::GeometryOpacity) => Channel::Luminance, + _ => Channel::Rgb, + }; + let mut slot = TextureSlot { + transform: UvTransform { offset: o.offset, scale: o.scale, ..UvTransform::default() }, + wrap: if o.clamp { Wrap::Clamp } else { Wrap::Repeat }, + channel, + invert: kw == "map_Ns", + ..TextureSlot::for_input(input, fsh_core::TextureKey::NONE) + }; + if input == MaterialInput::Bump { + slot.strength *= o.bump; + } + if input == MaterialInput::EmissionColor && scene.materials[ci].emissive.iter().all(|v| *v <= 0.0) { + scene.materials[ci].emissive = [1.0; 3]; + } scene.textures.push(RawTexture { uri, role, uv_set: 0, colour_space: space }); let t = scene.textures.len() - 1; scene.materials[ci].textures.push(t); + let x = scene.extra_mut(ci); + x.slots.retain(|s| s.input != input); + x.slots.push(RawSlot { input, texture: t, slot }); } } } + +struct MapOptions { + file: String, + offset: [f32; 2], + scale: [f32; 2], + clamp: bool, + bump: f32, + channel: Option<Channel>, +} + +/// Reads the options before a map's file name (`-o u v w`, `-s u v w`, `-clamp on`, `-bm m`, `-imfchan c`; others +/// are skipped with their arguments); the rest of the line is the file name, spaces included. +fn map_options(toks: &[&str]) -> MapOptions { + let mut o = MapOptions { file: String::new(), offset: [0.0; 2], scale: [1.0; 2], clamp: false, bump: 1.0, channel: None }; + let num = |t: Option<&&str>| t.and_then(|t| t.parse::<f32>().ok()).filter(|v| v.is_finite()); + let mut i = 0; + while i < toks.len() { + let t = toks[i]; + if !t.starts_with('-') || num(Some(&t)).is_some() { + break; + } + i += 1; + match t { + "-o" | "-s" | "-t" => { + let mut v = Vec::new(); + while v.len() < 3 && i + 1 < toks.len() { + match num(toks.get(i)) { + Some(x) => v.push(x), + None => break, + } + i += 1; + } + let d = if t == "-s" { 1.0 } else { 0.0 }; + let pair = [v.first().copied().unwrap_or(d), v.get(1).copied().unwrap_or(d)]; + match t { + "-o" => o.offset = pair, + "-s" => o.scale = pair, + _ => {} + } + } + "-mm" => i += 2, + "-clamp" => { + o.clamp = toks.get(i).is_some_and(|v| v.eq_ignore_ascii_case("on")); + i += 1; + } + "-bm" => { + o.bump = num(toks.get(i)).unwrap_or(1.0); + i += 1; + } + "-imfchan" => { + o.channel = match toks.get(i).copied() { + Some("r") => Some(Channel::R), + Some("g") => Some(Channel::G), + Some("b") => Some(Channel::B), + Some("m") | Some("l") | Some("z") => Some(Channel::Luminance), + _ => None, + }; + i += 1; + } + _ => i += 1, + } + } + o.file = toks[i.min(toks.len())..].join(" "); + o +} + +/// True when the bytes start a PNG whose colour type carries alpha (grey-alpha or RGBA). +pub(crate) fn png_has_alpha(head: &[u8]) -> bool { + head.len() >= 26 && head.starts_with(&[0x89, b'P', b'N', b'G']) && matches!(head[25], 4 | 6) +} + +/// True when the file at `path` is a PNG with alpha. +pub(crate) fn has_alpha(path: &str) -> bool { + use std::io::Read; + let mut head = [0u8; 26]; + std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && png_has_alpha(&head) +} diff --git a/native/crates/fsh-io/src/picture.rs b/native/crates/fsh-io/src/picture.rs index 0a75a1a6..66cdb738 100644 --- a/native/crates/fsh-io/src/picture.rs +++ b/native/crates/fsh-io/src/picture.rs @@ -116,3 +116,683 @@ impl FloatPicture { } } } + +/// Image file formats `decode_image` reads. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ImageFormat { + /// PNG, 1 to 16 bits. + Png, + /// JPEG, baseline or progressive. + Jpeg, + /// Radiance RGBE. + Hdr, + /// OpenEXR, single-part scanline. + Exr, +} + +/// RGBA pixels, row-major, top row first. Integer pixels are as stored in the file (normally sRGB encoded); +/// float pixels are scene-linear. +#[derive(Clone, Debug, PartialEq)] +pub enum ImagePixels { + /// 8 bits per channel. + Rgba8(Vec<u8>), + /// 16 bits per channel. + Rgba16(Vec<u16>), + /// 32-bit float per channel. + RgbaF32(Vec<f32>), +} + +/// A decoded image of any format `decode_image` reads, always expanded to four channels. +#[derive(Clone, Debug, PartialEq)] +pub struct DecodedImage { + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Format it came from. + pub format: ImageFormat, + /// Channels in the file (1 grey, 2 grey and alpha, 3 RGB, 4 RGBA). + pub channels: u8, + /// Pixels. + pub pixels: ImagePixels, +} + +/// Detects an image format by content, then by the extension of `name` (png, jpg, jpeg, jpe, jfif, hdr, rgbe, exr). +pub fn detect_image(name: &str, bytes: &[u8]) -> Option<ImageFormat> { + if crate::png::is_png(bytes) { + return Some(ImageFormat::Png); + } + if crate::jpeg::is_jpeg(bytes) { + return Some(ImageFormat::Jpeg); + } + if crate::hdr::is_hdr(bytes) { + return Some(ImageFormat::Hdr); + } + if bytes.starts_with(&EXR_MAGIC) { + return Some(ImageFormat::Exr); + } + let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + match ext.as_deref() { + Some("png") => Some(ImageFormat::Png), + Some("jpg" | "jpeg" | "jpe" | "jfif") => Some(ImageFormat::Jpeg), + Some("hdr" | "rgbe") => Some(ImageFormat::Hdr), + Some("exr") => Some(ImageFormat::Exr), + _ => None, + } +} + +/// Decodes a PNG, JPEG, Radiance HDR or OpenEXR file into RGBA pixels (grey expanded, opaque alpha added). +pub fn decode_image(name: &str, bytes: &[u8]) -> Result<DecodedImage> { + let format = detect_image(name, bytes).ok_or_else(|| IoError::UnknownFormat(name.to_string()))?; + let (width, height, channels, pixels) = match format { + ImageFormat::Png => integer_rgba(crate::png::read_png(bytes)?), + ImageFormat::Jpeg => integer_rgba(crate::jpeg::read_jpeg(bytes)?), + ImageFormat::Hdr => float_rgba(crate::hdr::read_hdr(bytes)?), + ImageFormat::Exr => read_exr_rgba(bytes)?, + }; + Ok(DecodedImage { width, height, format, channels, pixels }) +} + +fn expand<T: Copy>(src: &[T], channels: usize, opaque: T) -> Vec<T> { + let mut out = Vec::with_capacity(src.len() / channels.max(1) * 4); + for px in src.chunks_exact(channels.max(1)) { + match channels { + 1 => out.extend_from_slice(&[px[0], px[0], px[0], opaque]), + 2 => out.extend_from_slice(&[px[0], px[0], px[0], px[1]]), + 3 => out.extend_from_slice(&[px[0], px[1], px[2], opaque]), + _ => out.extend_from_slice(&px[..4]), + } + } + out +} + +fn integer_rgba(p: Picture) -> (u32, u32, u8, ImagePixels) { + let c = p.channels as usize; + let pixels = match &p.samples { + Samples::U8(v) => ImagePixels::Rgba8(expand(v, c, u8::MAX)), + Samples::U16(v) => ImagePixels::Rgba16(expand(v, c, u16::MAX)), + }; + (p.width, p.height, p.channels, pixels) +} + +fn float_rgba(p: FloatPicture) -> (u32, u32, u8, ImagePixels) { + (p.width, p.height, p.channels, ImagePixels::RgbaF32(expand(&p.data, p.channels as usize, 1.0))) +} + +const EXR_MAGIC: [u8; 4] = [0x76, 0x2f, 0x31, 0x01]; +const EXR_MAX_SIDE: i64 = 16384; + +fn exr_bad<T>(what: impl Into<String>) -> Result<T> { + Err(IoError::Malformed(format!("EXR: {}", what.into()))) +} + +/// IEEE 754 half to single precision. +pub fn half_to_f32(h: u16) -> f32 { + let sign = ((h as u32) & 0x8000) << 16; + let exp = ((h >> 10) & 0x1f) as u32; + let man = (h & 0x3ff) as u32; + let bits = match exp { + 0 if man == 0 => sign, + 0 => { + let mut e = 113u32; + let mut m = man; + while m & 0x400 == 0 { + m <<= 1; + e -= 1; + } + sign | (e << 23) | ((m & 0x3ff) << 13) + } + 31 => sign | 0x7f80_0000 | (man << 13), + _ => sign | ((exp + 112) << 23) | (man << 13), + }; + f32::from_bits(bits) +} + +struct ExrChannel { + name: String, + kind: u32, +} + +fn le_i32(b: &[u8], at: usize) -> Option<i32> { + b.get(at..at + 4).map(|s| i32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} + +fn cstr(b: &[u8], at: usize) -> Option<(String, usize)> { + let end = at + b.get(at..)?.iter().position(|&c| c == 0)?; + Some((String::from_utf8_lossy(&b[at..end]).into_owned(), end + 1)) +} + +fn exr_unpredict(raw: Vec<u8>) -> Vec<u8> { + let mut t = raw; + for i in 1..t.len() { + t[i] = (t[i - 1] as i32 + t[i] as i32 - 128) as u8; + } + let half = t.len().div_ceil(2); + let mut out = Vec::with_capacity(t.len()); + for i in 0..half { + out.push(t[i]); + if let Some(&v) = t.get(half + i) { + out.push(v); + } + } + out +} + +fn exr_rle(data: &[u8], max_out: usize) -> Result<Vec<u8>> { + let mut out = Vec::with_capacity(max_out); + let mut i = 0; + while i < data.len() { + let n = data[i] as i8 as i32; + i += 1; + if n < 0 { + let len = (-n) as usize; + let Some(s) = data.get(i..i + len) else { return exr_bad("RLE run past the end") }; + out.extend_from_slice(s); + i += len; + } else { + let Some(&v) = data.get(i) else { return exr_bad("RLE run past the end") }; + out.extend(std::iter::repeat_n(v, n as usize + 1)); + i += 1; + } + if out.len() > max_out { + return exr_bad("RLE block larger than declared"); + } + } + Ok(out) +} + +/// PXR24 chunk: zlib, then per line and channel the byte planes of differences (uint 4, half 2, float 3 high +/// bytes) summed back into values, written in the uncompressed line layout. +fn exr_pxr24(data: &[u8], width: usize, lines: usize, channels: &[ExrChannel]) -> Result<Vec<u8>> { + let planes = |k: u32| match k { + 0 => 4, + 1 => 2, + _ => 3, + }; + let packed: usize = channels.iter().map(|c| planes(c.kind) * width).sum::<usize>() * lines; + let raw = crate::deflate::zlib_decompress(data, packed)?; + if raw.len() != packed { + return exr_bad("PXR24 chunk decodes to the wrong size"); + } + let mut out = Vec::with_capacity(lines * channels.iter().map(|c| if c.kind == 1 { 2 } else { 4 } * width).sum::<usize>()); + let mut at = 0; + for _ in 0..lines { + for c in channels { + let np = planes(c.kind); + let p = &raw[at..at + np * width]; + at += np * width; + let mut pixel = 0u32; + for j in 0..width { + let mut diff = 0u32; + for k in 0..np { + diff = (diff << 8) | p[k * width + j] as u32; + } + if c.kind == 2 { + diff <<= 8; + } + pixel = pixel.wrapping_add(diff); + match c.kind { + 1 => out.extend_from_slice(&(pixel as u16).to_le_bytes()), + _ => out.extend_from_slice(&pixel.to_le_bytes()), + } + } + } + } + Ok(out) +} + +fn read_exr_rgba(b: &[u8]) -> Result<(u32, u32, u8, ImagePixels)> { + if !b.starts_with(&EXR_MAGIC) || b.len() < 8 { + return exr_bad("not an OpenEXR file"); + } + let flags = u32::from_le_bytes([b[4], b[5], b[6], b[7]]); + if flags & 0xff != 2 { + return exr_bad(format!("version {}", flags & 0xff)); + } + if flags & 0x1a00 != 0 { + return Err(IoError::Unsupported("tiled, deep or multi-part OpenEXR".into())); + } + let mut at = 8; + let mut channels: Vec<ExrChannel> = Vec::new(); + let mut compression = 0u8; + let mut window: Option<[i32; 4]> = None; + loop { + let Some((name, next)) = cstr(b, at) else { return exr_bad("header cut short") }; + at = next; + if name.is_empty() { + break; + } + let Some((kind, next)) = cstr(b, at) else { return exr_bad("header cut short") }; + let Some(size) = le_i32(b, next).filter(|s| *s >= 0) else { return exr_bad("attribute size") }; + let start = next + 4; + let Some(value) = b.get(start..start + size as usize) else { return exr_bad("attribute past the end") }; + at = start + size as usize; + match (name.as_str(), kind.as_str()) { + ("channels", "chlist") => { + let mut c = 0; + while c < value.len() && value[c] != 0 { + let Some((cn, n2)) = cstr(value, c) else { return exr_bad("channel list") }; + let (Some(k), Some(xs), Some(ys)) = (le_i32(value, n2), le_i32(value, n2 + 8), le_i32(value, n2 + 12)) else { + return exr_bad("channel list"); + }; + if xs != 1 || ys != 1 { + return Err(IoError::Unsupported("subsampled OpenEXR channels".into())); + } + if !(0..=2).contains(&k) { + return exr_bad(format!("channel type {k}")); + } + channels.push(ExrChannel { name: cn, kind: k as u32 }); + c = n2 + 16; + } + } + ("compression", _) => compression = value.first().copied().unwrap_or(0), + ("dataWindow", "box2i") if value.len() >= 16 => { + let v: Vec<i32> = (0..4).filter_map(|i| le_i32(value, i * 4)).collect(); + window = Some([v[0], v[1], v[2], v[3]]); + } + _ => {} + } + } + let Some([x0, y0, x1, y1]) = window else { return exr_bad("no data window") }; + let (w, h) = (x1 as i64 - x0 as i64 + 1, y1 as i64 - y0 as i64 + 1); + if w <= 0 || h <= 0 || w > EXR_MAX_SIDE || h > EXR_MAX_SIDE { + return exr_bad(format!("size {w}x{h}")); + } + let (w, h) = (w as usize, h as usize); + let lines = match compression { + 0..=2 => 1, + 3 => 16, + 4 => 32, + 5 => 16, + c => return Err(IoError::Unsupported(format!("OpenEXR compression {c} (none, RLE, ZIPS, ZIP, PIZ and PXR24 are read)"))), + }; + if channels.is_empty() { + return exr_bad("no channels"); + } + let find = |want: &str| { + channels.iter().position(|c| c.name == want).or_else(|| { + let suffix = format!(".{want}"); + channels.iter().position(|c| c.name.ends_with(&suffix)) + }) + }; + let (r, g, bl, a, y) = (find("R"), find("G"), find("B"), find("A"), find("Y")); + let source: [Option<usize>; 4] = match (r, g, bl, y) { + (Some(_), _, _, _) | (_, Some(_), _, _) | (_, _, Some(_), _) => [r, g, bl, a], + (None, None, None, Some(y)) => [Some(y), Some(y), Some(y), a], + _ => [Some(0), Some(0), Some(0), a], + }; + let file_channels = if y.is_some() && r.is_none() { 1 } else { 3 } + u8::from(a.is_some()); + let sizes: Vec<usize> = channels.iter().map(|c| if c.kind == 1 { 2 } else { 4 }).collect(); + let line_bytes: usize = sizes.iter().sum::<usize>() * w; + let chunks = h.div_ceil(lines); + let table = at; + let mut out = vec![0.0f32; w * h * 4]; + for px in out.as_chunks_mut::<4>().0 { + px[3] = 1.0; + } + for k in 0..chunks { + let Some(off) = b.get(table + k * 8..table + k * 8 + 8) else { return exr_bad("offset table cut short") }; + let off = u64::from_le_bytes([off[0], off[1], off[2], off[3], off[4], off[5], off[6], off[7]]) as usize; + let (Some(cy), Some(size)) = (le_i32(b, off), le_i32(b, off + 4)) else { return exr_bad("chunk past the end") }; + let Some(data) = b.get(off + 8..off + 8 + size.max(0) as usize) else { return exr_bad("chunk past the end") }; + let first = cy as i64 - y0 as i64; + if first < 0 || first as usize >= h { + return exr_bad(format!("chunk at line {cy}")); + } + let first = first as usize; + let n = lines.min(h - first); + let want = line_bytes * n; + let block = if data.len() == want { + data.to_vec() + } else { + match compression { + 1 => exr_unpredict(exr_rle(data, want)?), + 2 | 3 => exr_unpredict(crate::deflate::zlib_decompress(data, want)?), + 4 => piz::decode(data, w, n, &sizes.iter().map(|s| s / 2).collect::<Vec<_>>())?, + 5 => exr_pxr24(data, w, n, &channels)?, + _ => return exr_bad("uncompressed chunk of the wrong size"), + } + }; + if block.len() != want { + return exr_bad("chunk decodes to the wrong size"); + } + let mut p = 0; + for line in 0..n { + let row = first + line; + for (ci, c) in channels.iter().enumerate() { + let targets: Vec<usize> = (0..4).filter(|&t| source[t] == Some(ci)).collect(); + for x in 0..w { + let v = match c.kind { + 0 => u32::from_le_bytes([block[p], block[p + 1], block[p + 2], block[p + 3]]) as f32, + 1 => half_to_f32(u16::from_le_bytes([block[p], block[p + 1]])), + _ => f32::from_le_bytes([block[p], block[p + 1], block[p + 2], block[p + 3]]), + }; + p += sizes[ci]; + for &t in &targets { + out[(row * w + x) * 4 + t] = v; + } + } + } + } + } + Ok((w as u32, h as u32, file_channels, ImagePixels::RgbaF32(out))) +} + +mod piz { + use super::exr_bad; + use crate::error::Result; + + const ENCSIZE: usize = (1 << 16) + 1; + const DECBITS: i32 = 14; + const DECSIZE: usize = 1 << DECBITS; + const DECMASK: u64 = DECSIZE as u64 - 1; + const SHORT_ZEROCODE_RUN: u64 = 59; + const LONG_ZEROCODE_RUN: u64 = 63; + const SHORTEST_LONG_RUN: u64 = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; + + struct Reader<'a> { + b: &'a [u8], + at: usize, + c: u64, + lc: i32, + } + + impl Reader<'_> { + fn byte(&mut self) -> Result<()> { + let Some(&v) = self.b.get(self.at) else { return exr_bad("PIZ data cut short") }; + self.at += 1; + self.c = (self.c << 8) | v as u64; + self.lc += 8; + Ok(()) + } + + fn bits(&mut self, n: i32) -> Result<u64> { + while self.lc < n { + self.byte()?; + } + self.lc -= n; + Ok((self.c >> self.lc) & ((1u64 << n) - 1)) + } + } + + fn le32(b: &[u8], at: usize) -> Result<u32> { + match b.get(at..at + 4) { + Some(s) => Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]])), + None => exr_bad("PIZ header cut short"), + } + } + + fn canonical(code: &mut [u64]) { + let mut n = [0u64; 59]; + for &l in code.iter() { + n[l as usize] += 1; + } + let mut c = 0u64; + for i in (1..=58).rev() { + let nc = (c + n[i]) >> 1; + n[i] = c; + c = nc; + } + for l in code.iter_mut() { + let len = *l as usize; + if len > 0 { + *l = len as u64 | (n[len] << 6); + n[len] += 1; + } + } + } + + #[derive(Clone, Default)] + struct Dec { + len: i32, + lit: u32, + long: Vec<u32>, + } + + fn emit(sym: u32, rlc: u32, r: &mut Reader, out: &mut Vec<u16>, no: usize) -> Result<()> { + if sym == rlc { + if r.lc < 8 { + r.byte()?; + } + r.lc -= 8; + let run = ((r.c >> r.lc) & 0xff) as usize; + let Some(&last) = out.last() else { return exr_bad("PIZ run before any value") }; + if out.len() + run > no { + return exr_bad("PIZ run past the end"); + } + out.extend(std::iter::repeat_n(last, run)); + } else { + if out.len() >= no { + return exr_bad("PIZ data longer than declared"); + } + out.push(sym as u16); + } + Ok(()) + } + + /// Huffman stage (OpenEXR `hufUncompress`): `no` 16-bit values. + fn huffman(b: &[u8], no: usize) -> Result<Vec<u16>> { + if b.is_empty() { + return if no == 0 { Ok(Vec::new()) } else { exr_bad("empty PIZ data") }; + } + let (im, imax, nbits) = (le32(b, 0)? as usize, le32(b, 4)? as usize, le32(b, 12)? as usize); + if im >= ENCSIZE || imax >= ENCSIZE || im > imax { + return exr_bad("PIZ code range"); + } + let mut code = vec![0u64; ENCSIZE]; + let mut r = Reader { b, at: 20, c: 0, lc: 0 }; + let mut i = im; + while i <= imax { + let l = r.bits(6)?; + code[i] = l; + if l == LONG_ZEROCODE_RUN || l >= SHORT_ZEROCODE_RUN { + let run = if l == LONG_ZEROCODE_RUN { (r.bits(8)? + SHORTEST_LONG_RUN) as usize } else { (l - SHORT_ZEROCODE_RUN + 2) as usize }; + if i + run > imax + 1 { + return exr_bad("PIZ code table run"); + } + code[i..i + run].fill(0); + i += run; + } else { + i += 1; + } + } + canonical(&mut code); + let mut dec = vec![Dec::default(); DECSIZE]; + for (sym, &e) in code.iter().enumerate().take(imax + 1).skip(im) { + let (c, l) = (e >> 6, (e & 63) as i32); + if l > 0 && c >> l != 0 { + return exr_bad("PIZ code table entry"); + } + if l > DECBITS { + let d = &mut dec[(c >> (l - DECBITS)) as usize]; + if d.len != 0 { + return exr_bad("PIZ code table clash"); + } + d.lit += 1; + d.long.push(sym as u32); + } else if l > 0 { + let first = (c << (DECBITS - l)) as usize; + for d in &mut dec[first..first + (1usize << (DECBITS - l))] { + if d.len != 0 || !d.long.is_empty() { + return exr_bad("PIZ code table clash"); + } + d.len = l; + d.lit = sym as u32; + } + } + } + let start = r.at; + let end = start + nbits.div_ceil(8); + if end > b.len() { + return exr_bad("PIZ bit count past the end"); + } + let rlc = imax as u32; + let mut r = Reader { b: &b[..end], at: start, c: 0, lc: 0 }; + let mut out = Vec::with_capacity(no); + while r.at < end { + r.byte()?; + while r.lc >= DECBITS { + let d = &dec[((r.c >> (r.lc - DECBITS)) & DECMASK) as usize]; + if d.len != 0 { + r.lc -= d.len; + emit(d.lit, rlc, &mut r, &mut out, no)?; + } else { + if d.long.is_empty() { + return exr_bad("PIZ unknown code"); + } + let mut found = false; + for &sym in &d.long { + let l = (code[sym as usize] & 63) as i32; + while r.lc < l && r.at < end { + r.byte()?; + } + if r.lc >= l && code[sym as usize] >> 6 == ((r.c >> (r.lc - l)) & ((1u64 << l) - 1)) { + r.lc -= l; + emit(sym, rlc, &mut r, &mut out, no)?; + found = true; + break; + } + } + if !found { + return exr_bad("PIZ unknown long code"); + } + } + } + } + let skip = ((8 - nbits as i64).rem_euclid(8)) as i32; + r.c >>= skip; + r.lc -= skip; + while r.lc > 0 { + let d = &dec[((r.c << (DECBITS - r.lc)) & DECMASK) as usize]; + if d.len == 0 || d.len > r.lc { + return exr_bad("PIZ trailing code"); + } + r.lc -= d.len; + emit(d.lit, rlc, &mut r, &mut out, no)?; + } + if out.len() != no { + return exr_bad("PIZ data shorter than declared"); + } + Ok(out) + } + + fn wdec14(l: u16, h: u16) -> (u16, u16) { + let (ls, hi) = (l as i16 as i32, h as i16 as i32); + let ai = ls + (hi & 1) + (hi >> 1); + (ai as i16 as u16, (ai - hi) as i16 as u16) + } + + fn wdec16(l: u16, h: u16) -> (u16, u16) { + let (m, d) = (l as i32, h as i32); + let b = (m - (d >> 1)) & 0xffff; + let a = (d + b - 0x8000) & 0xffff; + (a as u16, b as u16) + } + + /// Inverse Haar wavelet of one component (OpenEXR `wav2Decode`), in place. + fn wavelet(v: &mut [u16], base: usize, nx: usize, ox: usize, ny: usize, oy: usize, max: u16) { + let dec = if max < (1 << 14) { wdec14 } else { wdec16 }; + let n = nx.min(ny); + let mut p = 1usize; + while p <= n { + p <<= 1; + } + p >>= 1; + let mut p2 = p; + p >>= 1; + while p >= 1 { + let (oy1, oy2, ox1, ox2) = (oy * p, oy * p2, ox * p, ox * p2); + let ey = base + oy * (ny - p2); + let mut py = base; + while py <= ey { + let ex = py + ox * (nx - p2); + let mut px = py; + while px <= ex { + let (p01, p10) = (px + ox1, px + oy1); + let p11 = p10 + ox1; + let (i00, i10) = dec(v[px], v[p10]); + let (i01, i11) = dec(v[p01], v[p11]); + (v[px], v[p01]) = dec(i00, i01); + (v[p10], v[p11]) = dec(i10, i11); + px += ox2; + } + if nx & p != 0 { + let p10 = px + oy1; + let (i00, b) = dec(v[px], v[p10]); + v[p10] = b; + v[px] = i00; + } + py += oy2; + } + if ny & p != 0 { + let ex = py + ox * (nx - p2); + let mut px = py; + while px <= ex { + let p01 = px + ox1; + let (i00, b) = dec(v[px], v[p01]); + v[p01] = b; + v[px] = i00; + px += ox2; + } + } + p2 = p; + p >>= 1; + } + } + + /// Decodes one PIZ chunk of `lines` scanlines `width` wide whose channels hold `halves[c]` 16-bit words per + /// sample (1 half, 2 float or uint), into the uncompressed line layout. + pub(super) fn decode(data: &[u8], width: usize, lines: usize, halves: &[usize]) -> Result<Vec<u8>> { + if data.len() < 4 { + return exr_bad("PIZ chunk cut short"); + } + let (min_nz, max_nz) = (u16::from_le_bytes([data[0], data[1]]) as usize, u16::from_le_bytes([data[2], data[3]]) as usize); + if max_nz >= 8192 { + return exr_bad("PIZ bitmap range"); + } + let mut bitmap = [0u8; 8192]; + let mut at = 4; + if min_nz <= max_nz { + let len = max_nz - min_nz + 1; + let Some(s) = data.get(at..at + len) else { return exr_bad("PIZ bitmap cut short") }; + bitmap[min_nz..=max_nz].copy_from_slice(s); + at += len; + } + let mut lut = vec![0u16; 1 << 16]; + let mut k = 0usize; + for i in 0..(1usize << 16) { + if i == 0 || bitmap[i >> 3] & (1 << (i & 7)) != 0 { + lut[k] = i as u16; + k += 1; + } + } + let max_value = (k - 1) as u16; + let length = le32(data, at)? as usize; + at += 4; + let Some(huf) = data.get(at..at + length) else { return exr_bad("PIZ Huffman data cut short") }; + let total: usize = halves.iter().map(|h| width * lines * h).sum(); + let mut v = huffman(huf, total)?; + let mut starts = Vec::with_capacity(halves.len()); + let mut s = 0; + for &h in halves { + starts.push(s); + for j in 0..h { + wavelet(&mut v, s + j, width, h, lines, width * h, max_value); + } + s += width * lines * h; + } + for x in v.iter_mut() { + *x = lut[*x as usize]; + } + let mut out = Vec::with_capacity(total * 2); + for y in 0..lines { + for (c, &h) in halves.iter().enumerate() { + let row = &v[starts[c] + y * width * h..starts[c] + (y + 1) * width * h]; + for w in row { + out.extend_from_slice(&w.to_le_bytes()); + } + } + } + Ok(out) + } +} diff --git a/native/crates/fsh-io/src/ply.rs b/native/crates/fsh-io/src/ply.rs index 9cb7b72f..91b1b67a 100644 --- a/native/crates/fsh-io/src/ply.rs +++ b/native/crates/fsh-io/src/ply.rs @@ -1,5 +1,6 @@ use crate::error::{malformed, IoError, Result}; use crate::raw::{RawMesh, RawNode, RawScene}; +use crate::triangulate::triangulate; use crate::watch::{Stage, Watch}; use fsh_core::{srgb_decode, Vec2, Vec3, Vec4}; @@ -274,13 +275,21 @@ pub fn read_ply(bytes: &[u8], name: &str, watch: &Watch) -> Result<RawScene> { m.colours.push(Vec4::new(c(cr), c(cg), c(cb), a.unwrap_or(1.0))); } if want_uv { - uv.push(Vec2::new(g(tu), 1.0 - g(tv))); + uv.push(Vec2::new(g(tu), g(tv))); } } if is_face && list.len() >= 3 { let idx = |v: f64| if v >= 0.0 && v <= u32::MAX as f64 { v as u32 } else { u32::MAX }; - for i in 1..list.len() - 1 { - m.indices.extend_from_slice(&[idx(list[0]), idx(list[i]), idx(list[i + 1])]); + let ids: Vec<u32> = list.iter().map(|&v| idx(v)).collect(); + if ids.len() > 3 && ids.iter().all(|&i| (i as usize) < m.positions.len()) { + let pts: Vec<Vec3> = ids.iter().map(|&i| m.positions[i as usize]).collect(); + for t in triangulate(&pts) { + m.indices.extend_from_slice(&[ids[t[0]], ids[t[1]], ids[t[2]]]); + } + } else { + for i in 1..ids.len() - 1 { + m.indices.extend_from_slice(&[ids[0], ids[i], ids[i + 1]]); + } } } } diff --git a/native/crates/fsh-io/src/raw.rs b/native/crates/fsh-io/src/raw.rs index 7b198c9f..c9b68899 100644 --- a/native/crates/fsh-io/src/raw.rs +++ b/native/crates/fsh-io/src/raw.rs @@ -1,5 +1,5 @@ use fsh_core::{LengthUnit, Mat4, Vec2, Vec3, Vec4}; -use fsh_scene::TextureRole; +use fsh_scene::{MaterialInput, TextureRole, TextureSlot}; /// Which file axis points up. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] @@ -75,7 +75,8 @@ pub struct RawMesh { pub positions: Vec<Vec3>, /// Authored normals; empty when the file had none. pub normals: Vec<Vec3>, - /// UV sets, each one entry per vertex (glTF convention: v grows downwards). + /// UV sets, each one entry per vertex, v growing upwards (origin at the image's bottom left, row 0 of an image at + /// v = 1); glTF's downward v is flipped on read and on write. pub uvs: Vec<Vec<Vec2>>, /// Linear RGBA vertex colours; empty when absent. pub colours: Vec<Vec4>, @@ -83,8 +84,9 @@ pub struct RawMesh { pub indices: Vec<u32>, /// Index into `RawScene::materials`. pub material: Option<usize>, - /// Set by the clean-up pass: this mesh equals another mesh moved by an offset; its own data is cleared. - pub instance_of: Option<(usize, Vec3)>, + /// Set by the clean-up pass: this mesh equals another mesh under a rigid transform (rotation, possibly a + /// mirror, and translation) that maps the source's local coordinates to this mesh's; its own data is cleared. + pub instance_of: Option<(usize, Mat4)>, } impl RawMesh { @@ -181,6 +183,55 @@ impl Default for RawMaterial { } } +/// Prefix of a `RawTexture::uri` that names an image held in `RawScene::images` (`#embedded:<index>`). +pub const EMBEDDED_PREFIX: &str = "#embedded:"; + +/// Image bytes stored inside the model file (GLB buffer views, data URIs, 3MF package parts, FBX content). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawImage { + /// Name for reports (the image's name or path in the file). + pub name: String, + /// Encoded image file bytes. + pub bytes: Vec<u8>, +} + +/// A texture driving one material input; `slot.texture` is filled in when the scene is converted. +#[derive(Clone, Debug, PartialEq)] +pub struct RawSlot { + /// Material input driven. + pub input: MaterialInput, + /// Index into `RawScene::textures`. + pub texture: usize, + /// Mapping, channel, factor and filtering settings. + pub slot: TextureSlot, +} + +/// Material values beyond [`RawMaterial`], kept beside the materials (indexed like them) so older callers that +/// build `RawMaterial` literally keep compiling. Colours are linear sRGB. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawMaterialExtra { + /// Texture slots by input; the first slot of an input wins. + pub slots: Vec<RawSlot>, + /// Specular tint (KHR_materials_specular). + pub specular_colour: Option<[f32; 3]>, + /// Clear coat index of refraction (1.5 for glTF clearcoat). + pub coat_ior: Option<f32>, + /// Sheen colour and roughness. + pub sheen: Option<([f32; 3], f32)>, + /// Volume attenuation colour and distance in metres (KHR_materials_volume). + pub attenuation: Option<([f32; 3], f32)>, + /// Thin walled surface (transmission without a volume). + pub thin_walled: Option<bool>, + /// Thin film weight, index of refraction and thickness in micrometres (KHR_materials_iridescence). + pub thin_film: Option<[f32; 3]>, + /// Abbe number (KHR_materials_dispersion). + pub abbe: Option<f32>, + /// Roughness anisotropy 0..1. + pub anisotropy: Option<f32>, + /// Alpha cutoff of a masked material (glTF alphaMode MASK); coverage is soft until a cutoff opcode exists. + pub alpha_cutoff: Option<f32>, +} + /// Everything a reader found, independent of any document. #[derive(Clone, Debug, Default, PartialEq)] pub struct RawScene { @@ -194,6 +245,13 @@ pub struct RawScene { pub materials: Vec<RawMaterial>, /// Texture references. pub textures: Vec<RawTexture>, + /// Tangents per mesh, indexed like `meshes` (xyz plus handedness sign in w, one per vertex); a missing or + /// empty entry means none. Kept beside the meshes so `RawMesh` stays constructible by older callers. + pub tangents: Vec<Vec<Vec4>>, + /// Material values beyond `RawMaterial`, indexed like `materials`; a missing entry means none. + pub extras: Vec<RawMaterialExtra>, + /// Images stored inside the file, named by `RawTexture::uri` `#embedded:<index>`. + pub images: Vec<RawImage>, /// Unit the file declares, if it declares one. pub unit: Option<LengthUnit>, /// Up axis the file declares, if it declares one. @@ -208,6 +266,25 @@ impl RawScene { Self { name: name.into(), ..Default::default() } } + /// The extra values of a material, created on first use. + pub fn extra_mut(&mut self, material: usize) -> &mut RawMaterialExtra { + if self.extras.len() <= material { + self.extras.resize(material + 1, RawMaterialExtra::default()); + } + &mut self.extras[material] + } + + /// Adds an embedded image and returns the texture uri that names it. + pub fn add_image(&mut self, name: impl Into<String>, bytes: Vec<u8>) -> String { + self.images.push(RawImage { name: name.into(), bytes }); + format!("{EMBEDDED_PREFIX}{}", self.images.len() - 1) + } + + /// Bytes of an embedded image by texture uri. + pub fn image_of(&self, uri: &str) -> Option<&RawImage> { + uri.strip_prefix(EMBEDDED_PREFIX).and_then(|i| i.parse::<usize>().ok()).and_then(|i| self.images.get(i)) + } + /// Total triangles over meshes that carry their own data. pub fn triangle_count(&self) -> usize { self.meshes.iter().map(|m| m.triangle_count()).sum() diff --git a/native/crates/fsh-io/src/stl.rs b/native/crates/fsh-io/src/stl.rs index 91a7e71f..b094b407 100644 --- a/native/crates/fsh-io/src/stl.rs +++ b/native/crates/fsh-io/src/stl.rs @@ -1,7 +1,7 @@ use crate::error::{malformed, IoError, Result}; use crate::raw::{RawMesh, RawNode, RawScene}; use crate::watch::{Stage, Watch}; -use fsh_core::Vec3; +use fsh_core::{srgb_decode, Vec3, Vec4}; /// True when the size matches a binary STL's declared triangle count. pub fn is_binary_stl(bytes: &[u8]) -> bool { @@ -61,6 +61,11 @@ fn read_binary(bytes: &[u8], scene: &mut RawScene, watch: &Watch) -> Result<()> let mut m = RawMesh { name: scene.name.clone(), ..Default::default() }; m.positions.reserve(n * 3); m.indices.reserve(n * 3); + let header = &bytes[..80]; + let materialise = header.windows(6).position(|w| w == b"COLOR="); + let default = materialise.and_then(|i| header.get(i + 6..i + 10)).map(|c| [c[0], c[1], c[2], c[3]]); + let mut colours: Vec<Vec4> = Vec::new(); + let mut any = false; for t in 0..n { if t % 65536 == 0 { watch.step(Stage::Reading, t as f32 / n.max(1) as f32)?; @@ -68,6 +73,20 @@ fn read_binary(bytes: &[u8], scene: &mut RawScene, watch: &Watch) -> Result<()> let b = 84 + t * 50; let v = |k: usize| Vec3::new(f32_at(bytes, b + k), f32_at(bytes, b + k + 4), f32_at(bytes, b + k + 8)); push_tri(&mut m, v(0), [v(12), v(24), v(36)]); + let attr = u16::from_le_bytes([bytes[b + 48], bytes[b + 49]]); + let five = |s: u16| srgb_decode(((attr >> s) & 31) as f32 / 31.0); + let c = match materialise { + Some(_) if attr & 0x8000 == 0 => Some(Vec4::new(five(0), five(5), five(10), 1.0)), + Some(_) => default.map(|c| Vec4::new(srgb_decode(c[0] as f32 / 255.0), srgb_decode(c[1] as f32 / 255.0), srgb_decode(c[2] as f32 / 255.0), c[3] as f32 / 255.0)), + None if attr & 0x8000 != 0 => Some(Vec4::new(five(10), five(5), five(0), 1.0)), + None => None, + }; + any |= c.is_some(); + let c = c.unwrap_or(Vec4::ONE); + colours.extend_from_slice(&[c, c, c]); + } + if any { + m.colours = colours; } scene.meshes.push(m); Ok(()) diff --git a/native/crates/fsh-io/src/tangents.rs b/native/crates/fsh-io/src/tangents.rs new file mode 100644 index 00000000..73c570ed --- /dev/null +++ b/native/crates/fsh-io/src/tangents.rs @@ -0,0 +1,82 @@ +use crate::raw::RawMesh; +use bevy_mikktspace::{generate_tangents, Geometry, TangentSpace}; +use fsh_core::{Vec3, Vec4}; +use std::collections::HashMap; + +struct Corners<'a> { + m: &'a RawMesh, + out: Vec<Option<[f32; 4]>>, +} + +impl Corners<'_> { + fn v(&self, face: usize, vert: usize) -> usize { + self.m.indices[face * 3 + vert] as usize + } +} + +impl Geometry for Corners<'_> { + fn num_faces(&self) -> usize { + self.m.indices.len() / 3 + } + + fn num_vertices_of_face(&self, _face: usize) -> usize { + 3 + } + + fn position(&self, face: usize, vert: usize) -> [f32; 3] { + let p = self.m.positions[self.v(face, vert)]; + [p.x, p.y, p.z] + } + + fn normal(&self, face: usize, vert: usize) -> [f32; 3] { + let n = self.m.normals[self.v(face, vert)]; + [n.x, n.y, n.z] + } + + fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] { + let t = self.m.uvs[0][self.v(face, vert)]; + [t.x, t.y] + } + + fn set_tangent(&mut self, t: Option<TangentSpace>, face: usize, vert: usize) { + self.out[face * 3 + vert] = t.map(|t| t.tangent_encoded()).filter(|t| t.iter().all(|v| v.is_finite())); + } +} + +fn any_perpendicular(n: Vec3) -> Vec4 { + let h = if n.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }; + let t = (h - n * n.dot(h)).normalize_or(Vec3::X); + Vec4::new(t.x, t.y, t.z, 1.0) +} + +/// MikkTSpace tangents from the first UV set, taken with v pointing up as glTF's own tangents are; vertices whose corners disagree are split, so the mesh's vertex +/// order changes. Needs normals and at least one UV set. Returns the tangents, one per (new) vertex. +pub(crate) fn mikktspace(m: &mut RawMesh) -> Vec<Vec4> { + if m.uvs.is_empty() || m.normals.len() != m.positions.len() || m.indices.is_empty() { + return Vec::new(); + } + let mut g = Corners { m: &*m, out: vec![None; m.indices.len()] }; + let ok = generate_tangents(&mut g).is_ok(); + let corners = g.out; + let mut order: Vec<u32> = Vec::new(); + let mut tangents: Vec<Vec4> = Vec::new(); + let mut map: HashMap<(u32, [u32; 4]), u32> = HashMap::new(); + let mut idx = Vec::with_capacity(m.indices.len()); + for (k, &v) in m.indices.iter().enumerate() { + let t = match corners[k] { + Some(t) if ok => Vec4::new(t[0], t[1], t[2], if t[3] < 0.0 { -1.0 } else { 1.0 }), + _ => any_perpendicular(m.normals[v as usize]), + }; + let key = (v, [t.x.to_bits(), t.y.to_bits(), t.z.to_bits(), t.w.to_bits()]); + let next = order.len() as u32; + let id = *map.entry(key).or_insert_with(|| { + order.push(v); + tangents.push(t); + next + }); + idx.push(id); + } + m.indices = idx; + crate::clean::remap(m, &order); + tangents +} diff --git a/native/crates/fsh-io/src/threemf.rs b/native/crates/fsh-io/src/threemf.rs new file mode 100644 index 00000000..d2ac10e3 --- /dev/null +++ b/native/crates/fsh-io/src/threemf.rs @@ -0,0 +1,721 @@ +use crate::error::{malformed, IoError, Result}; +use crate::raw::{RawMaterial, RawMesh, RawNode, RawScene, RawSlot, RawTexture, UpAxis}; +use crate::watch::{Stage, Watch}; +use crate::zip::{is_zip, Zip}; +use fsh_core::{srgb_decode, srgb_encode, LengthUnit, Mat4, Vec2, Vec3, Vec4}; +use fsh_scene::fsh_materials::{Filter, Wrap}; +use fsh_scene::{MaterialInput, TextureRole, TextureSlot}; +use roxmltree::{Document, Node, ParsingOptions}; +use std::collections::HashMap; + +const MAX_MODEL_XML: u64 = 1 << 31; +const MAX_NODES: usize = 1 << 20; +const MAX_DEPTH: usize = 64; +const MAX_IMAGE: u64 = 256 << 20; + +/// True for a ZIP package that holds a 3MF model part. +pub fn is_3mf(bytes: &[u8]) -> bool { + is_zip(bytes) + && Zip::open(bytes) + .map(|z| z.entries.iter().any(|e| e.name.to_ascii_lowercase().ends_with(".model"))) + .unwrap_or(false) +} + +struct Tri { + v: [u32; 3], + pid: Option<u32>, + p: [Option<u32>; 3], +} + +#[derive(Clone, Copy)] +struct Display { + metallic: f32, + roughness: f32, + transmission: f32, + ior: f32, +} + +struct Base { + name: String, + colour: [f32; 4], + display: Option<Display>, +} + +enum Group { + Base(Vec<Base>), + Colour(Vec<[f32; 4]>), + Tex { tex: u32, uvs: Vec<Vec2> }, + Composite { base: u32, mats: Vec<u32>, rows: Vec<Vec<f32>> }, + Multi { pids: Vec<u32>, rows: Vec<Vec<u32>> }, +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Bucket { + Plain, + Base(u32, u32), + Colour, + Tex(u32), +} + +enum Corner { + None, + Base(u32, u32), + Colour([f32; 4]), + Tex(u32, Vec2), +} + +#[derive(Default)] +struct MeshData { + verts: Vec<Vec3>, + tris: Vec<Tri>, +} + +struct Component { + path: Option<String>, + id: u32, + transform: Mat4, +} + +struct Object { + name: String, + skipped: bool, + pid: Option<u32>, + pindex: u32, + mesh: Option<MeshData>, + components: Vec<Component>, +} + +struct Item { + path: Option<String>, + id: u32, + transform: Mat4, +} + +#[derive(Default)] +struct Model { + unit: Option<(LengthUnit, f32)>, + objects: HashMap<u32, Object>, + build: Vec<Item>, + groups: HashMap<u32, Group>, + displays: HashMap<u32, Vec<Display>>, + textures: HashMap<u32, Tex2d>, +} + +struct Tex2d { + path: String, + wrap: Wrap, + filter: Filter, +} + +fn tile(s: Option<&str>) -> Wrap { + match s.map(str::trim) { + Some("mirror") => Wrap::Mirror, + Some("clamp") | Some("none") => Wrap::Clamp, + _ => Wrap::Repeat, + } +} + +fn colour(s: &str) -> Option<[f32; 4]> { + let h = s.trim().strip_prefix('#')?; + if !(h.len() == 6 || h.len() == 8) || !h.is_ascii() { + return None; + } + let byte = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).ok().map(|v| v as f32 / 255.0); + let a = if h.len() == 8 { byte(6)? } else { 1.0 }; + Some([srgb_decode(byte(0)?), srgb_decode(byte(2)?), srgb_decode(byte(4)?), a]) +} + +fn floats(s: &str) -> Option<Vec<f32>> { + s.split_whitespace().map(|t| t.parse::<f32>().ok().filter(|v| v.is_finite())).collect() +} + +fn ints(s: &str) -> Option<Vec<u32>> { + s.split_whitespace().map(|t| t.parse::<u32>().ok()).collect() +} + +fn read_group(r: Node, part: &str, model: &mut Model, scene: &mut RawScene) -> Result<()> { + let kind = local(&r); + let Some(id) = index(&r, "id")? else { return Ok(()) }; + let bad = |what: &str| IoError::Malformed(format!("{part}: {kind} {id}: {what}")); + let group = match kind { + "basematerials" => { + let disp = index(&r, "displaypropertiesid")?; + let mut v = Vec::new(); + for (i, b) in children(r, "base").enumerate() { + let c = attr(&b, "displaycolor").and_then(colour).ok_or_else(|| bad("a base material has no valid displaycolor"))?; + let name = attr(&b, "name").map(str::to_string).filter(|s| !s.trim().is_empty()).unwrap_or_else(|| format!("Material {id}.{i}")); + let display = match index(&b, "displaypropertiesid")? { + Some(d) => model.displays.get(&d).and_then(|d| d.get(i).or(d.first())).copied(), + None => disp.and_then(|d| model.displays.get(&d)).and_then(|d| d.get(i)).copied(), + }; + v.push(Base { name, colour: c, display }); + } + Group::Base(v) + } + "colorgroup" => { + let v = children(r, "color").map(|c| attr(&c, "color").and_then(colour).ok_or_else(|| bad("a colour is not #RRGGBB or #RRGGBBAA"))).collect::<Result<_>>()?; + Group::Colour(v) + } + "texture2d" => { + let p = attr(&r, "path").ok_or_else(|| bad("no path"))?; + let (u, v) = (tile(attr(&r, "tilestyleu")), tile(attr(&r, "tilestylev"))); + if u != v { + scene.warnings.push(format!("{part}: texture {id} tiles differently along u and v; its u tiling is used for both")); + } + let filter = match attr(&r, "filter").map(str::trim) { + Some("nearest") => Filter::Nearest, + Some("linear") => Filter::Bilinear, + _ => Filter::Trilinear, + }; + model.textures.insert(id, Tex2d { path: p.trim().to_string(), wrap: u, filter }); + return Ok(()); + } + "texture2dgroup" => { + let tex = index(&r, "texid")?.ok_or_else(|| bad("no texid"))?; + let uvs = children(r, "tex2coord").map(|c| Ok(Vec2::new(num(&c, "u")?, num(&c, "v")?))).collect::<Result<_>>()?; + Group::Tex { tex, uvs } + } + "compositematerials" => { + let base = index(&r, "matid")?.ok_or_else(|| bad("no matid"))?; + let mats = attr(&r, "matindices").and_then(ints).ok_or_else(|| bad("bad matindices"))?; + let rows = children(r, "composite").map(|c| attr(&c, "values").and_then(floats).ok_or_else(|| bad("bad values"))).collect::<Result<_>>()?; + Group::Composite { base, mats, rows } + } + "multiproperties" => { + let pids = attr(&r, "pids").and_then(ints).ok_or_else(|| bad("bad pids"))?; + let rows = children(r, "multi").map(|c| attr(&c, "pindices").and_then(ints).ok_or_else(|| bad("bad pindices"))).collect::<Result<_>>()?; + scene.warnings.push(format!("{part}: multiproperties {id} are approximated by their first layer")); + Group::Multi { pids, rows } + } + "pbmetallicdisplayproperties" | "pbspeculardisplayproperties" | "translucentdisplayproperties" => { + let mut v = Vec::new(); + for c in r.children().filter(|c| c.is_element()) { + let f = |k: &str, d: f32| attr(&c, k).and_then(|s| s.trim().parse::<f32>().ok()).filter(|x| x.is_finite()).unwrap_or(d); + v.push(match local(&c) { + "pbmetallic" => Display { metallic: f("metallicness", 0.0), roughness: f("roughness", 1.0), transmission: 0.0, ior: 1.5 }, + "pbspecular" => Display { metallic: 0.0, roughness: 1.0 - f("glossiness", 0.0), transmission: 0.0, ior: 1.5 }, + "translucent" => { + let ior = attr(&c, "refractiveindex").and_then(floats).and_then(|v| v.first().copied()).unwrap_or(1.5); + Display { metallic: 0.0, roughness: f("roughness", 0.0), transmission: 1.0, ior } + } + _ => continue, + }); + } + model.displays.insert(id, v); + return Ok(()); + } + _ => return Ok(()), + }; + model.groups.insert(id, group); + Ok(()) +} + +fn local<'a>(n: &Node<'a, '_>) -> &'a str { + n.tag_name().name() +} + +fn attr<'a>(n: &Node<'a, '_>, name: &str) -> Option<&'a str> { + n.attributes().find(|a| a.name() == name).map(|a| a.value()) +} + +fn children<'a, 'i>(n: Node<'a, 'i>, name: &'static str) -> impl Iterator<Item = Node<'a, 'i>> { + n.children().filter(move |c| c.is_element() && local(c) == name) +} + +fn num(n: &Node, name: &str) -> Result<f32> { + let s = attr(n, name).ok_or_else(|| IoError::Malformed(format!("<{}> has no {name}", local(n))))?; + let v: f32 = s.trim().parse().map_err(|_| IoError::Malformed(format!("<{}> {name}={s:?} is not a number", local(n))))?; + if !v.is_finite() { + return Err(IoError::InvalidData(format!("<{}> {name} is not finite", local(n)))); + } + Ok(v) +} + +fn index(n: &Node, name: &str) -> Result<Option<u32>> { + match attr(n, name) { + None => Ok(None), + Some(s) => s + .trim() + .parse::<u32>() + .map(Some) + .map_err(|_| IoError::Malformed(format!("<{}> {name}={s:?} is not an index", local(n)))), + } +} + +fn transform(n: &Node) -> Result<Mat4> { + let Some(s) = attr(n, "transform") else { return Ok(Mat4::IDENTITY) }; + let v: Vec<f32> = s + .split_whitespace() + .map(|t| t.parse::<f32>().map_err(|_| IoError::Malformed(format!("transform value {t:?} is not a number")))) + .collect::<Result<_>>()?; + if v.len() != 12 || v.iter().any(|x| !x.is_finite()) { + return malformed(format!("a transform needs 12 finite numbers, found {s:?}")); + } + Ok(Mat4::from_rows([ + [v[0], v[3], v[6], v[9]], + [v[1], v[4], v[7], v[10]], + [v[2], v[5], v[8], v[11]], + [0.0, 0.0, 0.0, 1.0], + ])) +} + +fn unit_of(s: &str) -> Option<(LengthUnit, f32)> { + Some(match s { + "micron" => (LengthUnit::Millimetre, 0.001), + "millimeter" => (LengthUnit::Millimetre, 1.0), + "centimeter" => (LengthUnit::Centimetre, 1.0), + "meter" => (LengthUnit::Metre, 1.0), + "inch" => (LengthUnit::Inch, 1.0), + "foot" => (LengthUnit::Foot, 1.0), + _ => return None, + }) +} + +fn path_attr(n: &Node) -> Option<String> { + attr(n, "path").map(|p| p.trim().to_string()).filter(|p| !p.is_empty()) +} + +fn read_mesh(m: Node, name: &str, watch: &Watch) -> Result<MeshData> { + let mut out = MeshData::default(); + for vs in children(m, "vertices") { + for (i, v) in children(vs, "vertex").enumerate() { + if i % 65536 == 0 { + watch.step(Stage::Reading, 0.5)?; + } + out.verts.push(Vec3::new(num(&v, "x")?, num(&v, "y")?, num(&v, "z")?)); + } + } + let nv = out.verts.len() as u32; + for ts in children(m, "triangles") { + for (i, t) in children(ts, "triangle").enumerate() { + if i % 65536 == 0 { + watch.step(Stage::Reading, 0.6)?; + } + let mut v = [0u32; 3]; + for (k, key) in ["v1", "v2", "v3"].iter().enumerate() { + v[k] = index(&t, key)?.ok_or_else(|| IoError::Malformed(format!("{name}: a triangle has no {key}")))?; + if v[k] >= nv { + return Err(IoError::InvalidData(format!("{name}: vertex {} is out of range ({nv} defined)", v[k]))); + } + } + let p1 = index(&t, "p1")?; + let p = [p1, index(&t, "p2")?.or(p1), index(&t, "p3")?.or(p1)]; + out.tris.push(Tri { v, pid: index(&t, "pid")?, p }); + } + } + Ok(out) +} + +fn xml_opts<'a>() -> ParsingOptions<'a> { + ParsingOptions { allow_dtd: false, ..ParsingOptions::default() } +} + +fn declare_prefixes(text: &str, part: &str, scene: &mut RawScene) -> Result<String> { + let mut cur = text.to_string(); + for _ in 0..8 { + let prefix = match Document::parse_with_options(&cur, xml_opts()) { + Ok(_) => return Ok(cur), + Err(roxmltree::Error::UnknownNamespace(p, _)) if p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') => p, + Err(e) => return malformed(format!("{part}: {e}")), + }; + let at = cur.find("<model").map(|i| i + 6).ok_or_else(|| IoError::Malformed(format!("{part}: no <model> element")))?; + cur.insert_str(at, &format!(" xmlns:{prefix}=\"urn:formshot:undeclared:{prefix}\"")); + scene.warnings.push(format!("{part}: the namespace prefix {prefix:?} is used without a declaration; read by element name")); + } + malformed(format!("{part}: too many undeclared namespace prefixes")) +} + +fn parse_model(text: &str, part: &str, scene: &mut RawScene, watch: &Watch) -> Result<Model> { + let fixed; + let doc = match Document::parse_with_options(text, xml_opts()) { + Ok(d) => d, + Err(roxmltree::Error::UnknownNamespace(..)) => { + fixed = declare_prefixes(text, part, scene)?; + Document::parse_with_options(&fixed, xml_opts()).map_err(|e| IoError::Malformed(format!("{part}: {e}")))? + } + Err(e) => return malformed(format!("{part}: {e}")), + }; + watch.step(Stage::Reading, 0.4)?; + let root = doc.root_element(); + if local(&root) != "model" { + return malformed(format!("{part}: the root element is <{}>, not <model>", local(&root))); + } + let mut model = Model::default(); + if let Some(u) = attr(&root, "unit") { + match unit_of(u.trim()) { + Some(x) => model.unit = Some(x), + None => scene.warnings.push(format!("{part}: unknown unit {u:?}; millimetres assumed")), + } + } + if let Some(req) = attr(&root, "requiredextensions") { + let known: Vec<&str> = root.namespaces().filter(|ns| ns.uri().contains("/material/") || ns.uri().contains("/production/")).filter_map(|ns| ns.name()).collect(); + for prefix in req.split_whitespace().filter(|p| !known.contains(p)) { + let uri = root.lookup_namespace_uri(Some(prefix)).unwrap_or(prefix); + scene.warnings.push(format!("{part}: requires the extension {uri}, which is not read; the model may be incomplete")); + } + } + for res in children(root, "resources") { + for r in res.children().filter(|c| c.is_element() && local(c).ends_with("displayproperties")) { + read_group(r, part, &mut model, scene)?; + } + } + for res in children(root, "resources") { + for r in res.children().filter(|c| c.is_element()) { + if local(&r) != "object" { + if !local(&r).ends_with("displayproperties") { + read_group(r, part, &mut model, scene)?; + } + continue; + } + let id = index(&r, "id")?.ok_or_else(|| IoError::Malformed(format!("{part}: an object has no id")))?; + let name = attr(&r, "name").map(str::to_string).filter(|s| !s.trim().is_empty()).unwrap_or_else(|| format!("Object {id}")); + let kind = attr(&r, "type").unwrap_or("model"); + let skipped = matches!(kind, "support" | "solidsupport"); + let pid = index(&r, "pid")?; + let pindex = index(&r, "pindex")?.unwrap_or(0); + let mut obj = Object { name, skipped, pid, pindex, mesh: None, components: Vec::new() }; + if let Some(m) = children(r, "mesh").next() { + obj.mesh = Some(read_mesh(m, &obj.name, watch)?); + } + for cs in children(r, "components") { + for c in children(cs, "component") { + let cid = index(&c, "objectid")?.ok_or_else(|| IoError::Malformed(format!("{part}: a component has no objectid")))?; + obj.components.push(Component { path: path_attr(&c), id: cid, transform: transform(&c)? }); + } + } + if model.objects.insert(id, obj).is_some() { + return malformed(format!("{part}: object id {id} is used twice")); + } + } + } + for b in children(root, "build") { + for it in children(b, "item") { + let id = index(&it, "objectid")?.ok_or_else(|| IoError::Malformed(format!("{part}: a build item has no objectid")))?; + model.build.push(Item { path: path_attr(&it), id, transform: transform(&it)? }); + } + } + Ok(model) +} + +impl Model { + fn corner(&self, pid: u32, idx: u32, depth: u32) -> Option<Corner> { + let i = idx as usize; + match self.groups.get(&pid)? { + Group::Base(v) => (i < v.len()).then_some(Corner::Base(pid, idx)), + Group::Colour(v) => v.get(i).map(|c| Corner::Colour(*c)), + Group::Tex { uvs, .. } => uvs.get(i).map(|uv| Corner::Tex(pid, *uv)), + Group::Composite { base, mats, rows } => { + let Some(Group::Base(b)) = self.groups.get(base) else { return None }; + let mut c = [0.0f32; 4]; + let mut w = 0.0f32; + for (m, x) in mats.iter().zip(rows.get(i)?) { + let bc = b.get(*m as usize)?.colour; + for k in 0..4 { + c[k] += bc[k] * x.max(0.0); + } + w += x.max(0.0); + } + (w > 0.0).then(|| Corner::Colour(c.map(|v| v / w))) + } + Group::Multi { pids, rows } => { + if depth > 0 { + return None; + } + self.corner(*pids.first()?, *rows.get(i)?.first()?, depth + 1) + } + } + } +} + +fn bucket_of(c: &Corner) -> Bucket { + match c { + Corner::None => Bucket::Plain, + Corner::Base(g, i) => Bucket::Base(*g, *i), + Corner::Colour(_) => Bucket::Colour, + Corner::Tex(g, _) => Bucket::Tex(*g), + } +} + +fn buckets(model: &Model, obj: &Object, md: &MeshData, scale: f32, warnings: &mut Vec<String>, watch: &Watch) -> Result<Vec<(Bucket, RawMesh)>> { + let mut out: Vec<(Bucket, RawMesh)> = Vec::new(); + let mut slot: HashMap<Bucket, usize> = HashMap::new(); + let mut maps: Vec<HashMap<(u32, [u32; 4]), u32>> = Vec::new(); + let mut missing = false; + for (ti, t) in md.tris.iter().enumerate() { + watch.poll(ti)?; + let (pid, p) = match (t.pid, obj.pid) { + (Some(pid), _) => (Some(pid), t.p.map(|x| Some(x.unwrap_or(obj.pindex)))), + (None, Some(pid)) => (Some(pid), [Some(obj.pindex); 3]), + (None, None) => (None, [None; 3]), + }; + let corners: [Corner; 3] = std::array::from_fn(|k| match (pid, p[k]) { + (Some(g), Some(i)) => model.corner(g, i, 0).unwrap_or_else(|| { + missing = true; + Corner::None + }), + _ => Corner::None, + }); + let b = bucket_of(&corners[0]); + let s = *slot.entry(b).or_insert_with(|| { + out.push((b, RawMesh { name: obj.name.clone(), ..Default::default() })); + maps.push(HashMap::new()); + out.len() - 1 + }); + let mesh = &mut out[s].1; + for (k, c) in corners.iter().enumerate() { + let c = if bucket_of(c) == b { c } else { &corners[0] }; + let v = t.v[k]; + let key = match c { + Corner::Colour(col) => (v, col.map(f32::to_bits)), + Corner::Tex(_, uv) => (v, [uv.x.to_bits(), uv.y.to_bits(), 0, 0]), + _ => (v, [0; 4]), + }; + let next = mesh.positions.len() as u32; + let id = *maps[s].entry(key).or_insert_with(|| { + mesh.positions.push(md.verts[v as usize] * scale); + match c { + Corner::Colour(col) => mesh.colours.push(Vec4::from(*col)), + Corner::Tex(_, uv) => { + if mesh.uvs.is_empty() { + mesh.uvs.push(Vec::new()); + } + mesh.uvs[0].push(*uv); + } + _ => {} + } + next + }); + mesh.indices.push(id); + } + } + if missing { + warnings.push(format!("{}: some triangles name properties that do not exist; the default material was used", obj.name)); + } + Ok(out) +} + +#[derive(PartialEq, Eq, Hash)] +enum MatKey { + Base(usize, u32, u32), + Flat([u32; 4]), + VertexColours, + Tex(usize, u32), +} + +fn flat_material(name: String, c: [f32; 4]) -> RawMaterial { + RawMaterial { name, base_colour: [c[0], c[1], c[2]], opacity: c[3].clamp(0.0, 1.0), roughness: 0.4, ..Default::default() } +} + +fn hex(c: [f32; 4]) -> String { + let b = |v: f32| (srgb_encode(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + format!("#{:02X}{:02X}{:02X}", b(c[0]), b(c[1]), b(c[2])) +} + +fn root_part(zip: &Zip) -> String { + let fallback = "3D/3dmodel.model".to_string(); + let Some(e) = zip.find("_rels/.rels") else { return fallback }; + let Ok(bytes) = zip.read(e, 1 << 24) else { return fallback }; + let text = String::from_utf8_lossy(&bytes); + let Ok(doc) = Document::parse(&text) else { return fallback }; + doc.descendants() + .filter(|n| n.is_element() && local(n) == "Relationship") + .find(|n| attr(n, "Type").is_some_and(|t| t.ends_with("/3dmodel"))) + .and_then(|n| attr(&n, "Target")) + .map(|t| t.trim_start_matches('/').to_string()) + .unwrap_or(fallback) +} + +struct Reader<'z, 'w> { + zip: Zip<'z>, + watch: &'w Watch, + parts: Vec<(String, Model)>, + meshes: HashMap<(usize, u32), Vec<usize>>, + mats: HashMap<MatKey, usize>, + images: HashMap<String, String>, + scale: f32, +} + +impl Reader<'_, '_> { + fn part(&mut self, path: Option<&str>, from: usize, scene: &mut RawScene) -> Result<usize> { + let Some(p) = path else { return Ok(from) }; + let p = p.trim_start_matches('/'); + if let Some(i) = self.parts.iter().position(|(n, _)| n.eq_ignore_ascii_case(p)) { + return Ok(i); + } + let e = self.zip.find(p).ok_or_else(|| IoError::Malformed(format!("the package has no part {p}")))?.clone(); + let bytes = self.zip.read(&e, MAX_MODEL_XML)?; + let text = std::str::from_utf8(&bytes).map_err(|_| IoError::Malformed(format!("{p} is not UTF-8")))?; + let model = parse_model(text, p, scene, self.watch)?; + self.parts.push((p.to_string(), model)); + Ok(self.parts.len() - 1) + } + + fn object_meshes(&mut self, part: usize, id: u32, scene: &mut RawScene) -> Result<Vec<usize>> { + if let Some(v) = self.meshes.get(&(part, id)) { + return Ok(v.clone()); + } + let model = &self.parts[part].1; + let Some(obj) = model.objects.get(&id) else { return Ok(Vec::new()) }; + let mut out = Vec::new(); + if let (Some(md), false) = (&obj.mesh, obj.skipped) { + for (b, mut m) in buckets(model, obj, md, self.scale, &mut scene.warnings, self.watch)? { + let key = match b { + Bucket::Plain => None, + Bucket::Base(g, i) => Some(MatKey::Base(part, g, i)), + Bucket::Tex(g) => match model.groups.get(&g) { + Some(Group::Tex { tex, .. }) => Some(MatKey::Tex(part, *tex)), + _ => None, + }, + Bucket::Colour => { + let first = m.colours.first().copied().unwrap_or(Vec4::ONE); + if m.colours.iter().all(|c| *c == first) { + m.colours = Vec::new(); + Some(MatKey::Flat([first.x, first.y, first.z, first.w].map(f32::to_bits))) + } else { + Some(MatKey::VertexColours) + } + } + }; + if let Some(k) = key { + let slot = match self.mats.get(&k) { + Some(&s) => s, + None => { + let mut pending: Vec<(usize, TextureSlot)> = Vec::new(); + let mat = match &k { + MatKey::Base(_, g, i) => match model.groups.get(g) { + Some(Group::Base(v)) => { + let base = &v[*i as usize]; + let mut mat = flat_material(base.name.clone(), base.colour); + if let Some(d) = base.display { + mat.metallic = d.metallic.clamp(0.0, 1.0); + mat.roughness = d.roughness.clamp(0.0, 1.0); + mat.transmission = d.transmission; + mat.ior = d.ior; + } + mat + } + _ => RawMaterial::default(), + }, + MatKey::Flat(bits) => { + let c = bits.map(f32::from_bits); + flat_material(format!("Colour {}", hex(c)), c) + } + MatKey::VertexColours => flat_material("Vertex colours".into(), [1.0; 4]), + MatKey::Tex(_, t) => { + let mut mat = flat_material("Textured".into(), [1.0; 4]); + match model.textures.get(t) { + Some(tex) => { + let path = tex.path.trim_start_matches('/'); + mat.name = path.rsplit('/').next().unwrap_or(path).to_string(); + let uri = match self.images.get(path) { + Some(u) => Some(u.clone()), + None => { + let read = self.zip.find(path).ok_or_else(|| IoError::Malformed(format!("the package has no part {path}"))).and_then(|e| self.zip.read(e, MAX_IMAGE)); + match read { + Ok(bytes) => { + let u = scene.add_image(path, bytes); + self.images.insert(path.to_string(), u.clone()); + Some(u) + } + Err(e) => { + scene.warnings.push(format!("texture {path}: {e}; the texture was skipped")); + None + } + } + } + }; + if let Some(uri) = uri { + scene.textures.push(RawTexture { uri, role: TextureRole::BaseColour, uv_set: 0, colour_space: "srgb" }); + let ti = scene.textures.len() - 1; + mat.textures.push(ti); + let slot = TextureSlot { wrap: tex.wrap, filter: tex.filter, ..TextureSlot::default() }; + pending.push((ti, slot)); + } + } + None => scene.warnings.push(format!("texture {t} is not defined")), + } + mat + } + }; + scene.materials.push(mat); + let mi = scene.materials.len() - 1; + for (texture, slot) in pending { + scene.extra_mut(mi).slots.push(RawSlot { input: MaterialInput::BaseColor, texture, slot }); + } + self.mats.insert(k, mi); + mi + } + }; + m.material = Some(slot); + } + scene.meshes.push(m); + out.push(scene.meshes.len() - 1); + } + } + self.meshes.insert((part, id), out.clone()); + Ok(out) + } + + fn emit(&mut self, part: usize, id: u32, parent: Option<usize>, t: Mat4, stack: &mut Vec<(usize, u32)>, scene: &mut RawScene) -> Result<()> { + if stack.contains(&(part, id)) { + return malformed(format!("object {id} contains itself through its components")); + } + if stack.len() >= MAX_DEPTH { + return malformed("components are nested too deeply"); + } + if scene.nodes.len() >= MAX_NODES { + return Err(IoError::Unsupported("the build expands to more than a million nodes".into())); + } + let (name, skipped, comps) = match self.parts[part].1.objects.get(&id) { + Some(o) => (o.name.clone(), o.skipped, o.components.iter().map(|c| (c.path.clone(), c.id, c.transform)).collect::<Vec<_>>()), + None => return malformed(format!("object {id} is referenced but not defined")), + }; + if skipped { + scene.warnings.push(format!("{name}: support geometry was skipped")); + return Ok(()); + } + if scene.nodes.len().is_multiple_of(256) { + self.watch.step(Stage::Reading, 0.9)?; + } + let meshes = self.object_meshes(part, id, scene)?; + let mut sc = t; + sc.m[0][3] *= self.scale; + sc.m[1][3] *= self.scale; + sc.m[2][3] *= self.scale; + let mut node = RawNode::new(name, parent, meshes); + node.transform = sc; + scene.nodes.push(node); + let me = scene.nodes.len() - 1; + stack.push((part, id)); + for (path, cid, ct) in comps { + let cp = self.part(path.as_deref(), part, scene)?; + self.emit(cp, cid, Some(me), ct, stack, scene)?; + } + stack.pop(); + Ok(()) + } +} + +/// Reads a 3MF package: build items and components become nodes, meshes keep the declared unit, Z is up. +pub fn read_3mf(bytes: &[u8], name: &str, watch: &Watch) -> Result<RawScene> { + watch.step(Stage::Reading, 0.0)?; + let zip = Zip::open(bytes)?; + let root = root_part(&zip); + let mut scene = RawScene::named(name); + scene.up_axis = Some(UpAxis::Z); + let mut r = Reader { zip, watch, parts: Vec::new(), meshes: HashMap::new(), mats: HashMap::new(), images: HashMap::new(), scale: 1.0 }; + let main = r.part(Some(&root), 0, &mut scene)?; + let (unit, scale) = r.parts[main].1.unit.unwrap_or((LengthUnit::Millimetre, 1.0)); + scene.unit = Some(unit); + r.scale = scale; + let items: Vec<(Option<String>, u32, Mat4)> = r.parts[main].1.build.iter().map(|i| (i.path.clone(), i.id, i.transform)).collect(); + if items.is_empty() { + scene.warnings.push("the 3MF build has no items".into()); + } + for (path, id, t) in items { + let p = r.part(path.as_deref(), main, &mut scene)?; + r.emit(p, id, None, t, &mut Vec::new(), &mut scene)?; + } + watch.step(Stage::Reading, 1.0)?; + Ok(scene) +} diff --git a/native/crates/fsh-io/src/triangulate.rs b/native/crates/fsh-io/src/triangulate.rs new file mode 100644 index 00000000..c4fb7b20 --- /dev/null +++ b/native/crates/fsh-io/src/triangulate.rs @@ -0,0 +1,105 @@ +use fsh_core::Vec3; + +/// Polygons with more corners than this are fanned: ear clipping costs up to the cube of the corner count. +pub(crate) const MAX_CLIPPED: usize = 512; + +fn newell(p: &[Vec3]) -> [f64; 3] { + let mut n = [0.0f64; 3]; + for i in 0..p.len() { + let (a, b) = (p[i], p[(i + 1) % p.len()]); + let (ax, ay, az) = (a.x as f64, a.y as f64, a.z as f64); + let (bx, by, bz) = (b.x as f64, b.y as f64, b.z as f64); + n[0] += (ay - by) * (az + bz); + n[1] += (az - bz) * (ax + bx); + n[2] += (ax - bx) * (ay + by); + } + n +} + +fn cross2(o: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 { + (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) +} + +fn fan(n: usize, out: &mut Vec<[usize; 3]>) { + for i in 1..n.saturating_sub(1) { + out.push([0, i, i + 1]); + } +} + +/// Triangles of a simple polygon (concave or slightly non-planar) by ear clipping in its best-fit plane; corners +/// keep the polygon's winding. Falls back to a fan when the polygon has no area, clipping gets stuck, or it has +/// more than [`MAX_CLIPPED`] corners. +pub(crate) fn triangulate(p: &[Vec3]) -> Vec<[usize; 3]> { + let n = p.len(); + let mut out = Vec::with_capacity(n.saturating_sub(2)); + if n < 3 { + return out; + } + if n == 3 { + out.push([0, 1, 2]); + return out; + } + if n > MAX_CLIPPED { + fan(n, &mut out); + return out; + } + let nn = newell(p); + let len = (nn[0] * nn[0] + nn[1] * nn[1] + nn[2] * nn[2]).sqrt(); + if len <= 0.0 || !len.is_finite() { + fan(n, &mut out); + return out; + } + let nz = [nn[0] / len, nn[1] / len, nn[2] / len]; + let helper = if nz[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + let u = { + let c = [nz[1] * helper[2] - nz[2] * helper[1], nz[2] * helper[0] - nz[0] * helper[2], nz[0] * helper[1] - nz[1] * helper[0]]; + let l = (c[0] * c[0] + c[1] * c[1] + c[2] * c[2]).sqrt(); + [c[0] / l, c[1] / l, c[2] / l] + }; + let v = [nz[1] * u[2] - nz[2] * u[1], nz[2] * u[0] - nz[0] * u[2], nz[0] * u[1] - nz[1] * u[0]]; + let q: Vec<[f64; 2]> = p + .iter() + .map(|a| { + let a = [a.x as f64, a.y as f64, a.z as f64]; + [a[0] * u[0] + a[1] * u[1] + a[2] * u[2], a[0] * v[0] + a[1] * v[1] + a[2] * v[2]] + }) + .collect(); + let scale = q.iter().fold(0.0f64, |m, a| m.max(a[0].abs()).max(a[1].abs())).max(1e-30); + let eps = 1e-12 * scale * scale; + let mut ring: Vec<usize> = (0..n).collect(); + let mut guard = 0usize; + let mut i = 0usize; + while ring.len() > 3 { + let m = ring.len(); + let (a, b, c) = (ring[(i + m - 1) % m], ring[i % m], ring[(i + 1) % m]); + let convex = cross2(q[a], q[b], q[c]) > eps; + let ear = convex + && ring.iter().all(|&k| { + if k == a || k == b || k == c || q[k] == q[a] || q[k] == q[b] || q[k] == q[c] { + return true; + } + let (d1, d2, d3) = (cross2(q[a], q[b], q[k]), cross2(q[b], q[c], q[k]), cross2(q[c], q[a], q[k])); + !(d1 >= -eps && d2 >= -eps && d3 >= -eps) + }); + if ear { + out.push([a, b, c]); + ring.remove(i % m); + guard = 0; + if i >= ring.len() { + i = 0; + } + continue; + } + i = (i + 1) % m; + guard += 1; + if guard > m { + let k = (0..m).find(|&k| cross2(q[ring[(k + m - 1) % m]], q[ring[k]], q[ring[(k + 1) % m]]) > eps).unwrap_or(0); + out.push([ring[(k + m - 1) % m], ring[k], ring[(k + 1) % m]]); + ring.remove(k); + guard = 0; + i = 0; + } + } + out.push([ring[0], ring[1], ring[2]]); + out +} diff --git a/native/crates/fsh-io/src/watch.rs b/native/crates/fsh-io/src/watch.rs index cc410dbd..21298f74 100644 --- a/native/crates/fsh-io/src/watch.rs +++ b/native/crates/fsh-io/src/watch.rs @@ -23,6 +23,8 @@ pub enum Stage { Converting = 7, /// Finished. Done = 8, + /// Generating tangents. + Tangents = 9, } impl Stage { @@ -36,6 +38,7 @@ impl Stage { 6 => Stage::Placing, 7 => Stage::Converting, 8 => Stage::Done, + 9 => Stage::Tangents, _ => Stage::Idle, } } @@ -52,6 +55,7 @@ impl Stage { Stage::Placing => "placing", Stage::Converting => "converting", Stage::Done => "done", + Stage::Tangents => "tangents", } } } @@ -96,6 +100,15 @@ impl Watch { self.cancel.load(Ordering::Relaxed) } + /// For long inner loops: every 65536th `i` returns `Cancelled` if the flag is up; progress is left as it is. + pub fn poll(&self, i: usize) -> Result<()> { + if i & 0xFFFF == 0 && self.is_cancelled() { + Err(IoError::Cancelled) + } else { + Ok(()) + } + } + /// Records progress and returns `Cancelled` if the flag is up. pub fn step(&self, stage: Stage, fraction: f32) -> Result<()> { self.set(stage, fraction); diff --git a/native/crates/fsh-io/src/zip.rs b/native/crates/fsh-io/src/zip.rs new file mode 100644 index 00000000..91ee912f --- /dev/null +++ b/native/crates/fsh-io/src/zip.rs @@ -0,0 +1,181 @@ +use crate::deflate::{crc32, inflate}; +use crate::error::{malformed, IoError, Result}; + +const EOCD: u32 = 0x0605_4b50; +const EOCD64: u32 = 0x0606_4b50; +const EOCD64_LOCATOR: u32 = 0x0706_4b50; +const CENTRAL: u32 = 0x0201_4b50; +const LOCAL: u32 = 0x0403_4b50; + +/// Largest member this reader inflates. +pub(crate) const MAX_MEMBER: u64 = 2 << 30; + +/// One member of a ZIP archive, as its central directory describes it. +#[derive(Clone, Debug)] +pub(crate) struct Entry { + pub name: String, + method: u16, + flags: u16, + compressed: u64, + pub size: u64, + crc: u32, + local: u64, +} + +/// A ZIP archive held in memory (stored and deflated members, ZIP64 sizes). +pub(crate) struct Zip<'a> { + data: &'a [u8], + pub entries: Vec<Entry>, +} + +pub(crate) fn is_zip(bytes: &[u8]) -> bool { + bytes.len() >= 4 && u32le(bytes, 0) == Some(LOCAL) +} + +fn u16le(b: &[u8], at: usize) -> Option<u16> { + b.get(at..at.checked_add(2)?).map(|s| u16::from_le_bytes([s[0], s[1]])) +} + +fn u32le(b: &[u8], at: usize) -> Option<u32> { + b.get(at..at.checked_add(4)?).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} + +fn u64le(b: &[u8], at: usize) -> Option<u64> { + let s = b.get(at..at.checked_add(8)?)?; + let mut a = [0u8; 8]; + a.copy_from_slice(s); + Some(u64::from_le_bytes(a)) +} + +fn cut() -> IoError { + IoError::Malformed("the ZIP archive is cut short".into()) +} + +fn find_eocd(data: &[u8]) -> Option<usize> { + if data.len() < 22 { + return None; + } + let lowest = data.len().saturating_sub(22 + 65535); + (lowest..=data.len() - 22).rev().find(|&i| u32le(data, i) == Some(EOCD)) +} + +fn zip64_fields(extra: &[u8], size: &mut u64, compressed: &mut u64, local: &mut u64) -> Result<()> { + let mut i = 0; + while i + 4 <= extra.len() { + let id = u16le(extra, i).ok_or_else(cut)?; + let len = u16le(extra, i + 2).ok_or_else(cut)? as usize; + let body = extra.get(i + 4..i + 4 + len).ok_or_else(cut)?; + if id == 1 { + let mut at = 0; + for slot in [size, compressed, local] { + if *slot == u32::MAX as u64 { + *slot = u64le(body, at).ok_or_else(|| IoError::Malformed("ZIP64 extra field is cut short".into()))?; + at += 8; + } + } + return Ok(()); + } + i += 4 + len; + } + Ok(()) +} + +impl<'a> Zip<'a> { + /// Reads the central directory. + pub fn open(data: &'a [u8]) -> Result<Self> { + let e = find_eocd(data).ok_or_else(|| IoError::Malformed("no ZIP end-of-directory record".into()))?; + let mut count = u16le(data, e + 10).ok_or_else(cut)? as u64; + let mut dir_size = u32le(data, e + 12).ok_or_else(cut)? as u64; + let mut dir_at = u32le(data, e + 16).ok_or_else(cut)? as u64; + if e >= 20 && u32le(data, e - 20) == Some(EOCD64_LOCATOR) { + let at = u64le(data, e - 12).ok_or_else(cut)?; + let at = usize::try_from(at).map_err(|_| cut())?; + if u32le(data, at) != Some(EOCD64) { + return malformed("ZIP64 end-of-directory record is missing"); + } + count = u64le(data, at + 32).ok_or_else(cut)?; + dir_size = u64le(data, at + 40).ok_or_else(cut)?; + dir_at = u64le(data, at + 48).ok_or_else(cut)?; + } + let end = dir_at.checked_add(dir_size).ok_or_else(cut)?; + if end > data.len() as u64 { + return Err(cut()); + } + if count > dir_size / 46 + 1 { + return malformed("the ZIP directory claims more members than it can hold"); + } + let mut entries = Vec::with_capacity(count as usize); + let mut p = dir_at as usize; + for _ in 0..count { + if u32le(data, p) != Some(CENTRAL) { + return malformed("bad ZIP central directory entry"); + } + let flags = u16le(data, p + 8).ok_or_else(cut)?; + let method = u16le(data, p + 10).ok_or_else(cut)?; + let crc = u32le(data, p + 16).ok_or_else(cut)?; + let mut compressed = u32le(data, p + 20).ok_or_else(cut)? as u64; + let mut size = u32le(data, p + 24).ok_or_else(cut)? as u64; + let name_len = u16le(data, p + 28).ok_or_else(cut)? as usize; + let extra_len = u16le(data, p + 30).ok_or_else(cut)? as usize; + let comment_len = u16le(data, p + 32).ok_or_else(cut)? as usize; + let mut local = u32le(data, p + 42).ok_or_else(cut)? as u64; + let name = data.get(p + 46..p + 46 + name_len).ok_or_else(cut)?; + let extra = data.get(p + 46 + name_len..p + 46 + name_len + extra_len).ok_or_else(cut)?; + zip64_fields(extra, &mut size, &mut compressed, &mut local)?; + entries.push(Entry { + name: String::from_utf8_lossy(name).into_owned(), + method, + flags, + compressed, + size, + crc, + local, + }); + p += 46 + name_len + extra_len + comment_len; + } + Ok(Self { data, entries }) + } + + /// Member by path, ignoring a leading slash and letter case. + pub fn find(&self, path: &str) -> Option<&Entry> { + let want = path.trim_start_matches('/'); + self.entries + .iter() + .find(|e| e.name == want) + .or_else(|| self.entries.iter().find(|e| e.name.trim_start_matches('/').eq_ignore_ascii_case(want))) + } + + /// Bytes of one member, refusing members larger than `cap`. + pub fn read(&self, e: &Entry, cap: u64) -> Result<Vec<u8>> { + if e.flags & 1 != 0 { + return Err(IoError::Unsupported(format!("{} is encrypted", e.name))); + } + if e.size > cap.min(MAX_MEMBER) { + return Err(IoError::Unsupported(format!("{} is too large ({} bytes)", e.name, e.size))); + } + let at = usize::try_from(e.local).map_err(|_| cut())?; + if u32le(self.data, at) != Some(LOCAL) { + return malformed(format!("bad ZIP local header for {}", e.name)); + } + let n = u16le(self.data, at + 26).ok_or_else(cut)? as usize; + let x = u16le(self.data, at + 28).ok_or_else(cut)? as usize; + let start = at + 30 + n + x; + let len = usize::try_from(e.compressed).map_err(|_| cut())?; + let body = self.data.get(start..start.checked_add(len).ok_or_else(cut)?).ok_or_else(cut)?; + if e.method == 8 && e.size > e.compressed.saturating_mul(1032).saturating_add(64) { + return malformed(format!("{} declares more data than deflate can hold", e.name)); + } + let out = match e.method { + 0 => body.to_vec(), + 8 => inflate(body, e.size as usize)?.0, + m => return Err(IoError::Unsupported(format!("{} uses ZIP compression method {m}", e.name))), + }; + if out.len() as u64 != e.size { + return malformed(format!("{} inflated to {} bytes, not the {} declared", e.name, out.len(), e.size)); + } + if crc32(&out) != e.crc { + return malformed(format!("{} fails its CRC check", e.name)); + } + Ok(out) + } +} diff --git a/native/crates/fsh-materials/Cargo.toml b/native/crates/fsh-materials/Cargo.toml index ff2f94b2..8707acd3 100644 --- a/native/crates/fsh-materials/Cargo.toml +++ b/native/crates/fsh-materials/Cargo.toml @@ -1,9 +1,10 @@ [package] name = "fsh-materials" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false [dependencies] fsh-core = { path = "../fsh-core" } +serde = { version = "1", features = ["derive"] } diff --git a/native/crates/fsh-materials/src/bsdf.rs b/native/crates/fsh-materials/src/bsdf.rs index cd89332c..a421ffd5 100644 --- a/native/crates/fsh-materials/src/bsdf.rs +++ b/native/crates/fsh-materials/src/bsdf.rs @@ -4,10 +4,12 @@ use fsh_core::math::{INV_PI, ONE_MINUS_EPSILON}; use fsh_core::sampling::{cosine_hemisphere, uniform_hemisphere, uniform_hemisphere_pdf}; use fsh_core::{lerp, Frame, Rgb, Vec2, Vec3}; +use crate::film::{film_conductor, film_dielectric, gulbrandsen, FilmLayer}; use crate::fresnel::{dielectric, eta_from_weight, reflect, refract, F82}; use crate::ggx::Ggx; use crate::inputs::SurfaceInputs; use crate::lobes::{eon_albedo, eon_eval, sheen_eval}; +use crate::optics::Optics; use crate::tables::tables; /// World-space frame at a hit point; normals need not be unit or agree in sign. @@ -82,6 +84,8 @@ const SPEC_R: usize = 3; const SPEC_T: usize = 4; const DIFFUSE: usize = 5; const BEND: f32 = 0.01; +const FILM_QUAD: [Vec2; 4] = + [Vec2::new(0.25, 0.25), Vec2::new(0.75, 0.25), Vec2::new(0.25, 0.75), Vec2::new(0.75, 0.75)]; const ETA_PASS: f32 = 1e-3; /// The layered surface BSDF at one shading point. Directions point away from the surface. @@ -116,6 +120,7 @@ pub struct Bsdf { e_avg: f32, emission: Rgb, opacity: f32, + film: FilmLayer, } #[derive(Clone, Copy)] @@ -125,6 +130,7 @@ struct Ctx { wo: Vec3, eta: f32, eta_r: f32, + film_n2: f32, r_opaque: f32, r_trans: f32, front: bool, @@ -238,9 +244,89 @@ impl Bsdf { e_avg, emission: s.emission, opacity: s.opacity, + film: FilmLayer::NONE, } } + /// As `new`, with the thin film of `optics` on the specular base (the dispersion of `optics` is the renderer's job). + pub fn new_optics(inputs: &SurfaceInputs, optics: &Optics, frame: &ShadingFrame, eta: f32) -> Self { + let mut b = Self::new(inputs, frame, eta); + if !optics.has_film() { + return b; + } + let s = inputs.sanitized(); + let eta = if eta.is_finite() && eta > 0.0 { eta.clamp(0.25, 4.0) } else { s.specular_ior }; + let exterior = s.specular_ior / eta; + let above = lerp(exterior, s.coat_ior, s.coat_weight); + let mut metal_n = Rgb::WHITE; + let mut metal_k = Rgb::BLACK; + for c in 0..3 { + let (n, k) = gulbrandsen(b.rho[c], b.spec_color[c]); + metal_n[c] = n / above; + metal_k[c] = k / above; + } + b.film = FilmLayer { + weight: optics.film_weight, + d: optics.film_thickness, + n2_front: optics.film_ior / above, + n2_ext: optics.film_ior / exterior, + metal_n, + metal_k, + }; + b + } + + fn film_on(&self) -> bool { + self.film.weight > 0.0 + } + + fn diel_film(&self, c: &Ctx, cos: f32, eta: f32) -> Rgb { + let f = dielectric(cos, eta); + let a = film_dielectric(cos, c.film_n2, eta, self.film.d); + Rgb::gray(f) + (a - Rgb::gray(f)) * self.film.weight + } + + fn spec_fresnel_rgb(&self, c: &Ctx, cos: f32) -> Rgb { + if !self.film_on() { + return Rgb::gray(spec_fresnel(c, cos)); + } + let mut f = self.diel_film(c, cos, c.eta) * c.r_trans; + if c.r_opaque > 0.0 { + f += self.diel_film(c, cos, c.eta_r) * c.r_opaque; + } + f + } + + fn trans_fresnel(&self, c: &Ctx, cos: f32) -> Rgb { + if !self.film_on() { + return Rgb::gray(1.0 - dielectric(cos, c.eta)); + } + (Rgb::WHITE - self.diel_film(c, cos, c.eta)).non_negative() + } + + fn metal_fresnel(&self, c: &Ctx, cos: f32) -> Rgb { + let f = self.f82.eval(cos); + if !self.film_on() { + return f; + } + let fl = &self.film; + let a = film_conductor(cos, c.film_n2, fl.metal_n, fl.metal_k, fl.d); + f + (a - f) * fl.weight + } + + fn film_delta(&self, c: &Ctx, mu: f32, eta: f32) -> Rgb { + let delta = |cos: f32| self.diel_film(c, cos, eta) - Rgb::gray(dielectric(cos, eta)); + if self.spec_delta { + return delta(mu); + } + let e1 = tables().cond(mu, self.spec.alpha_eff()).clamp(0.0, 1.0); + let mut sum = Rgb::BLACK; + for u in FILM_QUAD { + sum += delta(c.wo.dot(self.spec.sample_visible(c.wo, u)).clamp(0.0, 1.0)); + } + sum * (0.25 * e1) + } + /// Geometric opacity for stochastic pass-through. pub fn opacity(&self) -> f32 { self.opacity @@ -367,6 +453,7 @@ impl Bsdf { wo, eta: 1.0, eta_r: 1.0, + film_n2: if interior { self.film.n2_ext * self.eta_back } else { self.film.n2_front }, r_opaque: 0.0, r_trans: 0.0, front, @@ -392,6 +479,11 @@ impl Bsdf { c.a[SPEC_R] = Rgb::gray(er * norm); c.w[SPEC_T] = Rgb::gray(norm); c.a[SPEC_T] = Rgb::gray(et); + if self.film_on() { + let dt = self.film_delta(&c, mu, c.eta); + c.a[SPEC_R] = ((Rgb::gray(er) + dt) * norm).non_negative(); + c.a[SPEC_T] = (Rgb::gray(et) - dt).non_negative(); + } c.above = Rgb::BLACK; } else { c.eta = self.eta_trans; @@ -423,7 +515,7 @@ impl Bsdf { c.e_o = e; c.ms_p = if self.spec_delta || 1.0 - self.e_avg < 1e-4 { 0.0 } else { 1.0 - e }; c.w[METAL] = above * (self.metalness * self.spec_weight); - c.a[METAL] = self.f82.eval(mu) * e + self.f_ms * (1.0 - e); + c.a[METAL] = self.metal_fresnel(&c, mu) * e + self.f_ms * (1.0 - e); } let dw = above * (1.0 - self.metalness); if dw.max_element() > 0.0 { @@ -449,6 +541,14 @@ impl Bsdf { c.a[SPEC_T] = Rgb::gray(et); c.w[DIFFUSE] = dw * ((1.0 - tw) * (1.0 - erf).max(0.0)); c.a[DIFFUSE] = eon_albedo(self.rho, self.sigma, mu); + if self.film_on() { + let dt = self.film_delta(&c, mu, c.eta); + let d_o = if c.eta_r == c.eta { dt } else { self.film_delta(&c, mu, c.eta_r) }; + let rf = Rgb::gray(erf) + d_o; + c.a[SPEC_R] = ((rf * c.r_opaque) + (Rgb::gray(er) + dt) * c.r_trans).non_negative(); + c.a[SPEC_T] = (Rgb::gray(et) - dt).non_negative(); + c.w[DIFFUSE] = dw * ((Rgb::WHITE - rf).non_negative() * (1.0 - tw)); + } } } let mut total = 0.0; @@ -533,7 +633,7 @@ impl Bsdf { let mut v = Rgb::BLACK; let mut p = 0.0; if let Some((core, pdf, ch)) = self.spec.reflection(wo, wi) { - v = self.f82.eval(ch) * core; + v = self.metal_fresnel(c, ch) * core; p = (1.0 - c.ms_p) * pdf; } if c.ms_p > 0.0 { @@ -545,17 +645,22 @@ impl Bsdf { (v, p) } SPEC_R => match self.spec.reflection(wo, wi) { + Some((core, pdf, ch)) if self.film_on() => (self.spec_fresnel_rgb(c, ch) * core, pdf), Some((core, pdf, ch)) => (Rgb::gray(core * spec_fresnel(c, ch)), pdf), None => none, }, SPEC_T => { if self.thin { match self.spec.reflection(wo, Vec3::new(wi.x, wi.y, -wi.z)) { + Some((core, pdf, ch)) if self.film_on() => (self.trans_fresnel(c, ch) * core, pdf), Some((core, pdf, ch)) => (Rgb::gray(core * (1.0 - dielectric(ch, c.eta))), pdf), None => none, } } else { match self.spec.transmission(wo, wi, c.eta) { + Some((core, pdf, ch)) if self.film_on() => { + (self.trans_fresnel(c, ch) * (core / (c.eta * c.eta)), pdf) + } Some((core, pdf, ch)) => { let f = 1.0 - dielectric(ch, c.eta); (Rgb::gray(core * f / (c.eta * c.eta)), pdf) @@ -603,15 +708,17 @@ impl Bsdf { let mirror = Vec3::new(-wo.x, -wo.y, wo.z); match i { COAT => Some((mirror, Rgb::gray(dielectric(wo.z, self.coat_eta)), false)), - METAL => Some((mirror, self.f82.eval(wo.z), false)), - SPEC_R => Some((mirror, Rgb::gray(spec_fresnel(c, wo.z)), false)), + METAL => Some((mirror, self.metal_fresnel(c, wo.z), false)), + SPEC_R => Some((mirror, self.spec_fresnel_rgb(c, wo.z), false)), SPEC_T => { let f = 1.0 - dielectric(wo.z, c.eta); + let fc = if self.film_on() { self.trans_fresnel(c, wo.z) } else { Rgb::gray(f) }; if self.thin || (c.eta - 1.0).abs() < ETA_PASS { - Some((-wo, Rgb::gray(f), true)) + Some((-wo, fc, true)) } else { let wt = refract(wo, Vec3::Z, c.eta)?; - Some((wt, Rgb::gray(f / (c.eta * c.eta)), true)) + let fc = if self.film_on() { fc / (c.eta * c.eta) } else { Rgb::gray(f / (c.eta * c.eta)) }; + Some((wt, fc, true)) } } _ => None, diff --git a/native/crates/fsh-materials/src/film.rs b/native/crates/fsh-materials/src/film.rs new file mode 100644 index 00000000..70bb3e81 --- /dev/null +++ b/native/crates/fsh-materials/src/film.rs @@ -0,0 +1,155 @@ +use fsh_core::math::PI; +use fsh_core::Rgb; + +const SENS_AMP: [f32; 3] = [8.465_9e-1, 1.000_221_9, 1.001_122_5]; +const SENS_A: [f32; 3] = [1.056_203_4e1, 1.128_020_3e1, 1.387_578_6e1]; +const SENS_B: [f32; 3] = [1.708_547e-1, 3.673_309e-1, 2.610_352_4e-1]; +const SENS_X2_AMP: f32 = 1.538_683e-1; +const SENS_X2_A: f32 = 1.407_370_7e1; +const SENS_X2_B: f32 = 1.787_661_7e-1; + +const XYZ_TO_ACESCG_E: [[f32; 3]; 3] = [ + [1.593_588_8, -0.367_700_6, -0.226_282_92], + [-0.690_467_2, 1.672_178_1, 0.018_214_02], + [0.011_094_39, -0.006_686_05, 0.994_471_8], +]; + +/// A thin film as a built BSDF holds it: iors relative to the medium above the film (the coat mix) and to the exterior. +#[derive(Clone, Copy, Debug)] +pub(crate) struct FilmLayer { + pub weight: f32, + pub d: f32, + pub n2_front: f32, + pub n2_ext: f32, + pub metal_n: Rgb, + pub metal_k: Rgb, +} + +impl FilmLayer { + pub const NONE: Self = + Self { weight: 0.0, d: 0.0, n2_front: 1.0, n2_ext: 1.0, metal_n: Rgb::WHITE, metal_k: Rgb::BLACK }; +} + +const ORDERS: u32 = 3; +const THIN_LIMIT: f32 = 0.03; + +fn sensitivity(opd: f32, shift: f32) -> [f32; 3] { + let x2 = opd * opd; + let mut s: [f32; 3] = + core::array::from_fn(|c| SENS_AMP[c] * (SENS_A[c] * opd + shift).cos() * (-SENS_B[c] * x2).exp()); + s[0] += SENS_X2_AMP * (SENS_X2_A * opd + shift).cos() * (-SENS_X2_B * x2).exp(); + s +} + +fn dielectric_sp(ct1: f32, n1: f32, n2: f32) -> ([f32; 2], [f32; 2]) { + let st1 = 1.0 - ct1 * ct1; + let nr = n1 / n2; + let nr2 = nr * nr; + if nr2 * st1 > 1.0 { + let s = (st1 - 1.0 / nr2).max(0.0).sqrt(); + let c = ct1.max(1e-7); + return ([1.0, 1.0], [2.0 * (-nr2 * s / c).atan(), 2.0 * (-s / c).atan()]); + } + let ct2 = (1.0 - nr2 * st1).max(0.0).sqrt(); + let rp = (n2 * ct1 - n1 * ct2) / (n2 * ct1 + n1 * ct2); + let rs = (n1 * ct1 - n2 * ct2) / (n1 * ct1 + n2 * ct2); + let phi = |r: f32| if r < 0.0 { PI } else { 0.0 }; + ([rp * rp, rs * rs], [phi(rp), phi(rs)]) +} + +fn conductor_sp(ct1: f32, n1: f32, n: f32, k: f32) -> ([f32; 2], [f32; 2]) { + if k <= 0.0 { + return dielectric_sp(ct1, n1, n); + } + let nk2 = n * n - k * k; + let a = nk2 - n1 * n1 * (1.0 - ct1 * ct1); + let b = (a * a + 4.0 * n * n * k * k).sqrt(); + let u = (0.5 * (a + b)).max(0.0).sqrt(); + let v = (0.5 * (b - a)).max(0.0).sqrt(); + let n1c = n1 * ct1; + let rs = ((n1c - u) * (n1c - u) + v * v) / ((n1c + u) * (n1c + u) + v * v); + let phis = (2.0 * n1 * v * ct1).atan2(u * u + v * v - n1c * n1c) + PI; + let x = nk2 * ct1; + let y = 2.0 * n * k * ct1; + let rp = ((x - n1 * u) * (x - n1 * u) + (y - n1 * v) * (y - n1 * v)) + / ((x + n1 * u) * (x + n1 * u) + (y + n1 * v) * (y + n1 * v)); + let w = (n * n + k * k) * ct1; + let phip = (2.0 * n1 * ct1 * (2.0 * n * k * u - nk2 * v)).atan2(w * w - n1 * n1 * (u * u + v * v)); + ([rp, rs], [phip, phis]) +} + +fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// Airy reflectance of a film (`n2`, `d` micrometres) over a base (`n3 + i k3`), all relative to the medium above, +/// integrated against the CIE 1931 observer: the unpolarised mean (DC) term and the XYZ of the oscillating terms. +fn airy(ct1: f32, n2: f32, n3: f32, k3: f32, d: f32) -> Option<(f32, [f32; 3])> { + let ct1 = ct1.clamp(0.0, 1.0); + let eta2 = 1.0 + (n2 - 1.0) * smoothstep(0.0, THIN_LIMIT, d); + let s2 = (1.0 - ct1 * ct1) / (eta2 * eta2); + if s2 >= 1.0 { + return None; + } + let ct2 = (1.0 - s2).sqrt(); + let (r12, phi12) = dielectric_sp(ct1, 1.0, eta2); + let (r23, phi23) = conductor_sp(ct2, eta2, n3, k3); + let opd = 2.0 * eta2 * d * ct2; + let mut dc = 0.0; + let mut xyz = [0.0f32; 3]; + for p in 0..2 { + let t121 = 1.0 - r12[p]; + let r123 = r12[p] * r23[p]; + let rs = if 1.0 - r123 > 1e-7 { t121 * t121 * r23[p] / (1.0 - r123) } else { 0.0 }; + dc += 0.5 * (r12[p] + rs); + let phi2 = PI - phi12[p] + phi23[p]; + let root = r123.max(0.0).sqrt(); + let mut cm = rs - t121; + for m in 1..=ORDERS { + cm *= root; + let mf = m as f32; + for (x, s) in xyz.iter_mut().zip(sensitivity(mf * opd, mf * phi2)) { + *x += cm * s; + } + } + } + Some((dc, xyz)) +} + +fn to_acescg(row: usize, xyz: &[f32; 3]) -> f32 { + let m = &XYZ_TO_ACESCG_E[row]; + m[0] * xyz[0] + m[1] * xyz[1] + m[2] * xyz[2] +} + +/// Reflectance in ACEScg of a film of relative ior `n2` and thickness `d` (micrometres) over a dielectric of relative ior `n3`. +pub(crate) fn film_dielectric(ct1: f32, n2: f32, n3: f32, d: f32) -> Rgb { + match airy(ct1, n2, n3, 0.0, d) { + Some((dc, xyz)) => { + let f = |c: usize| (dc + to_acescg(c, &xyz)).clamp(0.0, 1.0); + Rgb::new(f(0), f(1), f(2)) + } + None => Rgb::WHITE, + } +} + +/// As `film_dielectric` over a conductor with a complex ior per channel, each channel taken from its own evaluation. +pub(crate) fn film_conductor(ct1: f32, n2: f32, n3: Rgb, k3: Rgb, d: f32) -> Rgb { + let mut out = Rgb::WHITE; + for c in 0..3 { + if let Some((dc, xyz)) = airy(ct1, n2, n3[c], k3[c], d) { + out[c] = (dc + to_acescg(c, &xyz)).clamp(0.0, 1.0); + } + } + out +} + +/// Complex ior (n, k) reproducing normal reflectance `r` with edge tint `g` (Gulbrandsen 2014). +pub(crate) fn gulbrandsen(r: f32, g: f32) -> (f32, f32) { + let r = r.clamp(0.0, 0.99); + let g = g.clamp(0.0, 1.0); + let sr = r.sqrt(); + let n = g * (1.0 - r) / (1.0 + r) + (1.0 - g) * (1.0 + sr) / (1.0 - sr); + let k2 = (r * (n + 1.0) * (n + 1.0) - (n - 1.0) * (n - 1.0)) / (1.0 - r); + (n, k2.max(0.0).sqrt()) +} diff --git a/native/crates/fsh-materials/src/interp.rs b/native/crates/fsh-materials/src/interp.rs new file mode 100644 index 00000000..5e8762bc --- /dev/null +++ b/native/crates/fsh-materials/src/interp.rs @@ -0,0 +1,420 @@ +use crate::inputs::SurfaceInputs; +use crate::procedural::{procedural, ProcKind}; +use crate::program::{input, Field, Filter, Instr, Op, Program, Wrap, LABEL_ONE_SIDED, MAX_UV_SETS, REGISTERS}; +use crate::texture::TextureSampler; +use fsh_core::color::ACESCG_LUMINANCE; +use fsh_core::math::{smoothstep, INV_PI, TWO_PI}; +use fsh_core::{orthonormal_basis, Rgb, Vec2, Vec3}; + +/// Everything a program may read at one shading point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HitContext { + /// World position (metres). + pub p: Vec3, + /// Object-space position (metres). + pub p_object: Vec3, + /// Unit geometric normal, world space. + pub ng: Vec3, + /// Unit shading normal, world space. + pub ns: Vec3, + /// Unit shading normal, object space. + pub n_object: Vec3, + /// Uv sets (unused entries zero). + pub uv: [Vec2; MAX_UV_SETS], + /// Uv sets the mesh has. + pub uv_count: u32, + /// World dP/du of uv set 0; an orthonormal frame around `ns` when the mesh has no uvs. + pub dpdu: Vec3, + /// World dP/dv of uv set 0. + pub dpdv: Vec3, + /// Object-space dP/du. + pub dpdu_object: Vec3, + /// Object-space dP/dv. + pub dpdv_object: Vec3, + /// Unit mesh tangent, world space; zero when the mesh has none. + pub tangent: Vec3, + /// Handedness of the mesh tangent frame (+1 or -1). + pub tangent_sign: f32, + /// World width of the pixel footprint at the hit (metres). + pub footprint: f32, +} + +impl Default for HitContext { + fn default() -> Self { + Self { + p: Vec3::ZERO, + p_object: Vec3::ZERO, + ng: Vec3::Z, + ns: Vec3::Z, + n_object: Vec3::Z, + uv: [Vec2::ZERO; MAX_UV_SETS], + uv_count: 0, + dpdu: Vec3::X, + dpdv: Vec3::Y, + dpdu_object: Vec3::X, + dpdv_object: Vec3::Y, + tangent: Vec3::ZERO, + tangent_sign: 1.0, + footprint: 0.0, + } + } +} + +/// What a program produced at one shading point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Shaded { + /// Sanitised surface inputs. + pub inputs: SurfaceInputs, + /// Shading normal to use (the incoming one when the program leaves it). + pub normal: Vec3, + /// True when the program wrote the normal. + pub normal_changed: bool, + /// Displacement in metres (not applied per hit). + pub displacement: f32, +} + +type V4 = [f32; 4]; + +fn v3(v: V4) -> Vec3 { + Vec3::new(v[0], v[1], v[2]) +} + +fn v4(v: Vec3, w: f32) -> V4 { + [v.x, v.y, v.z, w] +} + +fn zip(a: V4, b: V4, f: impl Fn(f32, f32) -> f32) -> V4 { + [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2]), f(a[3], b[3])] +} + +fn map(a: V4, f: impl Fn(f32) -> f32) -> V4 { + [f(a[0]), f(a[1]), f(a[2]), f(a[3])] +} + +fn konst(consts: &[f32], at: u32, n: usize) -> &[f32] { + let s = (at as usize).min(consts.len()); + &consts[s..(s + n).min(consts.len())] +} + +fn ramp(x: f32, consts: &[f32], at: u32, mode: u8) -> V4 { + let n = consts.get(at as usize).copied().unwrap_or(0.0).max(0.0) as usize; + let stops = konst(consts, at + 1, n * 5); + let n = stops.len() / 5; + if n == 0 { + return [0.0; 4]; + } + let stop = |i: usize| -> (f32, V4) { (stops[i * 5], [stops[i * 5 + 1], stops[i * 5 + 2], stops[i * 5 + 3], stops[i * 5 + 4]]) }; + let x = if x.is_finite() { x } else { 0.0 }; + if x <= stop(0).0 { + return stop(0).1; + } + for i in 1..n { + let (p1, c1) = stop(i); + if x < p1 { + let (p0, c0) = stop(i - 1); + if mode == 1 { + return c0; + } + let span = p1 - p0; + let t = if span > 0.0 { (x - p0) / span } else { 1.0 }; + let t = if mode == 2 { smoothstep(0.0, 1.0, t) } else { t }; + return zip(c0, c1, |a, b| a + (b - a) * t); + } + } + stop(n - 1).1 +} + +fn xform2(a: V4, k: &[f32]) -> V4 { + if k.len() < 6 { + return a; + } + let (sx, sy, c, s, ox, oy) = (k[0], k[1], k[2], k[3], k[4], k[5]); + let (u, v) = (a[0] * sx, a[1] * sy); + [c * u - s * v + ox, s * u + c * v + oy, a[2] * sx.abs().max(sy.abs()), a[3]] +} + +fn project(a: V4, kind: u8) -> V4 { + let (x, y, z, w) = (a[0], a[1], a[2], a[3]); + match kind { + 1 => { + let r = (x * x + z * z).sqrt().max(1.0e-3); + [x.atan2(z) / TWO_PI + 0.5, y, w * (1.0 / (TWO_PI * r)).max(1.0), 0.0] + } + 2 => { + let len = (x * x + y * y + z * z).sqrt(); + let v = if len > 0.0 { (y / len).clamp(-1.0, 1.0).acos() * INV_PI } else { 0.5 }; + [x.atan2(z) / TWO_PI + 0.5, v, w * INV_PI / len.max(1.0e-3), 0.0] + } + _ => [x, y, w, 0.0], + } +} + +fn label(a: V4, c: V4, k: &[f32], flags: u8) -> V4 { + if k.len() < 12 { + return [0.0; 4]; + } + let d = Vec3::new(a[0] - k[0], a[1] - k[1], a[2] - k[2]); + let (right, up, normal) = (Vec3::new(k[3], k[4], k[5]), Vec3::new(k[6], k[7], k[8]), Vec3::new(k[9], k[10], k[11])); + let u = d.dot(right) + 0.5; + let v = d.dot(up) + 0.5; + let w = d.dot(normal); + let fu = a[3] * right.length().max(up.length()); + let inside = (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v) && (-1.0..=1.0).contains(&w); + let facing = flags & LABEL_ONE_SIDED == 0 || v3(c).dot(normal.try_normalize().unwrap_or(Vec3::ZERO)) > 0.0; + [u, v, fu, if inside && facing { 1.0 } else { 0.0 }] +} + +/// Result of a pure instruction on known operand values, or `None` when the instruction depends on the hit. +pub fn fold(i: &Instr, a: V4, b: V4, c: V4, consts: &[f32]) -> Option<V4> { + Some(match i.op { + Op::Nop => return None, + Op::Const => { + let k = konst(consts, i.a, 4); + [k.first().copied().unwrap_or(0.0), k.get(1).copied().unwrap_or(0.0), k.get(2).copied().unwrap_or(0.0), k.get(3).copied().unwrap_or(0.0)] + } + Op::Swizzle => { + let s = |n: u32| a[((i.flags as u32 >> (2 * n)) & 3) as usize]; + [s(0), s(1), s(2), s(3)] + } + Op::Combine => [a[0], b[0], c[0], 0.0], + Op::Add => zip(a, b, |x, y| x + y), + Op::Sub => zip(a, b, |x, y| x - y), + Op::Mul => zip(a, b, |x, y| x * y), + Op::Div => zip(a, b, |x, y| if y == 0.0 { 0.0 } else { x / y }), + Op::Min => zip(a, b, f32::min), + Op::Max => zip(a, b, f32::max), + Op::Pow => zip(a, b, |x, y| { + let r = x.max(0.0).powf(y); + if r.is_finite() { + r + } else { + 0.0 + } + }), + Op::Lerp => zip(a, b, |x, y| x + (y - x) * c[0]), + Op::Clamp => [0, 1, 2, 3].map(|n| a[n].max(b[n]).min(c[n])), + Op::Invert => map(a, |x| 1.0 - x), + Op::Luminance => { + let l = a[0] * ACESCG_LUMINANCE[0] + a[1] * ACESCG_LUMINANCE[1] + a[2] * ACESCG_LUMINANCE[2]; + [l; 4] + } + Op::Ramp => ramp(a[0], consts, i.b, i.flags), + Op::Xform2 => xform2(a, konst(consts, i.b, 6)), + Op::Project => project(a, i.flags), + Op::Label => label(a, c, konst(consts, i.b, 12), i.flags), + Op::Input | Op::Tex | Op::TexBox | Op::NormalMap | Op::Bump | Op::Proc => return None, + }) +} + +fn bump_step(ctx: &HitContext) -> (f32, f32) { + let eps = (0.5 * ctx.footprint).clamp(1.0e-6, 1.0e-2); + let lu = ctx.dpdu.length(); + let lv = ctx.dpdv.length(); + let du = if lu > 0.0 && lu.is_finite() { eps / lu } else { 0.0 }; + let dv = if lv > 0.0 && lv.is_finite() { eps / lv } else { 0.0 }; + (du, dv) +} + +fn uv_footprint(ctx: &HitContext) -> f32 { + let area = ctx.dpdu.cross(ctx.dpdv).length(); + if area > 0.0 && area.is_finite() { + ctx.footprint / area.sqrt() + } else { + 0.0 + } +} + +fn read_input(ctx: &HitContext, which: u8, offset: u8, set: u32) -> V4 { + let (du, dv) = bump_step(ctx); + let (su, sv) = match offset { + input::OFFSET_U => (du, 0.0), + input::OFFSET_V => (0.0, dv), + _ => (0.0, 0.0), + }; + let fp = ctx.footprint; + match which { + input::POSITION => v4(ctx.p + ctx.dpdu * su + ctx.dpdv * sv, fp), + input::POSITION_OBJECT => v4(ctx.p_object + ctx.dpdu_object * su + ctx.dpdv_object * sv, fp), + input::NORMAL => v4(ctx.ns, 0.0), + input::GEOMETRIC_NORMAL => v4(ctx.ng, 0.0), + input::NORMAL_OBJECT => v4(ctx.n_object, 0.0), + input::UV => { + let set = if set >= ctx.uv_count { 0 } else { set }; + let uv = ctx.uv.get(set as usize).copied().unwrap_or(Vec2::ZERO); + [uv.x + su, uv.y + sv, uv_footprint(ctx), 0.0] + } + input::TANGENT => v4(ctx.tangent, ctx.tangent_sign), + input::FOOTPRINT => [fp, 0.0, 0.0, 0.0], + _ => [0.0; 4], + } +} + +fn tangent_frame(ctx: &HitContext, n: Vec3) -> (Vec3, Vec3) { + let raw = if ctx.tangent.length_squared() > 0.0 { ctx.tangent } else { ctx.dpdu }; + let t = (raw - n * n.dot(raw)).try_normalize().filter(|t| t.is_finite()).unwrap_or_else(|| orthonormal_basis(n).0); + let sign = if ctx.tangent.length_squared() > 0.0 { + if ctx.tangent_sign < 0.0 { + -1.0 + } else { + 1.0 + } + } else if n.cross(t).dot(ctx.dpdv) < 0.0 { + -1.0 + } else { + 1.0 + }; + (t, n.cross(t) * sign) +} + +fn unit_or(v: Vec3, d: Vec3) -> Vec3 { + v.try_normalize().filter(|n| n.is_finite()).unwrap_or(d) +} + +fn normal_map(ctx: &HitContext, c: V4, strength: f32, flip_y: bool) -> V4 { + let n = ctx.ns; + let (t, b) = tangent_frame(ctx, n); + let mut x = (2.0 * c[0] - 1.0) * strength; + let mut y = (2.0 * c[1] - 1.0) * strength; + let z = 2.0 * c[2] - 1.0; + if flip_y { + y = -y; + } + if !x.is_finite() || !y.is_finite() { + x = 0.0; + y = 0.0; + } + v4(unit_or(t * x + b * y + n * z.max(0.0), n), 0.0) +} + +fn bump(ctx: &HitContext, base: V4, h: V4) -> V4 { + let n = unit_or(v3(base), ctx.ns); + let (du, dv) = bump_step(ctx); + let dhdu = if du > 0.0 { (h[1] - h[0]) / du } else { 0.0 }; + let dhdv = if dv > 0.0 { (h[2] - h[0]) / dv } else { 0.0 }; + let r1 = ctx.dpdv.cross(n); + let r2 = n.cross(ctx.dpdu); + let det = ctx.dpdu.dot(r1); + let grad = (r1 * dhdu + r2 * dhdv) * if det < 0.0 { -1.0 } else { 1.0 }; + v4(unit_or(n * det.abs() - grad, n), 0.0) +} + +fn tex_box(ctx: &HitContext, i: &Instr, a: V4, k: &[f32], tex: &dyn TextureSampler) -> V4 { + let fallback = [k[0], k[1], k[2], k[3]]; + let (sx, sy, c, s, ox, oy, blend) = (k[4], k[5], k[6], k[7], k[8], k[9], k[10]); + let n = if i.flags & 16 != 0 { ctx.ns } else { ctx.n_object }; + let raw = [n.x.abs(), n.y.abs(), n.z.abs()].map(|v| (v - blend.clamp(0.0, 1.0) * 0.5).max(0.0).powi(4)); + let sum: f32 = raw.iter().sum(); + let w = if sum > 0.0 && sum.is_finite() { + raw.map(|v| v / sum) + } else { + let mut d = [0.0; 3]; + d[Vec3::new(n.x.abs(), n.y.abs(), n.z.abs()).max_dimension()] = 1.0; + d + }; + let planes = [[a[2], a[1]], [a[0], a[2]], [a[0], a[1]]]; + let wrap = Wrap::from_code(i.flags); + let filter = Filter::from_code(i.flags >> 2); + let mut out = [0.0; 4]; + for axis in 0..3 { + if w[axis] <= 0.0 { + continue; + } + let uv = xform2([planes[axis][0], planes[axis][1], a[3], 0.0], &[sx, sy, c, s, ox, oy]); + let v = tex.sample(i.b, Vec2::new(uv[0], uv[1]), uv[2], wrap, filter, fallback); + out = zip(out, v, |o, x| o + x * w[axis]); + } + out +} + +fn set_field(m: &mut SurfaceInputs, f: Field, v: V4) { + let c = Rgb::new(v[0], v[1], v[2]); + match f { + Field::BaseWeight => m.base_weight = v[0], + Field::BaseColor => m.base_color = c, + Field::BaseMetalness => m.base_metalness = v[0], + Field::BaseDiffuseRoughness => m.base_diffuse_roughness = v[0], + Field::SpecularWeight => m.specular_weight = v[0], + Field::SpecularColor => m.specular_color = c, + Field::SpecularRoughness => m.specular_roughness = v[0], + Field::SpecularIor => m.specular_ior = v[0], + Field::SpecularAnisotropy => m.specular_anisotropy = v[0], + Field::TransmissionWeight => m.transmission_weight = v[0], + Field::TransmissionColor => m.transmission_color = c, + Field::CoatWeight => m.coat_weight = v[0], + Field::CoatColor => m.coat_color = c, + Field::CoatRoughness => m.coat_roughness = v[0], + Field::CoatIor => m.coat_ior = v[0], + Field::FuzzWeight => m.fuzz_weight = v[0], + Field::FuzzColor => m.fuzz_color = c, + Field::FuzzRoughness => m.fuzz_roughness = v[0], + Field::Emission => m.emission = c, + Field::Opacity => m.opacity = v[0], + Field::Normal | Field::Displacement => {} + } +} + +impl Program { + /// Runs the program at one hit. A constant program returns `base` and the incoming normal without running. + pub fn evaluate(&self, ctx: &HitContext, tex: &dyn TextureSampler) -> Shaded { + let mut out = Shaded { inputs: self.base, normal: ctx.ns, normal_changed: false, displacement: 0.0 }; + if self.is_constant() { + return out; + } + let mut r = [[0.0f32; 4]; REGISTERS]; + let reg = |r: &[V4; REGISTERS], n: u32| r.get(n as usize).copied().unwrap_or([0.0; 4]); + for i in &self.code { + let (a, b, c) = (reg(&r, i.a), reg(&r, i.b), reg(&r, i.c)); + let v = match i.op { + Op::Input => read_input(ctx, i.flags & 15, i.flags >> 4, i.a), + Op::Tex => { + let k = konst(&self.consts, i.c, 4); + let fallback = [0, 1, 2, 3].map(|n| k.get(n).copied().unwrap_or(0.0)); + let wrap = Wrap::from_code(i.flags); + let filter = Filter::from_code(i.flags >> 2); + tex.sample(i.b, Vec2::new(a[0], a[1]), a[2], wrap, filter, fallback) + } + Op::TexBox => { + let k = konst(&self.consts, i.c, 11); + if k.len() < 11 { + [0.0; 4] + } else { + tex_box(ctx, i, a, k, tex) + } + } + Op::NormalMap => normal_map(ctx, a, b[0], i.flags & 1 != 0), + Op::Bump => bump(ctx, a, b), + Op::Proc => { + let n = self.consts.get(i.a as usize).copied().unwrap_or(0.0).max(0.0) as usize; + let regs = konst(&self.consts, i.a + 1, n.min(16)); + let mut args = [[0.0f32; 4]; 16]; + for (slot, rn) in args.iter_mut().zip(regs) { + *slot = reg(&r, *rn as u32); + } + match ProcKind::from_u8(i.flags) { + Some(kind) => procedural(kind, i.b, &args[..regs.len()]), + None => [0.0; 4], + } + } + _ => fold(i, a, b, c, &self.consts).unwrap_or([0.0; 4]), + }; + if let Some(d) = r.get_mut(i.dst as usize) { + *d = v; + } + } + for o in &self.outputs { + let v = reg(&r, o.reg as u32); + match o.field { + Field::Normal => { + if let Some(n) = v3(v).try_normalize().filter(|n| n.is_finite()) { + out.normal = n; + out.normal_changed = true; + } + } + Field::Displacement => out.displacement = if v[0].is_finite() { v[0] } else { 0.0 }, + f => set_field(&mut out.inputs, f, v), + } + } + out.inputs = out.inputs.sanitized(); + out + } +} diff --git a/native/crates/fsh-materials/src/lib.rs b/native/crates/fsh-materials/src/lib.rs index 77496253..62636644 100644 --- a/native/crates/fsh-materials/src/lib.rs +++ b/native/crates/fsh-materials/src/lib.rs @@ -1,12 +1,28 @@ //! FormShot surface shading: one layered physically based surface (fuzz over coat over a base mixing metal, dielectric specular, transmission and diffuse), with GGX, energy compensation and lobe selection. mod bsdf; +mod film; mod fresnel; mod ggx; mod inputs; +mod interp; mod lobes; +mod optics; +mod procedural; +pub mod program; +mod sample; mod tables; +mod texture; pub use bsdf::{Bsdf, BsdfSample, LobeFlags, ShadingFrame}; pub use inputs::SurfaceInputs; +pub use optics::{ + dispersion_channel, thin_film_conductor, thin_film_dielectric, Optics, ABBE_SPAN, CHANNEL_DISPERSION, + CHANNEL_WAVELENGTHS, +}; +pub use interp::{fold, HitContext, Shaded}; +pub use procedural::{procedural, ProcKind, ProcOutput}; +pub use sample::wrap_index; +pub use texture::{srgb8_table, ColourSpace, NoTextures, TextureImage, TextureLevel, TextureSampler, TextureSet, Texels}; +pub use program::{DecodeError, Field, Filter, Instr, Op, Output, Program, Wrap, MAX_UV_SETS, REGISTERS}; pub use tables::{energy_tables, warm_up, EnergyTables}; diff --git a/native/crates/fsh-materials/src/optics.rs b/native/crates/fsh-materials/src/optics.rs new file mode 100644 index 00000000..4e3f938b --- /dev/null +++ b/native/crates/fsh-materials/src/optics.rs @@ -0,0 +1,83 @@ +use fsh_core::Rgb; + +use crate::film::{film_conductor, film_dielectric}; + +/// Fraunhofer F (486.1327 nm) and C (656.2725 nm) lines: `1/lambda_F^2 - 1/lambda_C^2` in inverse square micrometres. +pub const ABBE_SPAN: f32 = 1.909_624_6; + +/// Representative wavelengths of the ACEScg R, G and B channels in micrometres: for each channel the wavelength whose +/// Cauchy ior is the channel-sensitivity-weighted mean ior, `(integral r_c lambda^-2 / integral r_c)^-1/2` over the +/// positive part of the channel's colour-matching function (CIE 1931, ACES white). +pub const CHANNEL_WAVELENGTHS: [f32; 3] = [0.5882, 0.5422, 0.4526]; + +/// `1/lambda_c^2 - 1/lambda_d^2` for each channel, lambda_d = 587.5618 nm (the d line), inverse square micrometres. +pub const CHANNEL_DISPERSION: [f32; 3] = [-6.282_304_6e-3, 5.049_531e-1, 1.985_068_8]; + +/// Wavelength-dependent optics of a surface beyond `SurfaceInputs`: thin-film iridescence and dispersion (OpenPBR 1.1). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Optics { + /// Thin-film coverage, 0..1; 0 is no film. + pub film_weight: f32, + /// Film thickness in micrometres. + pub film_thickness: f32, + /// Film index of refraction. + pub film_ior: f32, + /// Cauchy slope per unit of `(ior_d - 1)`: `B = (ior_d - 1) * dispersion`, square micrometres; 0 is no dispersion. + pub dispersion: f32, +} + +fn finite_or(v: f32, d: f32) -> f32 { + if v.is_finite() { + v + } else { + d + } +} + +impl Optics { + /// No film and no dispersion. + pub const NONE: Self = Self { film_weight: 0.0, film_thickness: 0.0, film_ior: 1.0, dispersion: 0.0 }; + + /// From the OpenPBR parameters (thickness in micrometres), sanitized; a scale or Abbe number of 0 turns dispersion off. + pub fn new(film_weight: f32, film_thickness: f32, film_ior: f32, dispersion_scale: f32, abbe: f32) -> Self { + let weight = finite_or(film_weight, 0.0).clamp(0.0, 1.0); + let thickness = finite_or(film_thickness, 0.5).clamp(0.0, 10.0); + let ior = finite_or(film_ior, 1.4).clamp(1.0, 4.0); + let scale = finite_or(dispersion_scale, 0.0).clamp(0.0, 1.0); + let abbe = finite_or(abbe, 0.0); + let dispersion = if scale > 0.0 && abbe > 0.0 { scale / (abbe * ABBE_SPAN) } else { 0.0 }; + Self { film_weight: weight, film_thickness: thickness, film_ior: ior, dispersion } + } + + /// True when a film is present. + pub fn has_film(&self) -> bool { + self.film_weight > 0.0 + } + + /// True when the ior varies with wavelength. + pub fn is_dispersive(&self) -> bool { + self.dispersion > 0.0 + } + + /// Ior at channel `c`'s representative wavelength from the ior at the d line (Cauchy two-term fit). + pub fn channel_ior(&self, ior_d: f32, c: usize) -> f32 { + ior_d + (ior_d - 1.0) * self.dispersion * CHANNEL_DISPERSION[c.min(2)] + } +} + +/// Channel picked by a uniform number in [0, 1): 0, 1 or 2, each with probability one third. +pub fn dispersion_channel(u: f32) -> usize { + let c = (u * 3.0) as usize; + c.min(2) +} + +/// Reflectance in ACEScg of a film (`film_ior`, `thickness` micrometres) over a dielectric (`base_ior`), both iors +/// relative to the medium above, at incidence cosine `cos`: Belcour and Barla's Airy summation, no blending by weight. +pub fn thin_film_dielectric(cos: f32, film_ior: f32, thickness: f32, base_ior: f32) -> Rgb { + film_dielectric(cos, film_ior, base_ior, thickness) +} + +/// As `thin_film_dielectric` over a conductor of complex ior `n + i k` per channel. +pub fn thin_film_conductor(cos: f32, film_ior: f32, thickness: f32, n: Rgb, k: Rgb) -> Rgb { + film_conductor(cos, film_ior, n, k, thickness) +} diff --git a/native/crates/fsh-materials/src/procedural.rs b/native/crates/fsh-materials/src/procedural.rs new file mode 100644 index 00000000..86a4a72e --- /dev/null +++ b/native/crates/fsh-materials/src/procedural.rs @@ -0,0 +1,110 @@ +mod cells; +mod common; +mod noise; +mod patterns; + +/// Procedural pattern kinds; the numbers are the `Op::Proc` flags. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(u8)] +pub enum ProcKind { + /// Gradient noise. + Noise = 0, + /// Fractal sum of noise octaves. + Fbm = 1, + /// Cellular (Worley) pattern. + Voronoi = 2, + /// Three-dimensional checker. + Checker = 3, + /// Gradient along an axis or radius. + Gradient = 4, + /// Bands or rings. + Wave = 5, + /// Brushed-metal streaks (a height). + Brushed = 6, + /// Metallic flakes (a normal and a mask). + Flakes = 7, + /// Wood rings. + Wood = 8, + /// Marble veins. + Marble = 9, +} + +/// What one procedural output carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ProcOutput { + /// A scalar in x. + Value, + /// A colour in xyz, alpha 1 in w. + Colour, + /// A vector in xyz. + Vector, + /// A world normal in xyz; zero means "leave the normal". + Normal, +} + +impl ProcKind { + /// Every kind in flag order. + pub const ALL: [ProcKind; 10] = [ + ProcKind::Noise, + ProcKind::Fbm, + ProcKind::Voronoi, + ProcKind::Checker, + ProcKind::Gradient, + ProcKind::Wave, + ProcKind::Brushed, + ProcKind::Flakes, + ProcKind::Wood, + ProcKind::Marble, + ]; + + /// Kind from its flag value. + pub fn from_u8(v: u8) -> Option<ProcKind> { + Self::ALL.get(v as usize).copied() + } + + /// Graph node id of the kind. + pub fn id(self) -> &'static str { + match self { + ProcKind::Noise => "noise", + ProcKind::Fbm => "fbm", + ProcKind::Voronoi => "voronoi", + ProcKind::Checker => "checker", + ProcKind::Gradient => "gradient", + ProcKind::Wave => "wave", + ProcKind::Brushed => "brushed", + ProcKind::Flakes => "flakes", + ProcKind::Wood => "wood", + ProcKind::Marble => "marble", + } + } + + /// Outputs in index order (the `output` argument of `procedural`). + pub fn outputs(self) -> &'static [ProcOutput] { + use ProcOutput::*; + match self { + ProcKind::Noise | ProcKind::Fbm | ProcKind::Gradient | ProcKind::Wave => &[Value, Colour], + ProcKind::Voronoi => &[Value, Colour, Vector], + ProcKind::Checker | ProcKind::Wood | ProcKind::Marble => &[Colour, Value], + ProcKind::Brushed => &[Value], + ProcKind::Flakes => &[Normal, Value, Colour], + } + } +} + +/// Evaluates output `output` of a procedural. `args[0]` is the coordinate (xyz, footprint in w), then the kind's +/// inputs in catalogue order (floats in x, colours in xyz), then the settings vector (seed, mode 1, mode 2, 0). +pub fn procedural(kind: ProcKind, output: u32, args: &[[f32; 4]]) -> [f32; 4] { + let at = |i: usize| args.get(i).copied().unwrap_or([0.0; 4]); + match kind { + ProcKind::Noise => noise::noise(output, at), + ProcKind::Fbm => noise::fbm(output, at), + ProcKind::Voronoi => cells::voronoi(output, at), + ProcKind::Checker => patterns::checker(output, at), + ProcKind::Gradient => patterns::gradient(output, at), + ProcKind::Wave => patterns::wave(output, at), + ProcKind::Brushed => patterns::brushed(at), + ProcKind::Flakes => cells::flakes(output, at), + ProcKind::Wood => patterns::wood(output, at), + ProcKind::Marble => patterns::marble(output, at), + } +} diff --git a/native/crates/fsh-materials/src/procedural/cells.rs b/native/crates/fsh-materials/src/procedural/cells.rs new file mode 100644 index 00000000..46f3f0ff --- /dev/null +++ b/native/crates/fsh-materials/src/procedural/cells.rs @@ -0,0 +1,121 @@ +use super::common::{aa, footprint, hash, lerp, mode, num, pcg3d, position, seed_of, splat, unit, V4}; +use std::f32::consts::TAU; + +const FAR: f32 = 1.0e30; + +const MEAN: [[[f32; 3]; 3]; 2] = [ + [[0.4801, 0.7027, 0.2227], [0.7498, 1.0003, 0.2498], [0.3749, 0.6250, 0.2501]], + [[0.5205, 0.7171, 0.1963], [0.7659, 1.0520, 0.2866], [0.4205, 0.5793, 0.1585]], +]; + +pub(super) struct Nearest { + pub f1: f32, + pub f2: f32, + pub cell: [i32; 3], + pub point: [f32; 3], + pub hash: [u32; 3], +} + +fn distance(d: [f32; 3], metric: u32) -> f32 { + let (x, y, z) = (d[0].abs(), d[1].abs(), d[2].abs()); + match metric { + 1 => x + y + z, + 2 => x.max(y).max(z), + _ => (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(), + } +} + +pub(super) fn nearest(p: [f32; 3], seed: u32, randomness: f32, metric: u32) -> Nearest { + let fl = [p[0].floor(), p[1].floor(), p[2].floor()]; + let i = [fl[0] as i32, fl[1] as i32, fl[2] as i32]; + let f = [p[0] - fl[0], p[1] - fl[1], p[2] - fl[2]]; + let mut best = Nearest { f1: FAR, f2: FAR, cell: i, point: [0.5; 3], hash: [0; 3] }; + for dz in -1i32..=1 { + for dy in -1i32..=1 { + for dx in -1i32..=1 { + let c = [i[0].wrapping_add(dx), i[1].wrapping_add(dy), i[2].wrapping_add(dz)]; + let h = hash(c, seed); + let pt = [ + dx as f32 + 0.5 + randomness * (unit(h[0]) - 0.5), + dy as f32 + 0.5 + randomness * (unit(h[1]) - 0.5), + dz as f32 + 0.5 + randomness * (unit(h[2]) - 0.5), + ]; + let d = distance([pt[0] - f[0], pt[1] - f[1], pt[2] - f[2]], metric); + if d < best.f1 { + best.f2 = best.f1; + best.f1 = d; + best.cell = c; + best.point = pt; + best.hash = h; + } else if d < best.f2 { + best.f2 = d; + } + } + } + } + best.point = [fl[0] + best.point[0], fl[1] + best.point[1], fl[2] + best.point[2]]; + best +} + +pub(super) fn flakes(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let scale = num(at(1)[0]); + let density = num(at(2)[0]).clamp(0.0, 1.0); + let spread = num(at(3)[0]).clamp(0.0, 1.0); + let seed = seed_of(at(4)[0]); + let t = aa(footprint(v) * scale.abs()); + let n = nearest(position(v, scale), seed, 1.0, 0); + let h = pcg3d(n.hash); + let on = unit(h[0]) < density; + let mask = lerp(density, if on { 1.0 } else { 0.0 }, t); + let tilt = if on { + let cos_t = 1.0 - unit(h[1]) * spread; + let sin_t = (1.0 - cos_t * cos_t).max(0.0).sqrt(); + let phi = TAU * unit(h[2]); + [sin_t * phi.cos(), sin_t * phi.sin(), cos_t] + } else { + [0.0, 0.0, 1.0] + }; + let m = [tilt[0] * t, tilt[1] * t, lerp(1.0, tilt[2], t)]; + let len = (m[0] * m[0] + m[1] * m[1] + m[2] * m[2]).sqrt(); + let m = if len > 0.0 { [m[0] / len, m[1] / len, m[2] / len] } else { [0.0, 0.0, 1.0] }; + match output { + 1 => splat(mask), + 2 => [0.5 + 0.5 * m[0], 0.5 + 0.5 * m[1], 0.5 + 0.5 * m[2], 1.0], + _ => [m[0], m[1], m[2], 0.0], + } +} + +pub(super) fn voronoi(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let scale = num(at(1)[0]); + let randomness = num(at(2)[0]).clamp(0.0, 1.0); + let settings = at(3); + let seed = seed_of(settings[0]); + let metric = mode(settings[1], 2); + let feature = mode(settings[2], 2); + let t = aa(footprint(v) * scale.abs()); + let n = nearest(position(v, scale), seed, randomness, metric); + match output { + 1 => { + let h = pcg3d(n.hash); + [lerp(0.5, unit(h[0]), t), lerp(0.5, unit(h[1]), t), lerp(0.5, unit(h[2]), t), 1.0] + } + 2 => { + if scale == 0.0 { + return v; + } + let w = [n.point[0] / scale, n.point[1] / scale, n.point[2] / scale]; + [lerp(v[0], w[0], t), lerp(v[1], w[1], t), lerp(v[2], w[2], t), v[3]] + } + _ => { + let d = match feature { + 1 => n.f2, + 2 => n.f2 - n.f1, + _ => n.f1, + }; + let mean = lerp(MEAN[0][metric as usize][feature as usize], MEAN[1][metric as usize][feature as usize], randomness); + splat(lerp(mean, d, t)) + } + } +} diff --git a/native/crates/fsh-materials/src/procedural/common.rs b/native/crates/fsh-materials/src/procedural/common.rs new file mode 100644 index 00000000..25d2d976 --- /dev/null +++ b/native/crates/fsh-materials/src/procedural/common.rs @@ -0,0 +1,104 @@ +pub(super) type V4 = [f32; 4]; + +const SEED_MIX: [u32; 3] = [0x9E37_79B9, 0x85EB_CA6B, 0xC2B2_AE35]; +const OCTAVE_MIX: u32 = 0x632B_E5AB; +const CHANNEL_MIX: u32 = 0x2545_F491; +const COORD_LIMIT: f32 = 1.0e9; +const SEED_LIMIT: f32 = 4_294_967_040.0; + +pub(super) fn pcg3d(v: [u32; 3]) -> [u32; 3] { + let mut x = v[0].wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let mut y = v[1].wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let mut z = v[2].wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + x = x.wrapping_add(y.wrapping_mul(z)); + y = y.wrapping_add(z.wrapping_mul(x)); + z = z.wrapping_add(x.wrapping_mul(y)); + x ^= x >> 16; + y ^= y >> 16; + z ^= z >> 16; + x = x.wrapping_add(y.wrapping_mul(z)); + y = y.wrapping_add(z.wrapping_mul(x)); + z = z.wrapping_add(x.wrapping_mul(y)); + [x, y, z] +} + +pub(super) fn hash(c: [i32; 3], seed: u32) -> [u32; 3] { + pcg3d([ + (c[0] as u32).wrapping_add(seed.wrapping_mul(SEED_MIX[0])), + (c[1] as u32).wrapping_add(seed.wrapping_mul(SEED_MIX[1])), + (c[2] as u32).wrapping_add(seed.wrapping_mul(SEED_MIX[2])), + ]) +} + +pub(super) fn unit(h: u32) -> f32 { + (h >> 8) as f32 * (1.0 / 16_777_216.0) +} + +pub(super) fn octave_seed(seed: u32, i: u32) -> u32 { + seed.wrapping_add(i.wrapping_mul(OCTAVE_MIX)) +} + +pub(super) fn channel_seed(seed: u32, c: u32) -> u32 { + seed.wrapping_add(c.wrapping_mul(CHANNEL_MIX)) +} + +pub(super) fn seed_of(v: f32) -> u32 { + if v.is_finite() && v > 0.0 { + v.min(SEED_LIMIT) as u32 + } else { + 0 + } +} + +pub(super) fn coord(v: f32) -> f32 { + if v.is_finite() { + v.clamp(-COORD_LIMIT, COORD_LIMIT) + } else { + 0.0 + } +} + +pub(super) fn num(v: f32) -> f32 { + if v.is_finite() { + v + } else { + 0.0 + } +} + +pub(super) fn mode(v: f32, max: u32) -> u32 { + (num(v).clamp(0.0, 255.0) as u32).min(max) +} + +pub(super) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +pub(super) fn aa(r: f32) -> f32 { + 1.0 - smoothstep(0.5, 1.0, r) +} + +pub(super) fn lerp(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +pub(super) fn splat(v: f32) -> V4 { + [v, v, v, v] +} + +pub(super) fn mix3(a: V4, b: V4, t: f32) -> V4 { + [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t), 1.0] +} + +pub(super) fn footprint(v: V4) -> f32 { + if v[3].is_finite() && v[3] > 0.0 { + v[3] + } else { + 0.0 + } +} + +pub(super) fn position(v: V4, scale: f32) -> [f32; 3] { + [coord(v[0] * scale), coord(v[1] * scale), coord(v[2] * scale)] +} diff --git a/native/crates/fsh-materials/src/procedural/noise.rs b/native/crates/fsh-materials/src/procedural/noise.rs new file mode 100644 index 00000000..6297a6b6 --- /dev/null +++ b/native/crates/fsh-materials/src/procedural/noise.rs @@ -0,0 +1,114 @@ +use super::common::{aa, channel_seed, footprint, hash, lerp, num, octave_seed, position, seed_of, splat, V4}; + +pub(super) const TURBULENCE_MEAN: f32 = 0.2199; + +fn fade(t: f32) -> f32 { + t * t * t * (t * (t * 6.0 - 15.0) + 10.0) +} + +fn grad(h: u32, x: f32, y: f32, z: f32) -> f32 { + let h = h & 15; + let u = if h < 8 { x } else { y }; + let v = if h < 4 { + y + } else if h == 12 || h == 14 { + x + } else { + z + }; + let a = if h & 1 == 0 { u } else { -u }; + let b = if h & 2 == 0 { v } else { -v }; + a + b +} + +pub(super) fn perlin(p: [f32; 3], seed: u32) -> f32 { + let fl = [p[0].floor(), p[1].floor(), p[2].floor()]; + let i = [fl[0] as i32, fl[1] as i32, fl[2] as i32]; + let (x, y, z) = (p[0] - fl[0], p[1] - fl[1], p[2] - fl[2]); + let (u, v, w) = (fade(x), fade(y), fade(z)); + let g = |dx: i32, dy: i32, dz: i32| { + let h = hash([i[0].wrapping_add(dx), i[1].wrapping_add(dy), i[2].wrapping_add(dz)], seed)[0]; + grad(h, x - dx as f32, y - dy as f32, z - dz as f32) + }; + let x00 = lerp(g(0, 0, 0), g(1, 0, 0), u); + let x10 = lerp(g(0, 1, 0), g(1, 1, 0), u); + let x01 = lerp(g(0, 0, 1), g(1, 0, 1), u); + let x11 = lerp(g(0, 1, 1), g(1, 1, 1), u); + lerp(lerp(x00, x10, v), lerp(x01, x11, v), w) +} + +pub(super) struct Fractal { + pub octaves: f32, + pub lacunarity: f32, + pub gain: f32, +} + +pub(super) fn fractal(p: [f32; 3], seed: u32, f: &Fractal, fw: f32, turbulent: bool) -> f32 { + let n = if f.octaves.is_finite() { f.octaves.clamp(1.0, 16.0) } else { 1.0 }; + let whole = n.floor(); + let part = n - whole; + let count = whole as u32 + u32::from(part > 0.0); + let lac = if f.lacunarity.is_finite() { f.lacunarity.clamp(0.0, 16.0) } else { 2.0 }; + let gain = if f.gain.is_finite() { f.gain.clamp(0.0, 4.0) } else { 0.5 }; + let mut sum = 0.0; + let mut norm = 0.0; + let mut amp = 1.0; + let mut freq = 1.0; + for i in 0..count { + let weight = if i as f32 >= whole { amp * part } else { amp }; + let q = [p[0] * freq, p[1] * freq, p[2] * freq]; + let mut v = perlin(q, octave_seed(seed, i)); + if turbulent { + v = v.abs() - TURBULENCE_MEAN; + } + sum += weight * aa(fw * freq) * v; + norm += weight; + amp *= gain; + freq *= lac; + } + if norm > 0.0 { + sum / norm + } else { + 0.0 + } +} + +fn unit_value(n: f32) -> f32 { + (0.5 + 0.5 * n).clamp(0.0, 1.0) +} + +fn channels(output: u32, seed: u32, eval: impl Fn(u32) -> f32) -> V4 { + if output == 1 { + let c = [0, 1, 2].map(|k| unit_value(eval(channel_seed(seed, k)))); + [c[0], c[1], c[2], 1.0] + } else { + splat(unit_value(eval(seed))) + } +} + +pub(super) fn noise(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let scale = num(at(1)[0]); + let detail = num(at(2)[0]).clamp(0.0, 15.0); + let roughness = num(at(3)[0]); + let distortion = num(at(4)[0]); + let seed = seed_of(at(5)[0]); + let fw = footprint(v) * scale.abs(); + let mut p = position(v, scale); + if distortion != 0.0 { + let d = [1u32, 2, 3].map(|k| distortion * aa(fw) * perlin(p, channel_seed(seed, k + 16))); + p = [p[0] + d[0], p[1] + d[1], p[2] + d[2]]; + } + let f = Fractal { octaves: detail + 1.0, lacunarity: 2.0, gain: roughness }; + channels(output, seed, |s| fractal(p, s, &f, fw, false)) +} + +pub(super) fn fbm(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let scale = num(at(1)[0]); + let f = Fractal { octaves: num(at(2)[0]), lacunarity: num(at(3)[0]), gain: num(at(4)[0]) }; + let seed = seed_of(at(5)[0]); + let fw = footprint(v) * scale.abs(); + let p = position(v, scale); + channels(output, seed, |s| fractal(p, s, &f, fw, false)) +} diff --git a/native/crates/fsh-materials/src/procedural/patterns.rs b/native/crates/fsh-materials/src/procedural/patterns.rs new file mode 100644 index 00000000..79ddadce --- /dev/null +++ b/native/crates/fsh-materials/src/procedural/patterns.rs @@ -0,0 +1,162 @@ +use super::common::{aa, coord, footprint, lerp, mix3, mode, num, octave_seed, position, seed_of, splat, V4}; +use super::noise::{fractal, perlin, Fractal, TURBULENCE_MEAN}; +use std::f32::consts::{PI, TAU}; + +const CHECKER_OFFSET: f32 = 1.0e-4; + +pub(super) fn checker(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let scale = num(at(1)[0]); + let p = position(v, scale); + let i = p.map(|x| (x + CHECKER_OFFSET).floor() as i32); + let parity = i[0].wrapping_add(i[1]).wrapping_add(i[2]) & 1; + let pick = if parity == 0 { 1.0 } else { 0.0 }; + let fac = lerp(0.5, pick, aa(footprint(v) * scale.abs())); + if output == 1 { + splat(fac) + } else { + mix3(at(3), at(2), fac) + } +} + +fn grey(output: u32, value: f32, colour_output: u32) -> V4 { + if output == colour_output { + [value, value, value, 1.0] + } else { + splat(value) + } +} + +pub(super) fn wave(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let scale = num(at(1)[0]); + let distortion = num(at(2)[0]); + let detail = num(at(3)[0]).clamp(0.0, 15.0); + let phase = num(at(4)[0]); + let settings = at(5); + let seed = seed_of(settings[0]); + let rings = mode(settings[1], 1) == 1; + let profile = mode(settings[2], 2); + let fw = footprint(v) * scale.abs(); + let p = position(v, scale); + let mut s = if rings { (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt() } else { p[0] }; + if distortion != 0.0 { + let f = Fractal { octaves: detail + 1.0, lacunarity: 2.0, gain: 0.5 }; + s += distortion * fractal(p, seed, &f, fw, false); + } + s += phase; + let fr = s - s.floor(); + let y = match profile { + 1 => fr, + 2 => 1.0 - (2.0 * fr - 1.0).abs(), + _ => 0.5 - 0.5 * (TAU * fr).cos(), + }; + grey(output, lerp(0.5, y, aa(fw * (1.0 + distortion.abs()))), 1) +} + +const FINE_ACROSS: f32 = 3.1; +const FINE_ALONG: f32 = 0.6; + +pub(super) fn brushed(at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let lines = num(at(1)[0]).abs(); + let length = num(at(2)[0]).abs().max(1.0e-6); + let strength = num(at(3)[0]); + let seed = seed_of(at(4)[0]); + let w = footprint(v); + let (x, y, z) = (coord(v[0]), coord(v[1]), coord(v[2])); + let qa = [coord(x / length), coord(y * lines), coord(z * lines)]; + let a = perlin(qa, seed) * aa((w * lines).max(w / length)); + let fine = lines * FINE_ACROSS; + let short = length * FINE_ALONG; + let qb = [coord(x / short), coord(y * fine), coord(z * fine)]; + let b = perlin(qb, octave_seed(seed, 1)) * aa((w * fine).max(w / short)); + splat((0.5 + strength * (0.6 * a + 0.4 * b)).clamp(0.0, 1.0)) +} + +const GRAIN_ACROSS: f32 = 6.0; +const GRAIN_ALONG: f32 = 0.1875; +const WOBBLE_ACROSS: f32 = 0.1; +const WOBBLE_ALONG: f32 = 0.0125; +const RING_MEAN: f32 = 0.25; + +pub(super) fn wood(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let scale = num(at(1)[0]); + let rings = num(at(2)[0]).abs(); + let distortion = num(at(3)[0]); + let seed = seed_of(at(6)[0]); + let fw = footprint(v) * scale.abs(); + let p = position(v, scale); + let f = Fractal { octaves: 2.0, lacunarity: 2.0, gain: 0.5 }; + let (wa, wl) = (rings * WOBBLE_ACROSS, rings * WOBBLE_ALONG); + let wobble = fractal([coord(p[0] * wa), coord(p[1] * wl), coord(p[2] * wa)], seed, &f, fw * wa, false); + let r = (p[0] * p[0] + p[2] * p[2]).sqrt(); + let t = r * rings + distortion * 2.0 * wobble; + let s = t - t.floor(); + let ring = lerp(RING_MEAN, s * s * s, aa(fw * rings * (1.0 + 0.3 * distortion.abs()))); + let (ga, gl) = (rings * GRAIN_ACROSS, rings * GRAIN_ALONG); + let q = [coord(p[0] * ga), coord(p[1] * gl), coord(p[2] * ga)]; + let grain = perlin(q, octave_seed(seed, 7)) * aa(fw * ga); + let value = (0.85 * ring + 0.15 * (0.5 + grain)).clamp(0.0, 1.0); + if output == 1 { + splat(value) + } else { + mix3(at(4), at(5), value) + } +} + +const TURBULENCE_FREQUENCY: f32 = 3.0; +const VEIN_MEAN: f32 = 0.1309; + +pub(super) fn marble(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let scale = num(at(1)[0]); + let veins = num(at(2)[0]); + let distortion = num(at(3)[0]); + let seed = seed_of(at(6)[0]); + let fw = footprint(v) * scale.abs(); + let p = position(v, scale); + let f = Fractal { octaves: 5.0, lacunarity: 2.0, gain: 0.5 }; + let q = p.map(|x| coord(x * TURBULENCE_FREQUENCY)); + let turbulence = TURBULENCE_MEAN + fractal(q, seed, &f, fw * TURBULENCE_FREQUENCY, true); + let phase = veins * p[0] + distortion * 2.0 * turbulence; + let fr = phase - phase.floor(); + let u = 1.0 - (PI * fr).sin(); + let u2 = u * u; + let vein = u2 * u2; + let value = lerp(VEIN_MEAN, vein, aa(fw * veins.abs() * (1.0 + distortion.abs()))); + if output == 1 { + splat(value) + } else { + mix3(at(4), at(5), value) + } +} + +pub(super) fn gradient(output: u32, at: impl Fn(usize) -> V4) -> V4 { + let v = at(0); + let p = position(v, 1.0); + let w = footprint(v); + let value = match mode(at(1)[1], 3) { + 1 => { + let x = p[0].clamp(0.0, 1.0); + x * x + } + 2 => { + let r = (p[0] * p[0] + p[1] * p[1]).sqrt(); + if r > 0.0 { + let angle = p[1].atan2(p[0]) / TAU + 0.5; + lerp(0.5, angle, aa(w / (TAU * r))) + } else { + 0.5 + } + } + 3 => (1.0 - (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt()).max(0.0), + _ => p[0].clamp(0.0, 1.0), + }; + if output == 1 { + [value, value, value, 1.0] + } else { + splat(value) + } +} diff --git a/native/crates/fsh-materials/src/program.rs b/native/crates/fsh-materials/src/program.rs new file mode 100644 index 00000000..36250138 --- /dev/null +++ b/native/crates/fsh-materials/src/program.rs @@ -0,0 +1,564 @@ +use crate::inputs::SurfaceInputs; +use core::fmt::Write as _; + +/// Number of vec4 registers a program may use. +pub const REGISTERS: usize = 32; +/// First word of an encoded program ("PM"). +pub const PROGRAM_MAGIC: u32 = 0x4d50; +/// Encoding version. +pub const PROGRAM_VERSION: u32 = 1; +/// Words before the first instruction in an encoded program. +pub const PROGRAM_HEADER_WORDS: usize = 8; +/// Uv sets a hit can carry. +pub const MAX_UV_SETS: usize = 4; + +/// The program reads uv set 0 (set n is `NEED_UV0 << n`). +pub const NEED_UV0: u32 = 1 << 0; +/// The program reads a tangent frame. +pub const NEED_TANGENT: u32 = 1 << 4; +/// The program samples textures. +pub const NEED_TEXTURES: u32 = 1 << 5; +/// The program evaluates procedurals. +pub const NEED_PROCEDURAL: u32 = 1 << 6; +/// The program writes the shading normal. +pub const NEED_NORMAL: u32 = 1 << 7; +/// The program bumps (evaluates offset points). +pub const NEED_BUMP: u32 = 1 << 8; + +/// One instruction kind; the numbers are the binary encoding. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum Op { + /// Nothing. + Nop = 0, + /// `dst = consts[a..a+4]`. + Const = 1, + /// `dst` = shading-point input `flags & 15` at bump offset `flags >> 4`; `a` is the uv set. + Input = 2, + /// `dst.i = a[(flags >> 2i) & 3]`. + Swizzle = 3, + /// `dst = (a.x, b.x, c.x, 0)`. + Combine = 4, + /// `a + b`. + Add = 5, + /// `a - b`. + Sub = 6, + /// `a * b`. + Mul = 7, + /// `a / b`, 0 where b is 0. + Div = 8, + /// `min(a, b)`. + Min = 9, + /// `max(a, b)`. + Max = 10, + /// `max(a, 0)^b`, 0 when not finite. + Pow = 11, + /// `a + (b - a) * c.x`. + Lerp = 12, + /// `min(max(a, b), c)`. + Clamp = 13, + /// `1 - a`. + Invert = 14, + /// ACEScg luminance of `a.xyz`, splatted. + Luminance = 15, + /// Colour ramp at `a.x`, stops at `consts[b]`, interpolation `flags`. + Ramp = 16, + /// Uv transform of `a` by `consts[b..b+6]`. + Xform2 = 17, + /// Projection of position `a` (flags 0 planar, 1 cylindrical, 2 spherical). + Project = 18, + /// Texture `b` at uv `a`, fallback `consts[c..c+4]`, wrap and filter in `flags`. + Tex = 19, + /// Box-projected texture `b` at position `a`, fallback and transform at `consts[c..c+11]`. + TexBox = 20, + /// Tangent-space normal map: colour `a`, strength `b.x`, flags bit 0 flips y. + NormalMap = 21, + /// Normal `a` bent by heights `b = (h, h_u, h_v)`. + Bump = 22, + /// Procedural `flags`, output `b`, argument registers listed at `consts[a]`. + Proc = 23, + /// Label projection of position `a` with object normal `c`, frame at `consts[b..b+12]`; `(u, v, footprint, mask)`; + /// flags bit 0: one-sided. + Label = 24, +} + +/// `Label` flag: print only where the object normal faces the label's normal. +pub const LABEL_ONE_SIDED: u8 = 1; + +impl Op { + /// Every opcode in encoding order. + pub const ALL: [Op; 25] = [ + Op::Nop, + Op::Const, + Op::Input, + Op::Swizzle, + Op::Combine, + Op::Add, + Op::Sub, + Op::Mul, + Op::Div, + Op::Min, + Op::Max, + Op::Pow, + Op::Lerp, + Op::Clamp, + Op::Invert, + Op::Luminance, + Op::Ramp, + Op::Xform2, + Op::Project, + Op::Tex, + Op::TexBox, + Op::NormalMap, + Op::Bump, + Op::Proc, + Op::Label, + ]; + + /// Opcode from its number. + pub fn from_u8(v: u8) -> Option<Op> { + Self::ALL.get(v as usize).copied() + } + + /// Lower-case mnemonic. + pub fn name(self) -> &'static str { + match self { + Op::Nop => "nop", + Op::Const => "const", + Op::Input => "input", + Op::Swizzle => "swizzle", + Op::Combine => "combine", + Op::Add => "add", + Op::Sub => "sub", + Op::Mul => "mul", + Op::Div => "div", + Op::Min => "min", + Op::Max => "max", + Op::Pow => "pow", + Op::Lerp => "lerp", + Op::Clamp => "clamp", + Op::Invert => "invert", + Op::Luminance => "luminance", + Op::Ramp => "ramp", + Op::Xform2 => "xform2", + Op::Project => "project", + Op::Tex => "tex", + Op::TexBox => "texbox", + Op::NormalMap => "normalmap", + Op::Bump => "bump", + Op::Proc => "proc", + Op::Label => "label", + } + } +} + +/// Shading-point inputs read by `Op::Input` (`flags & 15`). +pub mod input { + /// World position, footprint in w. + pub const POSITION: u8 = 0; + /// Object position, footprint in w. + pub const POSITION_OBJECT: u8 = 1; + /// World shading normal. + pub const NORMAL: u8 = 2; + /// World geometric normal. + pub const GEOMETRIC_NORMAL: u8 = 3; + /// Object shading normal. + pub const NORMAL_OBJECT: u8 = 4; + /// Uv set `a` as (u, v, uv footprint, 0). + pub const UV: u8 = 5; + /// World tangent, sign in w. + pub const TANGENT: u8 = 6; + /// Footprint in x. + pub const FOOTPRINT: u8 = 7; + /// Bump offset along u (`flags` high nibble). + pub const OFFSET_U: u8 = 1; + /// Bump offset along v (`flags` high nibble). + pub const OFFSET_V: u8 = 2; +} + +/// Texture coordinate wrapping. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Wrap { + /// Tile. + #[default] + Repeat, + /// Clamp to the edge texel. + Clamp, + /// Tile, mirrored every other tile. + Mirror, +} + +/// Texture filtering. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Filter { + /// Nearest texel of level 0. + Nearest, + /// Bilinear on level 0. + Bilinear, + /// Bilinear on the two mip levels the footprint selects, blended. + #[default] + Trilinear, +} + +impl Wrap { + /// Two-bit code. + pub fn code(self) -> u8 { + self as u8 + } + + /// From the two-bit code. + pub fn from_code(v: u8) -> Wrap { + match v & 3 { + 1 => Wrap::Clamp, + 2 => Wrap::Mirror, + _ => Wrap::Repeat, + } + } +} + +impl Filter { + /// Two-bit code. + pub fn code(self) -> u8 { + self as u8 + } + + /// From the two-bit code. + pub fn from_code(v: u8) -> Filter { + match v & 3 { + 0 => Filter::Nearest, + 1 => Filter::Bilinear, + _ => Filter::Trilinear, + } + } +} + +/// A surface input a program writes; the numbers are the binary encoding. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(u8)] +pub enum Field { + /// `base_weight`. + BaseWeight = 0, + /// `base_color`. + BaseColor = 1, + /// `base_metalness`. + BaseMetalness = 2, + /// `base_diffuse_roughness`. + BaseDiffuseRoughness = 3, + /// `specular_weight`. + SpecularWeight = 4, + /// `specular_color`. + SpecularColor = 5, + /// `specular_roughness`. + SpecularRoughness = 6, + /// `specular_ior`. + SpecularIor = 7, + /// `specular_anisotropy`. + SpecularAnisotropy = 8, + /// `transmission_weight`. + TransmissionWeight = 9, + /// `transmission_color`. + TransmissionColor = 10, + /// `coat_weight`. + CoatWeight = 11, + /// `coat_color`. + CoatColor = 12, + /// `coat_roughness`. + CoatRoughness = 13, + /// `coat_ior`. + CoatIor = 14, + /// `fuzz_weight`. + FuzzWeight = 15, + /// `fuzz_color`. + FuzzColor = 16, + /// `fuzz_roughness`. + FuzzRoughness = 17, + /// `emission`, scene units. + Emission = 18, + /// `opacity`. + Opacity = 19, + /// Shading normal, world space. + Normal = 20, + /// Displacement in metres along the normal (not applied per hit). + Displacement = 21, +} + +impl Field { + /// Every field in encoding order. + pub const ALL: [Field; 22] = [ + Field::BaseWeight, + Field::BaseColor, + Field::BaseMetalness, + Field::BaseDiffuseRoughness, + Field::SpecularWeight, + Field::SpecularColor, + Field::SpecularRoughness, + Field::SpecularIor, + Field::SpecularAnisotropy, + Field::TransmissionWeight, + Field::TransmissionColor, + Field::CoatWeight, + Field::CoatColor, + Field::CoatRoughness, + Field::CoatIor, + Field::FuzzWeight, + Field::FuzzColor, + Field::FuzzRoughness, + Field::Emission, + Field::Opacity, + Field::Normal, + Field::Displacement, + ]; + + /// Field from its number. + pub fn from_u8(v: u8) -> Option<Field> { + Self::ALL.get(v as usize).copied() + } + + /// True for colour fields (three components). + pub fn is_colour(self) -> bool { + matches!( + self, + Field::BaseColor + | Field::SpecularColor + | Field::TransmissionColor + | Field::CoatColor + | Field::FuzzColor + | Field::Emission + ) + } + + /// Name as in `SurfaceInputs`. + pub fn name(self) -> &'static str { + match self { + Field::BaseWeight => "base_weight", + Field::BaseColor => "base_color", + Field::BaseMetalness => "base_metalness", + Field::BaseDiffuseRoughness => "base_diffuse_roughness", + Field::SpecularWeight => "specular_weight", + Field::SpecularColor => "specular_color", + Field::SpecularRoughness => "specular_roughness", + Field::SpecularIor => "specular_ior", + Field::SpecularAnisotropy => "specular_anisotropy", + Field::TransmissionWeight => "transmission_weight", + Field::TransmissionColor => "transmission_color", + Field::CoatWeight => "coat_weight", + Field::CoatColor => "coat_color", + Field::CoatRoughness => "coat_roughness", + Field::CoatIor => "coat_ior", + Field::FuzzWeight => "fuzz_weight", + Field::FuzzColor => "fuzz_color", + Field::FuzzRoughness => "fuzz_roughness", + Field::Emission => "emission", + Field::Opacity => "opacity", + Field::Normal => "normal", + Field::Displacement => "displacement", + } + } +} + +/// One instruction: opcode, destination register, small flags and three operands. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Instr { + /// Opcode. + pub op: Op, + /// Destination register. + pub dst: u8, + /// Opcode-specific small operand. + pub flags: u8, + /// First operand. + pub a: u32, + /// Second operand. + pub b: u32, + /// Third operand. + pub c: u32, +} + +impl Instr { + /// Instruction with all fields. + pub fn new(op: Op, dst: u8, flags: u8, a: u32, b: u32, c: u32) -> Self { + Self { op, dst, flags, a, b, c } + } +} + +/// Write-back of one register into one field after the code ran. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Output { + /// Field written. + pub field: Field, + /// Source register. + pub reg: u8, +} + +/// A compiled material: a constant block plus a register program that overrides fields per hit. +#[derive(Clone, Debug, PartialEq)] +pub struct Program { + /// Constant inputs (sanitised); what a constant program evaluates to. + pub base: SurfaceInputs, + /// Instructions; empty for a constant program. + pub code: Vec<Instr>, + /// Constant pool. + pub consts: Vec<f32>, + /// Write-back table applied in order after the code. + pub outputs: Vec<Output>, + /// Registers used. + pub registers: u32, + /// `NEED_*` bits. + pub needs: u32, + /// Snapshot texture indices sampled, sorted and unique. + pub textures: Vec<u32>, +} + +impl Default for Program { + fn default() -> Self { + Self::constant(SurfaceInputs::default().sanitized()) + } +} + +/// Why an encoded program could not be read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DecodeError(pub String); + +impl core::fmt::Display for DecodeError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "bad program: {}", self.0) + } +} + +impl std::error::Error for DecodeError {} + +impl Program { + /// A program that evaluates to `base` and runs nothing. + pub fn constant(base: SurfaceInputs) -> Self { + Self { base, code: Vec::new(), consts: Vec::new(), outputs: Vec::new(), registers: 0, needs: 0, textures: Vec::new() } + } + + /// True when nothing varies: use `base` and skip the interpreter. + pub fn is_constant(&self) -> bool { + self.code.is_empty() && self.outputs.is_empty() + } + + /// The binary form (without `base`), every word below 2^24 except constants. + pub fn encode(&self) -> Vec<u32> { + let mut w = Vec::with_capacity(PROGRAM_HEADER_WORDS + self.code.len() * 4 + self.consts.len() + self.outputs.len()); + w.extend_from_slice(&[ + PROGRAM_MAGIC, + PROGRAM_VERSION, + self.code.len() as u32, + self.consts.len() as u32, + self.outputs.len() as u32, + self.registers, + self.needs, + 0, + ]); + for i in &self.code { + w.extend_from_slice(&[i.op as u32 | (i.dst as u32) << 8 | (i.flags as u32) << 16, i.a, i.b, i.c]); + } + w.extend(self.consts.iter().map(|c| c.to_bits())); + w.extend(self.outputs.iter().map(|o| o.field as u32 | (o.reg as u32) << 8)); + w + } + + /// The binary form for the GPU `tables` buffer: integer words as exact floats, constants as themselves. + pub fn encode_f32(&self) -> Vec<f32> { + let words = self.encode(); + let first_const = PROGRAM_HEADER_WORDS + self.code.len() * 4; + let last_const = first_const + self.consts.len(); + words + .iter() + .enumerate() + .map(|(i, w)| if (first_const..last_const).contains(&i) { f32::from_bits(*w) } else { *w as f32 }) + .collect() + } + + /// Reads `encode()` output back (with the given base block). + pub fn decode(words: &[u32], base: SurfaceInputs) -> Result<Program, DecodeError> { + let bad = |m: &str| DecodeError(m.to_string()); + if words.len() < PROGRAM_HEADER_WORDS || words[0] != PROGRAM_MAGIC { + return Err(bad("missing header")); + } + if words[1] != PROGRAM_VERSION { + return Err(bad("unknown version")); + } + let (n, k, o) = (words[2] as usize, words[3] as usize, words[4] as usize); + if words.len() != PROGRAM_HEADER_WORDS + n * 4 + k + o { + return Err(bad("length does not match the header")); + } + let mut code = Vec::with_capacity(n); + for i in 0..n { + let at = PROGRAM_HEADER_WORDS + i * 4; + let w0 = words[at]; + let op = Op::from_u8((w0 & 0xff) as u8).ok_or_else(|| bad("unknown opcode"))?; + code.push(Instr::new(op, (w0 >> 8 & 0xff) as u8, (w0 >> 16 & 0xff) as u8, words[at + 1], words[at + 2], words[at + 3])); + } + let c0 = PROGRAM_HEADER_WORDS + n * 4; + let consts = words[c0..c0 + k].iter().map(|w| f32::from_bits(*w)).collect(); + let mut outputs = Vec::with_capacity(o); + for w in &words[c0 + k..] { + let field = Field::from_u8((w & 0xff) as u8).ok_or_else(|| bad("unknown field"))?; + outputs.push(Output { field, reg: (w >> 8 & 0xff) as u8 }); + } + let mut textures: Vec<u32> = + code.iter().filter(|i: &&Instr| matches!(i.op, Op::Tex | Op::TexBox)).map(|i| i.b).collect(); + textures.sort_unstable(); + textures.dedup(); + Ok(Program { base, code, consts, outputs, registers: words[5], needs: words[6], textures }) + } + + /// Checks register numbers, constant ranges and opcodes, so the interpreter never indexes out of range. + pub fn check(&self) -> Result<(), DecodeError> { + let bad = |m: String| Err(DecodeError(m)); + let regs = REGISTERS as u32; + let k = self.consts.len() as u32; + for (pc, i) in self.code.iter().enumerate() { + if i.dst as u32 >= regs { + return bad(format!("instruction {pc} writes register {}", i.dst)); + } + let reg = |r: u32| r < regs; + let ok = match i.op { + Op::Nop => true, + Op::Const => i.a + 4 <= k, + Op::Input => (i.a as usize) < MAX_UV_SETS, + Op::Swizzle | Op::Invert | Op::Luminance | Op::Project => reg(i.a), + Op::Combine | Op::Lerp | Op::Clamp => reg(i.a) && reg(i.b) && reg(i.c), + Op::Add | Op::Sub | Op::Mul | Op::Div | Op::Min | Op::Max | Op::Pow | Op::NormalMap | Op::Bump => { + reg(i.a) && reg(i.b) + } + Op::Ramp => reg(i.a) && i.b < k && i.b + 1 + 5 * self.consts[i.b as usize].max(0.0) as u32 <= k, + Op::Xform2 => reg(i.a) && i.b + 6 <= k, + Op::Tex => reg(i.a) && i.c + 4 <= k, + Op::Label => reg(i.a) && reg(i.c) && i.b + 12 <= k, + Op::TexBox => reg(i.a) && i.c + 11 <= k, + Op::Proc => { + i.a < k && { + let n = self.consts[i.a as usize].max(0.0) as u32; + i.a + 1 + n <= k && (0..n).all(|j| reg(self.consts[(i.a + 1 + j) as usize] as u32)) + } + } + }; + if !ok { + return bad(format!("instruction {pc} ({}) has an operand out of range", i.op.name())); + } + } + if let Some(o) = self.outputs.iter().find(|o| o.reg as u32 >= regs) { + return bad(format!("output {} reads register {}", o.field.name(), o.reg)); + } + Ok(()) + } + + /// Readable listing, one instruction per line. + pub fn disassemble(&self) -> String { + let mut s = String::new(); + for (pc, i) in self.code.iter().enumerate() { + let _ = writeln!(s, "{pc:3} {:<9} r{} f{} {} {} {}", i.op.name(), i.dst, i.flags, i.a, i.b, i.c); + } + for o in &self.outputs { + let _ = writeln!(s, " out {} <- r{}", o.field.name(), o.reg); + } + if !self.consts.is_empty() { + let _ = writeln!(s, " consts {:?}", self.consts); + } + s + } +} diff --git a/native/crates/fsh-materials/src/sample.rs b/native/crates/fsh-materials/src/sample.rs new file mode 100644 index 00000000..50a094c6 --- /dev/null +++ b/native/crates/fsh-materials/src/sample.rs @@ -0,0 +1,241 @@ +use crate::program::{Filter, Wrap}; +use crate::texture::{srgb8_table, ColourSpace, Texels, TextureImage, TextureLevel, TextureSampler, TextureSet}; +use fsh_core::{srgb_decode, srgb_encode, Vec2}; + +type V4 = [f32; 4]; + +fn decode8(c: u8, srgb: bool, alpha: bool) -> f32 { + if srgb && !alpha { + srgb8_table()[c as usize] + } else { + c as f32 / 255.0 + } +} + +fn encode8(v: f32, srgb: bool, alpha: bool) -> u8 { + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let e = if srgb && !alpha { srgb_encode(v) } else { v }; + (e * 255.0).round().clamp(0.0, 255.0) as u8 +} + +/// Folds a texel coordinate into `0..n` by the wrap mode (repeat: euclidean modulo; clamp: to the edge; mirror: +/// period `2n`, reflected). +pub fn wrap_index(i: i64, n: usize, wrap: Wrap) -> usize { + let n = n.max(1) as i64; + let r = match wrap { + Wrap::Repeat => i.rem_euclid(n), + Wrap::Clamp => i.clamp(0, n - 1), + Wrap::Mirror => { + let m = i.rem_euclid(2 * n); + if m >= n { + 2 * n - 1 - m + } else { + m + } + } + }; + r as usize +} + +impl TextureLevel { + /// True when the texel storage matches the size. + pub fn is_valid(&self) -> bool { + let n = self.width as usize * self.height as usize * 4; + n > 0 + && match &self.texels { + Texels::Rgba8(v) => v.len() == n, + Texels::RgbaF32(v) => v.len() == n, + } + } + + /// Linear RGBA of texel (x, y) (row 0 at the top); 8-bit sRGB rgb decoded by `srgb8_table` when `srgb`. + pub fn texel(&self, x: usize, y: usize, srgb: bool) -> V4 { + let i = (y * self.width as usize + x) * 4; + match &self.texels { + Texels::Rgba8(v) => match v.get(i..i + 4) { + Some(p) => [decode8(p[0], srgb, false), decode8(p[1], srgb, false), decode8(p[2], srgb, false), decode8(p[3], srgb, true)], + None => [0.0; 4], + }, + Texels::RgbaF32(v) => match v.get(i..i + 4) { + Some(p) => [p[0], p[1], p[2], p[3]], + None => [0.0; 4], + }, + } + } + + /// The next mip level: `max(1, w/2) x max(1, h/2)` texels, each the mean of the 2x2 block at (2x, 2y) in linear + /// values (indices clamped to this level), re-encoded to this level's storage: sRGB rgb as + /// `round(srgb_encode(mean) * 255)`, other 8-bit channels as `(a + b + c + d + 2) / 4` in integers (the + /// mean rounded half up, exactly), floats as the plain mean. + pub fn half(&self, srgb: bool) -> TextureLevel { + let (w, h) = (self.width as usize, self.height as usize); + let (nw, nh) = ((w / 2).max(1), (h / 2).max(1)); + if !self.is_valid() { + let texels = match &self.texels { + Texels::Rgba8(_) => Texels::Rgba8(vec![0; nw * nh * 4]), + Texels::RgbaF32(_) => Texels::RgbaF32(vec![0.0; nw * nh * 4]), + }; + return TextureLevel { width: nw as u32, height: nh as u32, texels }; + } + let blocks = (0..nh).flat_map(|y| { + let (y0, y1) = ((2 * y).min(h - 1), (2 * y + 1).min(h - 1)); + (0..nw).map(move |x| { + let (x0, x1) = ((2 * x).min(w - 1), (2 * x + 1).min(w - 1)); + [(y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4] + }) + }); + let texels = match &self.texels { + Texels::Rgba8(v) => { + let t = srgb8_table(); + let mut out = Vec::with_capacity(nw * nh * 4); + for [a, b, c, d] in blocks { + for k in 0..4 { + let q = [v[a + k], v[b + k], v[c + k], v[d + k]]; + out.push(if srgb && k < 3 { + encode8((t[q[0] as usize] + t[q[1] as usize] + t[q[2] as usize] + t[q[3] as usize]) * 0.25, true, false) + } else { + ((q.iter().map(|&x| x as u32).sum::<u32>() + 2) / 4) as u8 + }); + } + } + Texels::Rgba8(out) + } + Texels::RgbaF32(v) => { + let mut out = Vec::with_capacity(nw * nh * 4); + for [a, b, c, d] in blocks { + for k in 0..4 { + out.push((v[a + k] + v[b + k] + v[c + k] + v[d + k]) * 0.25); + } + } + Texels::RgbaF32(out) + } + }; + TextureLevel { width: nw as u32, height: nh as u32, texels } + } + + /// Bilinear lookup at `uv` (v up): `x = u w - 0.5`, `y = (1 - v) h - 0.5`, the four texels wrapped, decoded, + /// then weighted. + pub fn bilinear(&self, uv: Vec2, wrap: Wrap, srgb: bool) -> V4 { + let (w, h) = (self.width as usize, self.height as usize); + let x = uv.x * w as f32 - 0.5; + let y = (1.0 - uv.y) * h as f32 - 0.5; + let (fx0, fy0) = (x.floor(), y.floor()); + let (fx, fy) = (x - fx0, y - fy0); + let (ix, iy) = (fx0 as i64, fy0 as i64); + let (x0, x1) = (wrap_index(ix, w, wrap), wrap_index(ix.saturating_add(1), w, wrap)); + let (y0, y1) = (wrap_index(iy, h, wrap), wrap_index(iy.saturating_add(1), h, wrap)); + let (a, b, c, d) = (self.texel(x0, y0, srgb), self.texel(x1, y0, srgb), self.texel(x0, y1, srgb), self.texel(x1, y1, srgb)); + [0, 1, 2, 3].map(|k| (a[k] * (1.0 - fx) + b[k] * fx) * (1.0 - fy) + (c[k] * (1.0 - fx) + d[k] * fx) * fy) + } + + /// Nearest texel at `uv`: `floor(u w)`, `floor((1 - v) h)`, wrapped. + pub fn nearest(&self, uv: Vec2, wrap: Wrap, srgb: bool) -> V4 { + let (w, h) = (self.width as usize, self.height as usize); + let x = wrap_index((uv.x * w as f32).floor() as i64, w, wrap); + let y = wrap_index(((1.0 - uv.y) * h as f32).floor() as i64, h, wrap); + self.texel(x, y, srgb) + } +} + +impl TextureImage { + /// An image from 8-bit RGBA texels (sRGB encoded when `colour_space` is sRGB), with its mip pyramid when + /// `mipmaps`; `None` when the texel count does not match the size. + pub fn from_rgba8(width: u32, height: u32, texels: Vec<u8>, colour_space: ColourSpace, mipmaps: bool) -> Option<TextureImage> { + Self::from_level(TextureLevel { width, height, texels: Texels::Rgba8(texels) }, colour_space, mipmaps) + } + + /// An image from linear float RGBA texels; values that are not finite (NaN or infinite, as EXR and HDR files may + /// hold) become 0 so filtering never spreads them. + pub fn from_rgba_f32(width: u32, height: u32, mut texels: Vec<f32>, colour_space: ColourSpace, mipmaps: bool) -> Option<TextureImage> { + for v in texels.iter_mut().filter(|v| !v.is_finite()) { + *v = 0.0; + } + Self::from_level(TextureLevel { width, height, texels: Texels::RgbaF32(texels) }, colour_space, mipmaps) + } + + /// An image from 16-bit RGBA samples, stored as linear floats: rgb `srgb_decode(i / 65535)` when the colour + /// space is sRGB, otherwise `i / 65535`; alpha `i / 65535`. + pub fn from_rgba16(width: u32, height: u32, samples: &[u16], colour_space: ColourSpace, mipmaps: bool) -> Option<TextureImage> { + let srgb = colour_space == ColourSpace::Srgb; + let texels = samples + .iter() + .enumerate() + .map(|(i, &s)| { + let v = s as f32 / 65535.0; + if srgb && i % 4 != 3 { + srgb_decode(v) + } else { + v + } + }) + .collect(); + Self::from_rgba_f32(width, height, texels, colour_space, mipmaps) + } + + /// An image from its level 0, with the pyramid built when `mipmaps`. + pub fn from_level(level0: TextureLevel, colour_space: ColourSpace, mipmaps: bool) -> Option<TextureImage> { + if !level0.is_valid() { + return None; + } + let mut img = TextureImage { colour_space, levels: vec![level0] }; + if mipmaps { + img.build_mips(); + } + Some(img) + } + + /// Replaces levels 1.. with the pyramid built from level 0 down to 1 x 1. + pub fn build_mips(&mut self) { + self.levels.truncate(1); + let srgb = self.stores_srgb(); + while let Some(last) = self.levels.last() { + if (last.width <= 1 && last.height <= 1) || !last.is_valid() { + break; + } + let next = last.half(srgb); + self.levels.push(next); + } + } + + /// True when 8-bit texels hold sRGB-encoded rgb (decoded through `srgb8_table`). + pub fn stores_srgb(&self) -> bool { + self.colour_space == ColourSpace::Srgb + } + + /// Filtered value at `uv` for a footprint `footprint` uv units wide, converted to shading space; `None` when the + /// image has no usable level or `uv` is not finite. + pub fn sample(&self, uv: Vec2, footprint: f32, wrap: Wrap, filter: Filter) -> Option<V4> { + if !uv.x.is_finite() || !uv.y.is_finite() { + return None; + } + let base = self.levels.first().filter(|l| l.is_valid())?; + let srgb = self.stores_srgb(); + let v = match filter { + Filter::Nearest => base.nearest(uv, wrap, srgb), + Filter::Bilinear => base.bilinear(uv, wrap, srgb), + Filter::Trilinear => { + let usable = self.levels.iter().take_while(|l| l.is_valid()).count(); + let fp = if footprint.is_finite() { footprint.max(0.0) } else { 0.0 }; + let size = (fp * base.width as f32).max(fp * base.height as f32).max(1.0e-8); + let lod = size.log2().clamp(0.0, (usable - 1) as f32); + let l0 = lod.floor(); + let t = lod - l0; + let i0 = l0 as usize; + let a = self.levels[i0].bilinear(uv, wrap, srgb); + if t > 0.0 && i0 + 1 < usable { + let b = self.levels[i0 + 1].bilinear(uv, wrap, srgb); + [0, 1, 2, 3].map(|k| a[k] + (b[k] - a[k]) * t) + } else { + a + } + } + }; + Some(self.colour_space.to_shading(v)) + } +} + +impl TextureSampler for TextureSet { + fn sample(&self, texture: u32, uv: Vec2, footprint: f32, wrap: Wrap, filter: Filter, fallback: [f32; 4]) -> [f32; 4] { + self.get(texture).and_then(|img| img.sample(uv, footprint, wrap, filter)).unwrap_or(fallback) + } +} diff --git a/native/crates/fsh-materials/src/texture.rs b/native/crates/fsh-materials/src/texture.rs new file mode 100644 index 00000000..e7e978a4 --- /dev/null +++ b/native/crates/fsh-materials/src/texture.rs @@ -0,0 +1,113 @@ +use crate::program::{Filter, Wrap}; +use fsh_core::Vec2; +use std::sync::Arc; + +/// How texel values become shading values. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ColourSpace { + /// sRGB transfer and primaries: decode, then convert to ACEScg. + #[default] + Srgb, + /// Linear values with sRGB primaries: convert to ACEScg. + Linear, + /// Linear ACEScg: used as stored. + Acescg, + /// Non-colour data (roughness, normals, heights): used as stored. + Data, +} + +impl ColourSpace { + /// Directory code used by the GPU packing (0 srgb, 1 linear, 2 acescg, 3 data). + pub fn code(self) -> u32 { + self as u32 + } + + /// Converts a filtered, already decoded RGBA value to shading space: sRGB primaries to ACEScg for `srgb` and + /// `linear`, unchanged for `acescg` and `data`; alpha is never changed. + pub fn to_shading(self, v: [f32; 4]) -> [f32; 4] { + match self { + ColourSpace::Srgb | ColourSpace::Linear => { + let c = fsh_core::Rgb::from_linear_srgb([v[0], v[1], v[2]]); + [c.r, c.g, c.b, v[3]] + } + ColourSpace::Acescg | ColourSpace::Data => v, + } + } + + /// Parses "srgb", "linear", "acescg" or "data" (also "raw" and "non_color" for data). + pub fn parse(s: &str) -> Option<ColourSpace> { + match s.trim().to_ascii_lowercase().as_str() { + "srgb" | "s_rgb" => Some(ColourSpace::Srgb), + "linear" | "linear_srgb" => Some(ColourSpace::Linear), + "acescg" | "aces_cg" => Some(ColourSpace::Acescg), + "data" | "raw" | "non_color" | "non_colour" => Some(ColourSpace::Data), + _ => None, + } + } +} + +/// The exact sRGB decode of every 8-bit code (`srgb_decode(i / 255)`); both engines decode through this table. +pub fn srgb8_table() -> &'static [f32; 256] { + static TABLE: std::sync::OnceLock<[f32; 256]> = std::sync::OnceLock::new(); + TABLE.get_or_init(|| core::array::from_fn(|i| fsh_core::srgb_decode(i as f32 / 255.0))) +} + +/// Texel storage of one mip level, row-major, row 0 at v = 1 (the top of the image). +#[derive(Clone, Debug, PartialEq)] +pub enum Texels { + /// Four bytes per texel (sRGB encoded when the image's colour space is sRGB). + Rgba8(Vec<u8>), + /// Four floats per texel. + RgbaF32(Vec<f32>), +} + +/// One mip level. +#[derive(Clone, Debug, PartialEq)] +pub struct TextureLevel { + /// Width in texels. + pub width: u32, + /// Height in texels. + pub height: u32, + /// Texels. + pub texels: Texels, +} + +/// A decoded image with its mip pyramid (level 0 first). +#[derive(Clone, Debug, PartialEq)] +pub struct TextureImage { + /// How texel values are interpreted. + pub colour_space: ColourSpace, + /// Mip levels, level 0 first; one level when mipmaps were not wanted. + pub levels: Vec<TextureLevel>, +} + +/// Pixels for every texture a snapshot names, in `RenderSnapshot::textures` order; `None` is a missing image. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TextureSet { + /// Images by snapshot texture index. + pub images: Vec<Option<Arc<TextureImage>>>, +} + +impl TextureSet { + /// Image at a snapshot texture index. + pub fn get(&self, texture: u32) -> Option<&TextureImage> { + self.images.get(texture as usize).and_then(|i| i.as_deref()) + } +} + +/// Texture lookups at a shading point; returns linear ACEScg (colour spaces) or raw values (data), RGBA. +pub trait TextureSampler { + /// Filtered value of `texture` at `uv` for a footprint `footprint` uv units wide; `fallback` when it has no pixels. + fn sample(&self, texture: u32, uv: Vec2, footprint: f32, wrap: Wrap, filter: Filter, fallback: [f32; 4]) -> [f32; 4]; +} + +/// A sampler without pixels: every lookup gives the fallback. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct NoTextures; + +impl TextureSampler for NoTextures { + fn sample(&self, _texture: u32, _uv: Vec2, _footprint: f32, _wrap: Wrap, _filter: Filter, fallback: [f32; 4]) -> [f32; 4] { + fallback + } +} diff --git a/native/crates/fsh-py/Cargo.toml b/native/crates/fsh-py/Cargo.toml index f2600a3e..46d6e861 100644 --- a/native/crates/fsh-py/Cargo.toml +++ b/native/crates/fsh-py/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-py" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false diff --git a/native/crates/fsh-py/pyproject.toml b/native/crates/fsh-py/pyproject.toml index 0555f980..02e048f3 100644 --- a/native/crates/fsh-py/pyproject.toml +++ b/native/crates/fsh-py/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "fsh-py" -version = "0.4.0" +version = "0.6.0" description = "FormShot engine binding: the command catalogue and an engine session" license = { text = "Apache-2.0" } requires-python = ">=3.9" diff --git a/native/crates/fsh-render-cpu/Cargo.toml b/native/crates/fsh-render-cpu/Cargo.toml index 049a3ca0..f26bcf49 100644 --- a/native/crates/fsh-render-cpu/Cargo.toml +++ b/native/crates/fsh-render-cpu/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-render-cpu" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false diff --git a/native/crates/fsh-render-cpu/src/camera.rs b/native/crates/fsh-render-cpu/src/camera.rs index 3304dd54..240486b3 100644 --- a/native/crates/fsh-render-cpu/src/camera.rs +++ b/native/crates/fsh-render-cpu/src/camera.rs @@ -98,6 +98,16 @@ impl CameraModel { } } + /// Ray cone of one film pixel (Akenine-Moller et al., Ray Tracing Gems ch. 20): (width at the ray origin, spread + /// angle). Perspective: width 0, spread `atan(2 tan_y / film height)`; orthographic: width `2 half_h / film + /// height`, spread 0. The lens is ignored. + pub(crate) fn pixel_cone(&self) -> (f32, f32) { + match self.cam.projection { + Projection::Orthographic => (2.0 * self.half_h / self.height, 0.0), + Projection::Perspective => (0.0, (2.0 * self.tan_y / self.height).atan()), + } + } + /// Ray through film position (`fx`, `fy`) in pixels from the top-left corner, with a lens sample. pub(crate) fn ray(&self, fx: f32, fy: f32, lens: Vec2) -> Ray { let sx = 2.0 * fx / self.width - 1.0; diff --git a/native/crates/fsh-render-cpu/src/emissive.rs b/native/crates/fsh-render-cpu/src/emissive.rs index 57c223ea..cae21b5f 100644 --- a/native/crates/fsh-render-cpu/src/emissive.rs +++ b/native/crates/fsh-render-cpu/src/emissive.rs @@ -1,6 +1,6 @@ use fsh_core::sampling::uniform_triangle; use fsh_core::{Rgb, Vec2, Vec3}; -use fsh_materials::{Bsdf, ShadingFrame}; +use fsh_materials::{Bsdf, ShadingFrame, TextureSet}; use fsh_scene::RayVisibility; use crate::geometry::{Geometry, SurfacePoint}; @@ -158,17 +158,25 @@ impl EmissiveSet { /// Radiance leaving triangle `k` at barycentrics (b1, b2) toward `wo` (unit, pointing away from the light), /// evaluated by the same BSDF emission the path sees when it hits the triangle. - fn radiance(&self, geo: &Geometry, k: usize, q: Vec3, b1: f32, b2: f32, wo: Vec3) -> Rgb { + #[allow(clippy::too_many_arguments)] + fn radiance(&self, geo: &Geometry, textures: &TextureSet, k: usize, q: Vec3, b1: f32, b2: f32, wo: Vec3) -> Rgb { let t = &self.tris[k]; let Some(data) = geo.instances.get(t.instance as usize) else { return Rgb::BLACK }; let ns = geo.shading_normal(t.instance, t.prim, b1, b2).unwrap_or(t.normal); let sp = SurfacePoint { p: q, ng: t.normal, ns }; + if data.program.is_some() { + if let Some(sh) = geo.shade(t.instance, t.prim, b1, b2, sp.p, sp.ng, sp.ns, 0.0, textures) { + let frame = ShadingFrame { shading_normal: sh.ns, geometric_normal: sp.ng, tangent: Vec3::ZERO }; + return Bsdf::new(&sh.inputs, &frame, sh.eta).emission(wo) * sh.inputs.opacity; + } + } let frame = ShadingFrame { shading_normal: sp.ns, geometric_normal: sp.ng, tangent: Vec3::ZERO }; Bsdf::new(&data.inputs, &frame, data.eta).emission(wo) * data.inputs.opacity } /// Samples triangle `k` uniformly by area as seen from `p`; `pdf` is the solid-angle density including `pick_prob`. - pub(crate) fn sample(&self, geo: &Geometry, k: usize, pick_prob: f32, p: Vec3, u: Vec2) -> Option<EmissiveSample> { + #[allow(clippy::too_many_arguments)] + pub(crate) fn sample(&self, geo: &Geometry, textures: &TextureSet, k: usize, pick_prob: f32, p: Vec3, u: Vec2) -> Option<EmissiveSample> { let t = self.tris.get(k)?; let b = uniform_triangle(u); let q = t.corners[0] * b[0] + t.corners[1] * b[1] + t.corners[2] * b[2]; @@ -182,7 +190,7 @@ impl EmissiveSet { if cos <= 1.0e-6 { return None; } - let radiance = self.radiance(geo, k, q, b[1], b[2], -wi); + let radiance = self.radiance(geo, textures, k, q, b[1], b[2], -wi); if radiance.is_black() { return None; } diff --git a/native/crates/fsh-render-cpu/src/geometry.rs b/native/crates/fsh-render-cpu/src/geometry.rs index 26975d34..3466aa64 100644 --- a/native/crates/fsh-render-cpu/src/geometry.rs +++ b/native/crates/fsh-render-cpu/src/geometry.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use fsh_accel::{Hit, Instance, MeshBvh, Scene}; -use fsh_core::{Transform, Vec3}; -use fsh_materials::{Bsdf, SurfaceInputs}; +use fsh_core::{orthonormal_basis, Rgb, Transform, Vec2, Vec3}; +use fsh_materials::{Bsdf, HitContext, Optics, Program, SurfaceInputs, TextureSet, MAX_UV_SETS}; use fsh_scene::{Mesh, RayVisibility, RenderSnapshot, SurfaceParams, SCENE_UNITS_PER_NIT}; use rayon::prelude::*; @@ -62,15 +62,46 @@ pub fn surface_inputs(p: &SurfaceParams, tint: Option<fsh_core::Rgb>) -> Surface .sanitized() } +/// Constant inputs of an instance: its material program's `base` block (sanitised parameters, emission in scene +/// units), then the part tint replacing `base_color` and sanitised again, as the GPU builds them. fn instance_inputs(snap: &RenderSnapshot, idx: usize) -> SurfaceInputs { let Some(inst) = snap.instances.get(idx) else { return SurfaceInputs::default().sanitized() }; - let params = snap - .materials - .get(inst.material.index()) - .or_else(|| snap.materials.get(snap.default_material.index())) - .map(|m| m.params) - .unwrap_or_default(); - surface_inputs(¶ms, inst.tint) + let material = snap.materials.get(inst.material.index()).or_else(|| snap.materials.get(snap.default_material.index())); + let Some(m) = material else { return surface_inputs(&SurfaceParams::default(), inst.tint) }; + let mut inputs = m.program.base; + if let Some(t) = inst.tint { + inputs.base_color = t; + inputs = inputs.sanitized(); + } + inputs +} + +fn instance_program(snap: &RenderSnapshot, idx: usize) -> Option<Arc<Program>> { + let inst = snap.instances.get(idx)?; + let m = snap.materials.get(inst.material.index()).or_else(|| snap.materials.get(snap.default_material.index()))?; + (!m.program.is_constant()).then(|| Arc::clone(&m.program)) +} + +fn lerp3<T: Copy + std::ops::Mul<f32, Output = T> + std::ops::Add<Output = T>>(c: [T; 3], w: [f32; 3]) -> T { + c[0] * w[0] + c[1] * w[1] + c[2] * w[2] +} + +fn unit(v: Vec3) -> Option<Vec3> { + v.try_normalize().filter(|n| n.is_finite()) +} + +/// dP/du and dP/dv of a triangle from its corners and uvs; `None` when the uv mapping is degenerate. +fn uv_derivatives(p: [Vec3; 3], uv: [Vec2; 3]) -> Option<(Vec3, Vec3)> { + let (dp1, dp2) = (p[1] - p[0], p[2] - p[0]); + let (d1, d2) = (uv[1] - uv[0], uv[2] - uv[0]); + let det = d1.x * d2.y - d1.y * d2.x; + if !det.is_finite() || det.abs() < 1.0e-12 { + return None; + } + let inv = 1.0 / det; + let dpdu = (dp1 * d2.y - dp2 * d1.y) * inv; + let dpdv = (dp2 * d1.x - dp1 * d2.x) * inv; + (dpdu.is_finite() && dpdv.is_finite()).then_some((dpdu, dpdv)) } #[derive(Clone)] @@ -80,12 +111,41 @@ pub(crate) struct CachedMesh { bvh: Arc<MeshBvh>, } +/// Thin film and dispersion of document surface parameters. +pub fn surface_optics(p: &SurfaceParams) -> Optics { + Optics::new( + p.thin_film_weight, + p.thin_film_thickness, + p.thin_film_ior, + p.transmission_dispersion_scale, + p.transmission_dispersion_abbe_number, + ) +} + +fn instance_optics(snap: &RenderSnapshot, idx: usize) -> Optics { + let Some(inst) = snap.instances.get(idx) else { return Optics::NONE }; + snap.materials + .get(inst.material.index()) + .or_else(|| snap.materials.get(snap.default_material.index())) + .map_or(Optics::NONE, |m| surface_optics(&m.params)) +} + pub(crate) struct InstanceData { pub mesh: usize, pub inputs: SurfaceInputs, + pub optics: Optics, pub eta: f32, pub transform: Transform, pub rays: u8, + pub program: Option<Arc<Program>>, + pub tint: Option<Rgb>, +} + +/// Inputs of one shading point from a material program. +pub(crate) struct Shading { + pub inputs: SurfaceInputs, + pub ns: Vec3, + pub eta: f32, } pub(crate) struct Geometry { @@ -134,9 +194,12 @@ impl Geometry { instances.push(InstanceData { mesh: mi, inputs, + optics: instance_optics(snap, idx), eta: Bsdf::relative_ior(&inputs, 1.0), transform: inst.transform, rays: inst.rays, + program: instance_program(snap, idx), + tint: inst.tint, }); let Some(cm) = meshes.get(mi) else { continue }; let Ok(a) = Instance::new(cm.bvh.clone(), inst.transform, idx as u32, accel_mask(inst.rays)) else { continue }; @@ -162,8 +225,94 @@ impl Geometry { pub(crate) fn refresh_materials(&mut self, snap: &RenderSnapshot) { for (idx, inst) in self.instances.iter_mut().enumerate() { inst.inputs = instance_inputs(snap, idx); + inst.optics = instance_optics(snap, idx); inst.eta = Bsdf::relative_ior(&inst.inputs, 1.0); + inst.program = instance_program(snap, idx); + inst.tint = snap.instances.get(idx).and_then(|i| i.tint); + } + } + + /// Everything a material program reads at barycentrics (b1, b2) of (snapshot instance, triangle): world `p`, + /// `ng` and `ns` as the hit found them, object position and normal, the mesh's uv sets as stored (v up), + /// dP/du and dP/dv of uv set 0 (an orthonormal frame around the normal without uvs), the mesh tangent made + /// orthogonal to `ns`, and the footprint width. + #[allow(clippy::too_many_arguments)] + pub(crate) fn hit_context(&self, instance: u32, prim: u32, b1: f32, b2: f32, p: Vec3, ng: Vec3, ns: Vec3, footprint: f32) -> Option<HitContext> { + let inst = self.instances.get(instance as usize)?; + let mesh = &self.meshes.get(inst.mesh)?.mesh; + let base = prim as usize * 3; + let idx = [*mesh.indices.get(base)? as usize, *mesh.indices.get(base + 1)? as usize, *mesh.indices.get(base + 2)? as usize]; + let w = [1.0 - b1 - b2, b1, b2]; + let pos = [*mesh.positions.get(idx[0])?, *mesh.positions.get(idx[1])?, *mesh.positions.get(idx[2])?]; + let p_object = lerp3(pos, w); + let n_geo = unit((pos[1] - pos[0]).cross(pos[2] - pos[0])).unwrap_or(Vec3::Z); + let n_object = if mesh.has_normals() { + idx.iter().map(|&i| mesh.normals.get(i).copied()).collect::<Option<Vec<Vec3>>>().and_then(|n| unit(lerp3([n[0], n[1], n[2]], w))) + } else { + None + } + .unwrap_or(n_geo); + let mut ctx = HitContext { p, p_object, ng, ns, n_object, footprint, ..HitContext::default() }; + let mut derivs = None; + for (k, set) in mesh.uvs.iter().take(MAX_UV_SETS).enumerate() { + if set.len() != mesh.positions.len() { + break; + } + let c = idx.map(|i| set[i]); + ctx.uv[k] = lerp3(c, w); + ctx.uv_count = k as u32 + 1; + if k == 0 { + derivs = uv_derivatives(pos, c); + } + } + match derivs { + Some((du, dv)) => { + ctx.dpdu_object = du; + ctx.dpdv_object = dv; + ctx.dpdu = inst.transform.vector(du); + ctx.dpdv = inst.transform.vector(dv); + } + None => { + (ctx.dpdu, ctx.dpdv) = orthonormal_basis(ns); + (ctx.dpdu_object, ctx.dpdv_object) = orthonormal_basis(n_object); + } + } + if mesh.tangents.len() == mesh.positions.len() { + let t = lerp3(idx.map(|i| mesh.tangents[i]), w); + let tw = inst.transform.vector(Vec3::new(t.x, t.y, t.z)); + if let Some(tu) = unit(tw - ns * ns.dot(tw)) { + let flip = if inst.transform.swaps_handedness() { -1.0 } else { 1.0 }; + ctx.tangent = tu; + ctx.tangent_sign = if t.w < 0.0 { -flip } else { flip }; + } + } + Some(ctx) + } + + /// Runs the material program of a non-constant instance at a surface point (then the part tint); `None` for + /// constant materials, which keep `InstanceData::inputs`. + #[allow(clippy::too_many_arguments)] + pub(crate) fn shade( + &self, + instance: u32, + prim: u32, + b1: f32, + b2: f32, + p: Vec3, + ng: Vec3, + ns: Vec3, + footprint: f32, + textures: &TextureSet, + ) -> Option<Shading> { + let program = self.instances.get(instance as usize)?.program.as_ref()?; + let ctx = self.hit_context(instance, prim, b1, b2, p, ng, ns, footprint)?; + let s = program.evaluate(&ctx, textures); + let mut inputs = s.inputs; + if let Some(t) = self.instances[instance as usize].tint { + inputs.base_color = t; + inputs = inputs.sanitized(); } + Some(Shading { eta: Bsdf::relative_ior(&inputs, 1.0), inputs, ns: s.normal }) } pub(crate) fn surface(&self, hit: &Hit) -> Option<SurfacePoint> { diff --git a/native/crates/fsh-render-cpu/src/integrator.rs b/native/crates/fsh-render-cpu/src/integrator.rs index 7ccbb7bd..94685906 100644 --- a/native/crates/fsh-render-cpu/src/integrator.rs +++ b/native/crates/fsh-render-cpu/src/integrator.rs @@ -1,8 +1,8 @@ use fsh_accel::{Hit, Intersector}; -use fsh_core::sampler::{bounce_dim, BOUNCE_BSDF, BOUNCE_LIGHT, BOUNCE_LIGHT_SELECT, BOUNCE_LOBE, BOUNCE_ROULETTE, BOUNCE_SPARE, DIM_LENS, DIM_PIXEL}; +use fsh_core::sampler::{bounce_dim, BOUNCE_BSDF, BOUNCE_LIGHT, BOUNCE_LIGHT_SELECT, BOUNCE_LOBE, BOUNCE_ROULETTE, BOUNCE_SPARE, DIM_LENS, DIM_PIXEL, DIM_WAVELENGTH}; use fsh_core::sampling::power_heuristic; use fsh_core::{PixelSampler, Ray, Rgb, Vec2, Vec3}; -use fsh_materials::{Bsdf, LobeFlags, ShadingFrame, SurfaceInputs}; +use fsh_materials::{dispersion_channel, Bsdf, LobeFlags, ShadingFrame, SurfaceInputs, TextureSet}; use fsh_scene::BackgroundMode; use crate::camera::{CameraModel, PixelFilter}; @@ -74,6 +74,45 @@ pub(crate) struct Ctx<'a> { pub ground: Option<GroundCtx>, pub background: BackgroundMode, pub background_colour: Rgb, + pub textures: &'a TextureSet, +} + +/// Smallest |cos| between the ray and the geometric normal used to stretch the footprint at grazing hits. +const CONE_MIN_COS: f32 = 0.05; + +/// Spread added to the ray cone by a bounce: `2 alpha` with `alpha = r^2`, r = 1 for diffuse lobes, the specular +/// roughness for glossy ones, 0 for delta lobes. +fn cone_widening(flags: LobeFlags, inputs: &SurfaceInputs) -> f32 { + if flags.is_specular() { + 0.0 + } else if flags.contains(LobeFlags::DIFFUSE) { + 2.0 + } else { + let r = inputs.specular_roughness.clamp(0.0, 1.0); + 2.0 * r * r + } +} + +/// Height above the geometric horizon a bent normal's mirror direction is lifted to. +const NORMAL_CLAMP_LIFT: f32 = 0.01; + +/// A shading normal that a material program bent (normal or bump map), adjusted so the mirror direction of `wo` stays +/// above the geometric surface: when it would point below, it is lifted to just above the horizon and the normal +/// becomes the half vector of `wo` and that direction (normal clamping as in Keller et al., The Iray Light Transport +/// Simulation and Rendering System, 2017). Without it strongly tilted maps go black where reflections are rejected. +fn clamp_bent_normal(ns: Vec3, ng: Vec3, wo: Vec3) -> Vec3 { + let ngf = if ng.dot(wo) < 0.0 { -ng } else { ng }; + let r = ns * (2.0 * wo.dot(ns)) - wo; + let d = r.dot(ngf); + if d >= NORMAL_CLAMP_LIFT { + return ns; + } + let h = (wo + (r + ngf * (NORMAL_CLAMP_LIFT - d)).normalize()).normalize(); + if h.is_finite() { + h + } else { + ns + } } #[derive(Clone, Copy, Debug, Default)] @@ -133,7 +172,7 @@ impl Ctx<'_> { shadows: lamp.shadows, }) } - LightChoice::Emissive(k) => self.lights.emissive.sample(self.geo, k, 1.0, p, u).map(|es| LightSample { + LightChoice::Emissive(k) => self.lights.emissive.sample(self.geo, self.textures, k, 1.0, p, u).map(|es| LightSample { wi: es.wi, radiance: es.radiance, pdf: es.pdf, @@ -231,6 +270,8 @@ impl Ctx<'_> { let mut first = true; let mut passes = 0u32; let mut pending: Option<Option<Hit>> = None; + let (mut cone_width, mut cone_spread) = self.cam.pixel_cone(); + let mut hero = false; loop { let hit = match pending.take() { @@ -299,6 +340,8 @@ impl Ctx<'_> { first = false; } t = t * bs.weight * g.reflection; + cone_width += cone_spread * t_ground * ray.direction.length(); + cone_spread += cone_widening(bs.flags, &g.inputs); ray = r2; pending = Some(h2); camera_chain = false; @@ -337,18 +380,29 @@ impl Ctx<'_> { let Some(surf) = self.geo.surface(&h) else { break }; let Some(inst) = self.geo.instances.get(h.instance_id as usize) else { break }; - let mut inputs = inst.inputs; + let dir = ray.direction.normalize(); + let wo = -dir; + let dist = h.t * ray.direction.length(); + let shaded = inst.program.as_ref().and_then(|_| { + let cos = surf.ng.dot(dir).abs().max(CONE_MIN_COS); + let footprint = (cone_width + cone_spread * dist).abs() / cos; + self.geo.shade(h.instance_id, h.prim, h.u, h.v, surf.p, surf.ng, surf.ns, footprint, self.textures) + }); + let (mut inputs, eta, ns) = match shaded { + Some(sh) if sh.ns != surf.ns => (sh.inputs, sh.eta, clamp_bent_normal(sh.ns, surf.ng, wo)), + Some(sh) => (sh.inputs, sh.eta, sh.ns), + None => (inst.inputs, inst.eta, surf.ns), + }; + cone_width += cone_spread * dist; if regularize && s.roughness_floor > 0.0 { inputs.specular_roughness = inputs.specular_roughness.max(s.roughness_floor); inputs.coat_roughness = inputs.coat_roughness.max(s.roughness_floor); } - let dir = ray.direction.normalize(); - let wo = -dir; if first { out.alpha = 1.0; out.hit = true; - out.depth = h.t * ray.direction.length(); - out.normal = if surf.ns.dot(wo) < 0.0 { -surf.ns } else { surf.ns }; + out.depth = dist; + out.normal = if ns.dot(wo) < 0.0 { -ns } else { ns }; } if inputs.opacity < 1.0 { let u = sp.get_1d(bounce_dim(vertex, BOUNCE_SPARE)); @@ -366,8 +420,20 @@ impl Ctx<'_> { continue; } } - let frame = ShadingFrame { shading_normal: surf.ns, geometric_normal: surf.ng, tangent: Vec3::ZERO }; - let bsdf = Bsdf::new(&inputs, &frame, inst.eta); + let frame = ShadingFrame { shading_normal: ns, geometric_normal: surf.ng, tangent: Vec3::ZERO }; + let mut eta = eta; + let mut channel = None; + if inst.optics.is_dispersive() && inputs.transmission_weight > 0.0 && !inputs.thin_walled { + let c = dispersion_channel(sp.get_1d(DIM_WAVELENGTH)); + inputs.specular_ior = inst.optics.channel_ior(inputs.specular_ior, c).clamp(1.0, 4.0); + eta = inputs.specular_ior; + channel = Some(c); + } + let bsdf = if inst.optics.has_film() { + Bsdf::new_optics(&inputs, &inst.optics, &frame, eta) + } else { + Bsdf::new(&inputs, &frame, eta) + }; if first { out.albedo = bsdf.albedo(wo); first = false; @@ -393,7 +459,12 @@ impl Ctx<'_> { let sampled = self.sample_light(choice, surf.p, u).map(|ls| (ls.wi, ls.radiance, ls.pdf * psel, ls.delta, ls.target, ls.shadows)); if let Some((wi, li, pdf_l, delta, target, shadows)) = sampled { if pdf_l > 0.0 && !li.is_black() { - let (f, pdf_b) = bsdf.eval(wo, wi); + let (mut f, pdf_b) = bsdf.eval(wo, wi); + if let Some(c) = channel.filter(|_| !hero && wi.dot(surf.ng) * wo.dot(surf.ng) < 0.0) { + let mut one = Rgb::BLACK; + one[c] = 3.0; + f *= one; + } if !f.is_black() { let visible = if shadows { *rays += 1; @@ -432,6 +503,12 @@ impl Ctx<'_> { bounces += 1; } t *= bs.weight; + if let Some(c) = channel.filter(|_| is_trans && !hero) { + let mut one = Rgb::BLACK; + one[c] = 3.0; + t *= one; + hero = true; + } if !t.is_finite() || t.is_black() { break; } @@ -440,6 +517,7 @@ impl Ctx<'_> { camera_chain = camera_chain && spec; prev_delta = spec; prev_pdf = bs.pdf; + cone_spread += cone_widening(bs.flags, &inputs); if bs.flags.contains(LobeFlags::DIFFUSE) { regularize = true; } diff --git a/native/crates/fsh-render-cpu/src/lib.rs b/native/crates/fsh-render-cpu/src/lib.rs index 5276251e..8dc3b7c3 100644 --- a/native/crates/fsh-render-cpu/src/lib.rs +++ b/native/crates/fsh-render-cpu/src/lib.rs @@ -25,6 +25,6 @@ pub use error::{RenderError, Result}; pub use film::{ instance_rect, relative_error, AdaptiveSettings, Framebuffer, PixelMean, PixelRect, PixelSums, ADAPTIVE_LUM_FLOOR, NO_INSTANCE, TILE, }; -pub use geometry::surface_inputs; +pub use geometry::{surface_inputs, surface_optics}; pub use integrator::IntegratorSettings; pub use renderer::{scaled_size, Execution, PassReport, Renderer, Stats, MIN_RESOLUTION_SCALE, STUDIO_PATH}; diff --git a/native/crates/fsh-render-cpu/src/renderer.rs b/native/crates/fsh-render-cpu/src/renderer.rs index e1cea3b8..2fa54207 100644 --- a/native/crates/fsh-render-cpu/src/renderer.rs +++ b/native/crates/fsh-render-cpu/src/renderer.rs @@ -2,7 +2,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use fsh_core::{Rgb, Vec3}; -use fsh_materials::SurfaceInputs; +use fsh_materials::{SurfaceInputs, TextureSet}; use fsh_scene::{BackgroundMode, EnvironmentSource, ImageStyle, RenderCamera, RenderSnapshot}; use rayon::prelude::*; @@ -118,6 +118,7 @@ pub struct Renderer { lights: LightSet, env: EnvMap, env_image: Option<EnvImage>, + textures: TextureSet, sun: Option<Lamp>, camera: CameraModel, style: ImageStyle, @@ -242,6 +243,7 @@ impl Renderer { lights, env, env_image: None, + textures: TextureSet::default(), sun, settings, adaptive: AdaptiveSettings::default(), @@ -289,6 +291,19 @@ impl Renderer { self.reset(); } + /// Supplies the pixels of the snapshot's textures (`RenderSnapshot::textures` order; `None` or a missing image + /// samples the program's fallback); resets accumulation. + pub fn set_textures(&mut self, textures: Option<TextureSet>) { + self.textures = textures.unwrap_or_default(); + self.rebuild_lights(); + self.reset(); + } + + /// The texture pixels in use. + pub fn textures(&self) -> &TextureSet { + &self.textures + } + fn rebuild_lights(&mut self) { self.lights = build_lights(&self.snapshot, &self.geometry, self.settings.emissive_lights, &self.env, self.sun); } @@ -518,6 +533,7 @@ impl Renderer { env: &'a EnvMap, camera: &'a CameraModel, settings: &'a IntegratorSettings, + textures: &'a TextureSet, ) -> Ctx<'a> { let g = &snapshot.ground; let ground = g.shadow_catcher.then(|| GroundCtx { @@ -541,6 +557,7 @@ impl Renderer { ground, background: snapshot.environment.background, background_colour: snapshot.environment.background_colour, + textures, } } @@ -549,7 +566,7 @@ impl Renderer { let start = (self.clock)(); let (w, h) = (self.film.width() as usize, self.film.height() as usize); let tiles_x = self.film.tiles_x(); - let ctx = Self::ctx(&self.snapshot, &self.geometry, &self.lights, &self.env, &self.camera, &self.settings); + let ctx = Self::ctx(&self.snapshot, &self.geometry, &self.lights, &self.env, &self.camera, &self.settings, &self.textures); let film = &mut self.film; let kernel = |ti: usize, tile: &mut [PixelSums]| -> (u64, u32) { if cancel.load(Ordering::Relaxed) { diff --git a/native/crates/fsh-render-cpu/src/spec.rs b/native/crates/fsh-render-cpu/src/spec.rs index fb00f76a..77af5dd6 100644 --- a/native/crates/fsh-render-cpu/src/spec.rs +++ b/native/crates/fsh-render-cpu/src/spec.rs @@ -2,7 +2,7 @@ //! environment, light and camera tables a renderer builds. use fsh_core::sampler::{ - BOUNCE_BSDF, BOUNCE_LIGHT, BOUNCE_LIGHT_SELECT, BOUNCE_LOBE, BOUNCE_ROULETTE, BOUNCE_SPARE, DIM_LENS, DIM_PIXEL, SOBOL_DIMENSIONS, + BOUNCE_BSDF, BOUNCE_LIGHT, BOUNCE_LIGHT_SELECT, BOUNCE_LOBE, BOUNCE_ROULETTE, BOUNCE_SPARE, DIM_LENS, DIM_PIXEL, DIM_WAVELENGTH, SOBOL_DIMENSIONS, }; use fsh_core::math::{dir_from_equirect_uv, equirect_uv_from_dir, PI}; @@ -68,6 +68,7 @@ pub const DRAW_ORDER: &[Draw] = &[ Draw { name: "catcher mirror lobe", source: DimSource::Bounce(BOUNCE_LOBE), width: 1, when: "catcher hit with reflection > 0" }, Draw { name: "catcher mirror direction", source: DimSource::Bounce(BOUNCE_BSDF), width: 2, when: "catcher hit with reflection > 0" }, Draw { name: "opacity pass-through", source: DimSource::Bounce(BOUNCE_SPARE), width: 1, when: "surface hit with opacity < 1" }, + Draw { name: "dispersion channel", source: DimSource::Fixed(DIM_WAVELENGTH), width: 1, when: "surface hit on a dispersive, transmissive, not thin-walled material; floor(3u) is the path's channel" }, Draw { name: "light choice", source: DimSource::Bounce(BOUNCE_LIGHT_SELECT), width: 1, when: "surface hit, BSDF not delta-only" }, Draw { name: "position on the light", source: DimSource::Bounce(BOUNCE_LIGHT), width: 2, when: "after a light choice" }, Draw { name: "BSDF lobe", source: DimSource::Bounce(BOUNCE_LOBE), width: 1, when: "surface hit below the bounce limit" }, diff --git a/native/crates/fsh-render-gpu/Cargo.toml b/native/crates/fsh-render-gpu/Cargo.toml index ac8e1670..17fd545a 100644 --- a/native/crates/fsh-render-gpu/Cargo.toml +++ b/native/crates/fsh-render-gpu/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-render-gpu" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false diff --git a/native/crates/fsh-render-gpu/src/emissive.rs b/native/crates/fsh-render-gpu/src/emissive.rs index 47d048e2..11badbe6 100644 --- a/native/crates/fsh-render-gpu/src/emissive.rs +++ b/native/crates/fsh-render-gpu/src/emissive.rs @@ -27,16 +27,16 @@ pub struct EmissiveTable { pub importance: f32, } -/// Sanitized surface inputs of one snapshot instance, as the CPU engine derives them. +/// Sanitized surface inputs of one snapshot instance: its material program's constant block with the part tint, as +/// the CPU engine derives them (a program's per-hit values are not seen by the emissive light table). pub fn instance_inputs(snap: &RenderSnapshot, idx: usize) -> SurfaceInputs { let Some(inst) = snap.instances.get(idx) else { return SurfaceInputs::default().sanitized() }; - let params = snap - .materials - .get(inst.material.index()) - .or_else(|| snap.materials.get(snap.default_material.index())) - .map(|m| m.params) - .unwrap_or_default(); - surface_inputs(¶ms, inst.tint) + let material = snap.materials.get(inst.material.index()).or_else(|| snap.materials.get(snap.default_material.index())); + let Some(m) = material else { return surface_inputs(&fsh_scene::SurfaceParams::default(), inst.tint) }; + match inst.tint { + Some(t) => SurfaceInputs { base_color: t, ..m.program.base }.sanitized(), + None => m.program.base, + } } impl EmissiveTable { diff --git a/native/crates/fsh-render-gpu/src/host.rs b/native/crates/fsh-render-gpu/src/host.rs index ccc6e441..9941384f 100644 --- a/native/crates/fsh-render-gpu/src/host.rs +++ b/native/crates/fsh-render-gpu/src/host.rs @@ -1,8 +1,8 @@ use std::sync::Arc; -use fsh_accel::{GpuBvh, GpuNode, Instance as AccelInstance, MeshBvh, Scene}; +use fsh_accel::{GpuBvh, GpuInstanceGeometry, GpuNode, Instance as AccelInstance, MeshBvh, Scene}; use fsh_core::Rgb; -use fsh_materials::SurfaceInputs; +use fsh_materials::{SurfaceInputs, TextureSet}; use fsh_render_cpu::{surface_inputs, EnvImage, IntegratorSettings, PixelFilter}; use fsh_scene::{BackgroundMode, Mesh, Projection, RayVisibility, RenderCamera, RenderSnapshot, SurfaceParams}; @@ -11,11 +11,14 @@ use crate::emissive::EmissiveTable; use crate::env::{build_environment, EnvTables}; use crate::error::Result; use crate::layout::{ - BvhNode, Frame, Instance, Light, Material, Sobol, Triangle, Vertex, BG_COLOUR, BG_ENVIRONMENT, BG_TRANSPARENT, - COUNT_MASK, FILTER_BOX, FILTER_GAUSSIAN, FILTER_TENT, INST_TINT, MESH_BASE_LIMIT, MESH_BASE_SHIFT, M_CAMERA, M_DIFFUSE, - M_GLOSSY, M_SHADOW, M_TRANSMISSION, NONE, PROJ_ORTHOGRAPHIC, PROJ_PERSPECTIVE, + vertex_stride, BvhNode, Frame, Instance, Light, Material, Sobol, Triangle, Vertex, BG_COLOUR, BG_ENVIRONMENT, + BG_TRANSPARENT, COUNT_MASK, FILTER_BOX, FILTER_GAUSSIAN, FILTER_TENT, INST_NORMALS, INST_TANGENTS, INST_TINT, + INST_UV_SHIFT, MAT_PROGRAM, MAX_GPU_UV_SETS, MESH_BASE_LIMIT, MESH_BASE_SHIFT, M_CAMERA, M_DIFFUSE, M_GLOSSY, M_SHADOW, + M_TRANSMISSION, NONE, PROJ_ORTHOGRAPHIC, PROJ_PERSPECTIVE, }; use crate::lights::{LampSpec, LightTable}; +use crate::refusals::program_refusal; +use crate::texpack; /// A snapshot turned into the exact records the device receives, with nothing uploaded yet. #[derive(Clone)] @@ -35,10 +38,14 @@ pub struct HostScene { pub mesh_bases: bool, /// Upload records. pub triangles: Vec<Triangle>, - /// Upload records. + /// Upload records: vertex attribute slots (normals, uv sets, tangents) of every exported mesh that has any. pub vertices: Vec<Vertex>, - /// First vertex of each exported mesh (`bvh.meshes` order), `NONE` without authored normals. + /// First slot of each exported mesh (`bvh.meshes` order), `NONE` when it carries no attribute. pub vertex_bases: Vec<u32>, + /// Instance flag bits (`INST_NORMALS`, uv count, `INST_TANGENTS`) of each exported mesh's slots. + pub vertex_flags: Vec<u32>, + /// Per exported mesh: uv sets and tangents are packed because an instance of it runs a material program. + pub attributes: Vec<bool>, /// Upload records. pub instances: Vec<Instance>, /// Snapshot materials, then the built-in default, then the ground. @@ -53,10 +60,19 @@ pub struct HostScene { pub emissive: EmissiveTable, /// Samples emissive triangles as lights (the integrator setting of the same name). pub emissive_lights: bool, - /// The `tables` buffer: environment, then BSDF tables when present, then the emissive block. + /// The `tables` buffer: environment, then BSDF tables when present, then the texture block, then the program + /// blobs, then the emissive block. pub tables: Vec<f32>, /// Floats of `tables` before the emissive block (the part a light-only update keeps). pub tables_fixed: usize, + /// Float offset where the texture block starts (the end of the environment and BSDF tables). + pub textures_start: usize, + /// Float offset where the program blobs start (the end of the texture block). + pub programs_start: usize, + /// Float offset of the texture directory, `NONE` without textures. + pub texture_dir: u32, + /// Pixels of the snapshot's textures, in `RenderSnapshot::textures` order. + pub textures: Option<TextureSet>, /// Float offsets of the BSDF energy tables in `tables`: conductor, conductor average, dielectric, sheen. pub bsdf_offsets: [u32; 4], /// Float offset of the emissive block, `NONE` without one. @@ -122,17 +138,21 @@ pub fn material_record(s: &SurfaceInputs, eta: f32) -> Material { eta, program: NONE, flags: 0, + ..Material::default() } } -/// Material records: every snapshot material, then the built-in default (`len - 2`), then the ground (`len - 1`). +/// Material records: every snapshot material (its compiled program's constant block), then the built-in default +/// (`len - 2`), then the ground (`len - 1`). Program offsets are filled by `append_programs`. pub fn build_materials(snap: &RenderSnapshot) -> Vec<Material> { let mut out: Vec<Material> = snap .materials .iter() .map(|m| { - let s = surface_inputs(&m.params, None); - material_record(&s, fsh_materials::Bsdf::relative_ior(&s, 1.0)) + let s = m.program.base; + let mut r = material_record(&s, fsh_materials::Bsdf::relative_ior(&s, 1.0)); + r.set_optics(&fsh_render_cpu::surface_optics(&m.params)); + r }) .collect(); let d = surface_inputs(&SurfaceParams::default(), None); @@ -150,6 +170,32 @@ pub fn build_materials(snap: &RenderSnapshot) -> Vec<Material> { out } +/// Appends the `encode_f32()` blob of every snapshot material whose program varies and runs on the GPU to `tables`, +/// pointing its record's `program` at it and setting `MAT_PROGRAM`; materials sharing one program share one blob. +/// Programs the GPU cannot run (`program_refusal`) keep their constant block; `Refusals::check` reports them. +pub fn append_programs(snap: &RenderSnapshot, materials: &mut [Material], tables: &mut Vec<f32>) { + let mut done: Vec<(*const fsh_materials::Program, u32)> = Vec::new(); + for (rec, m) in materials.iter_mut().zip(&snap.materials) { + rec.program = NONE; + rec.flags &= !MAT_PROGRAM; + if m.program.is_constant() || program_refusal(&m.program).is_some() { + continue; + } + let key = Arc::as_ptr(&m.program); + let at = match done.iter().find(|(k, _)| *k == key) { + Some(&(_, at)) => at, + None => { + let at = tables.len() as u32; + tables.extend(m.program.encode_f32()); + done.push((key, at)); + at + } + }; + rec.program = at; + rec.flags |= MAT_PROGRAM; + } +} + fn material_index(snap: &RenderSnapshot, inst: &fsh_scene::Instance) -> u32 { let n = snap.materials.len(); if inst.material.index() < n { @@ -184,14 +230,66 @@ fn mark_mesh_bases(nodes: &mut [BvhNode], bvh: &GpuBvh) -> bool { ok } -/// Instance records joining the exported geometry with materials, tints and normal offsets. -fn instance_records(snap: &RenderSnapshot, bvh: &GpuBvh, ids: &[u32], vertex_bases: &[u32]) -> Vec<Instance> { +fn runs_program(snap: &RenderSnapshot, inst: &fsh_scene::Instance) -> bool { + snap.materials.get(material_index(snap, inst) as usize).is_some_and(|m| !m.program.is_constant()) +} + +/// Per exported mesh (`bvh.meshes` order): true when some instance placing it wears a material that runs a program, +/// so its uv sets and tangents are worth packing. +pub fn mesh_attributes(snap: &RenderSnapshot, meshes: usize, geo: &[GpuInstanceGeometry], ids: &[u32]) -> Vec<bool> { + let mut out = vec![false; meshes]; + for (g, &id) in geo.iter().zip(ids) { + if let (Some(o), Some(src)) = (out.get_mut(g.mesh as usize), snap.instances.get(id as usize)) { + *o |= runs_program(snap, src); + } + } + out +} + +/// Packs one mesh's vertex attribute slots; returns the instance flag bits that describe them (0: none packed). Uv +/// sets are packed as the mesh stores them (v pointing up, as the importers write them and the CPU reads them). +fn pack_vertices(m: &Mesh, attributes: bool, out: &mut Vec<Vertex>) -> u32 { + let n = m.positions.len(); + let normals = m.has_normals() && m.normals.len() == n; + let uv_sets = if attributes { m.uvs.iter().take(MAX_GPU_UV_SETS as usize).take_while(|s| s.len() == n).count() } else { 0 }; + let tangents = attributes && !m.tangents.is_empty() && m.tangents.len() == n; + if !normals && uv_sets == 0 && !tangents { + return 0; + } + out.reserve(n * vertex_stride(normals, uv_sets as u32, tangents) as usize); + for i in 0..n { + if normals { + let v = m.normals[i]; + out.push(Vertex { v: [v.x, v.y, v.z, 0.0] }); + } + for pair in (0..uv_sets).step_by(2) { + let a = m.uvs[pair][i]; + let b = if pair + 1 < uv_sets { m.uvs[pair + 1][i] } else { fsh_core::Vec2::ZERO }; + out.push(Vertex { v: [a.x, a.y, b.x, b.y] }); + } + if tangents { + let t = m.tangents[i]; + out.push(Vertex { v: [t.x, t.y, t.z, t.w] }); + } + } + let mut flags = (uv_sets as u32) << INST_UV_SHIFT; + if normals { + flags |= INST_NORMALS; + } + if tangents { + flags |= INST_TANGENTS; + } + flags +} + +/// Instance records joining the exported geometry with materials, tints and vertex attribute offsets. +fn instance_records(snap: &RenderSnapshot, bvh: &GpuBvh, ids: &[u32], vertex_bases: &[u32], vertex_flags: &[u32]) -> Vec<Instance> { bvh.instances .iter() .zip(ids) .map(|(g, &id)| { let src = &snap.instances[id as usize]; - let mut flags = g.flags; + let mut flags = g.flags | vertex_flags[g.mesh as usize]; let mut tint = [0.0; 3]; if let Some(t) = src.tint { flags |= INST_TINT; @@ -220,6 +318,7 @@ impl HostScene { pub fn build( snap: &RenderSnapshot, image: Option<&EnvImage>, + textures: Option<&TextureSet>, settings: &IntegratorSettings, previous: Option<&HostScene>, ) -> Result<Self> { @@ -245,16 +344,15 @@ impl HostScene { _ => [0, 0, 0], } })?; + let attributes = mesh_attributes(snap, bvh.meshes.len(), &bvh.instances, &instance_ids); let mut vertices = Vec::new(); let mut vertex_bases = Vec::with_capacity(bvh.meshes.len()); - for r in &bvh.meshes { - match mesh_for(&meshes, &r.bvh) { - Some(m) if m.has_normals() => { - vertex_bases.push(vertices.len() as u32); - vertices.extend(m.normals.iter().map(|n| Vertex { normal: n.to_array(), pad: 0.0 })); - } - _ => vertex_bases.push(NONE), - } + let mut vertex_flags = Vec::with_capacity(bvh.meshes.len()); + for (r, &want) in bvh.meshes.iter().zip(&attributes) { + let start = vertices.len() as u32; + let flags = mesh_for(&meshes, &r.bvh).map_or(0, |m| pack_vertices(m, want, &mut vertices)); + vertex_bases.push(if flags == 0 { NONE } else { start }); + vertex_flags.push(flags); } let mut nodes: Vec<BvhNode> = bvh.nodes.iter().map(node_record).collect(); let mesh_bases = mark_mesh_bases(&mut nodes, &bvh); @@ -263,7 +361,7 @@ impl HostScene { .iter() .map(|t| Triangle { c0: t.c0, i0: t.w0, c1: t.c1, i1: t.w1, c2: t.c2, i2: t.w2 }) .collect(); - let instances = instance_records(snap, &bvh, &instance_ids, &vertex_bases); + let instances = instance_records(snap, &bvh, &instance_ids, &vertex_bases, &vertex_flags); let materials = build_materials(snap); let (env, sun, tables, bsdf_offsets) = Self::environment(snap, image); let tables_fixed = tables.len(); @@ -277,6 +375,8 @@ impl HostScene { triangles, vertices, vertex_bases, + vertex_flags, + attributes, instances, materials, lights: LightTable::default(), @@ -286,11 +386,16 @@ impl HostScene { emissive_lights: settings.emissive_lights, tables, tables_fixed, + textures_start: tables_fixed, + programs_start: tables_fixed, + texture_dir: NONE, + textures: textures.cloned(), bsdf_offsets, emissive_offset: NONE, sobol: sobol_table(), frame: Frame::default(), }; + s.material_tail(snap); s.relight(snap); s.frame = s.make_frame(snap, settings); Ok(s) @@ -345,6 +450,9 @@ impl HostScene { return Ok(false); } let Ok((top, geo)) = accel.gpu_export_top(&self.bvh.meshes) else { return Ok(false) }; + if mesh_attributes(snap, self.bvh.meshes.len(), &geo, &ids) != self.attributes { + return Ok(false); + } for (i, n) in top.iter().enumerate() { self.nodes[i] = node_record(n); } @@ -354,24 +462,63 @@ impl HostScene { self.bvh.top_count = top.len() as u32; self.bvh.nodes[..top.len()].copy_from_slice(&top); self.bvh.instances = geo; - self.instances = instance_records(snap, &self.bvh, &ids, &self.vertex_bases); + self.instances = instance_records(snap, &self.bvh, &ids, &self.vertex_bases, &self.vertex_flags); self.accel = accel; Ok(true) } - /// Redoes material records (the caller relights: emission may have changed). + /// True when the snapshot wants the same meshes' uv sets and tangents packed as this scene has (a material that + /// starts or stops running a program can change that, and then the vertex slots must be rebuilt). + pub fn attributes_match(&self, snap: &RenderSnapshot) -> bool { + mesh_attributes(snap, self.bvh.meshes.len(), &self.bvh.instances, &self.instance_ids) == self.attributes + } + + /// Rewrites everything after the environment and BSDF tables up to the emissive block: the texture block, then + /// the program blobs (material records get their program offsets). + fn material_tail(&mut self, snap: &RenderSnapshot) { + self.tables.truncate(self.textures_start); + self.texture_dir = texpack::append(self.textures.as_ref(), &mut self.tables); + self.programs_start = self.tables.len(); + self.programs(snap); + } + + fn programs(&mut self, snap: &RenderSnapshot) { + self.tables.truncate(self.programs_start); + append_programs(snap, &mut self.materials, &mut self.tables); + self.tables_fixed = self.tables.len(); + } + + /// Redoes material records and program blobs (the caller relights: emission may have changed, and writes + /// `tables` from `programs_start`). pub fn update_materials(&mut self, snap: &RenderSnapshot) { self.materials = build_materials(snap); + self.programs(snap); + } + + /// Replaces the texture pixels: rewrites the texture block, the program blobs and the emissive block (the caller + /// writes `tables` from `textures_start` and the material records, whose program offsets moved). + pub fn set_textures(&mut self, snap: &RenderSnapshot, textures: Option<TextureSet>) { + self.textures = textures; + self.material_tail(snap); + self.relight(snap); + } + + /// Floats `tables` would need with `textures` in place of the current pixels. + pub fn tables_len_with(&self, textures: Option<&TextureSet>) -> usize { + let block = self.programs_start - self.textures_start; + self.tables.len() - block + texpack::block_len(textures) } - /// Redoes the environment tables, the emissive table and the light table. + /// Redoes the environment tables, everything after them (textures, programs: material records get new program + /// offsets), the emissive table and the light table. pub fn update_lighting(&mut self, snap: &RenderSnapshot, image: Option<&EnvImage>) { let (env, sun, tables, bsdf_offsets) = Self::environment(snap, image); self.env = env; self.sun = sun; self.bsdf_offsets = bsdf_offsets; - self.tables_fixed = tables.len(); + self.textures_start = tables.len(); self.tables = tables; + self.material_tail(snap); self.relight(snap); } @@ -440,6 +587,7 @@ impl HostScene { f.node_count = self.nodes.len() as u32; f.triangle_count = self.triangles.len() as u32; f.stack_bound = self.bvh.stack_bound; + f.textures = self.texture_dir; BsdfTables::set_frame(self.bsdf_offsets, f); } } diff --git a/native/crates/fsh-render-gpu/src/layout.rs b/native/crates/fsh-render-gpu/src/layout.rs index fa35adfe..4ed3ee44 100644 --- a/native/crates/fsh-render-gpu/src/layout.rs +++ b/native/crates/fsh-render-gpu/src/layout.rs @@ -41,7 +41,7 @@ pub const B_SOBOL: u32 = 1; pub const B_NODES: u32 = 2; /// Group 0: `array<Triangle>`. pub const B_TRIS: u32 = 3; -/// Group 0: `array<vec4<f32>>` vertex normals. +/// Group 0: `array<Vertex>` vertex attribute slots (normals, uv sets, tangents). pub const B_VERTS: u32 = 4; /// Group 0: `array<Instance>`. pub const B_INSTANCES: u32 = 5; @@ -89,6 +89,19 @@ pub const INST_FLIP: u32 = 1 << 0; pub const INST_IN_TREE: u32 = 1 << 1; /// `Instance::flags`: `tint` replaces the material's base colour. pub const INST_TINT: u32 = 1 << 2; +/// `Instance::flags`: the mesh's vertex slots start with authored normals. +pub const INST_NORMALS: u32 = 1 << 3; +/// `Instance::flags`: shift of the 3-bit count of uv sets in the mesh's vertex slots (0..=4). +pub const INST_UV_SHIFT: u32 = 4; +/// `Instance::flags`: mask of the uv set count after the shift. +pub const INST_UV_MASK: u32 = 7; +/// `Instance::flags`: the mesh's vertex slots end with a tangent and sign. +pub const INST_TANGENTS: u32 = 1 << 7; +/// Uv sets the vertex record carries; a program reading more is refused (`material_program`). +pub const MAX_GPU_UV_SETS: u32 = 4; + +/// `Material::flags`: the material runs the program at `Material::program` (a float offset into `tables`). +pub const MAT_PROGRAM: u32 = 1 << 0; /// Visibility bit: camera rays. pub const M_CAMERA: u32 = 1; @@ -142,7 +155,8 @@ pub const BSDF_NX: u32 = 16; /// BSDF table: sheen roughness rows. pub const BSDF_NS: u32 = 16; -/// Camera, integrator, environment, counts and the render region; uniform at group 0 binding 0 (288 bytes). +/// Camera, integrator, environment, counts, the render region and the texture directory offset (`textures`, a float +/// offset into `tables`, `NONE` without textures); uniform at group 0 binding 0 (304 bytes). #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)] pub struct Frame { @@ -208,6 +222,10 @@ pub struct Frame { pub region_y0: u32, pub region_x1: u32, pub region_y1: u32, + pub textures: u32, + pub pad0: u32, + pub pad1: u32, + pub pad2: u32, } /// Byte offset of `Frame::samples`, written alone before each pass. @@ -244,12 +262,19 @@ pub struct Triangle { pub i2: u32, } -/// One authored vertex normal (16 bytes, w = 0). +/// One 16-byte vertex attribute slot. A mesh's vertices are `stride` slots each (`vertex_stride`), in this order and +/// only for what the mesh carries: authored normal (xyz, w 0), uv sets 0 and 1 (u0, v0, u1, v1), uv sets 2 and 3, +/// tangent (xyz, handedness sign in w). Uvs are packed as the mesh stores them (v pointing up). The instance flags +/// say which are present. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)] pub struct Vertex { - pub normal: [f32; 3], - pub pad: f32, + pub v: [f32; 4], +} + +/// Slots per vertex for a mesh with the given attributes. +pub fn vertex_stride(normals: bool, uv_sets: u32, tangents: bool) -> u32 { + u32::from(normals) + uv_sets.min(MAX_GPU_UV_SETS).div_ceil(2) + u32::from(tangents) } /// One instance (128 bytes). @@ -266,7 +291,8 @@ pub struct Instance { pub flags: u32, } -/// Sanitized surface inputs of one material (144 bytes), mirroring fsh_materials::SurfaceInputs. +/// Sanitized surface inputs of one material (160 bytes), mirroring fsh_materials::SurfaceInputs, then the thin film +/// and dispersion of fsh_materials::Optics. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)] pub struct Material { @@ -294,6 +320,20 @@ pub struct Material { pub eta: f32, pub program: u32, pub flags: u32, + pub film_weight: f32, + pub film_thickness: f32, + pub film_ior: f32, + pub dispersion: f32, +} + +impl Material { + /// Writes the thin film and dispersion of `o`. + pub fn set_optics(&mut self, o: &fsh_materials::Optics) { + self.film_weight = o.film_weight; + self.film_thickness = o.film_thickness; + self.film_ior = o.film_ior; + self.dispersion = o.dispersion; + } } /// One analytic lamp with its selection probability (96 bytes). @@ -353,13 +393,13 @@ pub struct AccumPixel { } const _: () = { - assert!(std::mem::size_of::<Frame>() == 288); + assert!(std::mem::size_of::<Frame>() == 304); assert!(std::mem::size_of::<Sobol>() == 8192); assert!(std::mem::size_of::<BvhNode>() == 32); assert!(std::mem::size_of::<Triangle>() == 48); assert!(std::mem::size_of::<Vertex>() == 16); assert!(std::mem::size_of::<Instance>() == 128); - assert!(std::mem::size_of::<Material>() == 144); + assert!(std::mem::size_of::<Material>() == 160); assert!(std::mem::size_of::<Light>() == 96); assert!(std::mem::size_of::<Band>() == 48); assert!(std::mem::size_of::<AccumPixel>() == 64); diff --git a/native/crates/fsh-render-gpu/src/lib.rs b/native/crates/fsh-render-gpu/src/lib.rs index 4adfb292..32ae4a5a 100644 --- a/native/crates/fsh-render-gpu/src/lib.rs +++ b/native/crates/fsh-render-gpu/src/lib.rs @@ -18,6 +18,7 @@ mod renderer; mod scene; pub mod shaders; mod sky; +pub mod texpack; mod traversal; #[cfg(feature = "validate")] pub mod validate; @@ -28,14 +29,16 @@ pub use context::{AdapterReport, ContextOptions, GpuContext, LimitsReport}; pub use emissive::{instance_inputs, EmissiveTable}; pub use env::{build_environment, EnvTables}; pub use error::{GpuError, Result}; -pub use host::{build_materials, material_record, set_camera, set_settings, sobol_table, HostScene}; +pub use host::{append_programs, build_materials, material_record, mesh_attributes, set_camera, set_settings, sobol_table, HostScene}; #[cfg(not(target_arch = "wasm32"))] pub use hwaccel::{hw_layout_entries, HwAccel}; pub use lights::{LampSpec, LightTable}; pub use pipeline::{cache_file, CacheStatus, Constants, Kernel}; -pub use refusals::{Refusal, RefusalKind, Refusals, SizeEstimate, MAX_SIDE}; +pub use refusals::{ + program_refusal, Refusal, RefusalKind, Refusals, SizeEstimate, GPU_OPCODES, GPU_PROCEDURALS, MAX_SIDE, OP_LABEL, +}; pub use renderer::{develop_means, Features, GpuRenderer, RendererOptions, ADAPTIVE_ENTRY, DEFAULT_TIME_BUDGET, KERNEL_ENTRY}; -pub use scene::{scene_layout_entries, Changes, GpuScene}; +pub use scene::{scene_layout_entries, Changes, GpuScene, TEXTURE_MEMORY}; pub use traversal::{AccelReport, GpuStats, Traversal, TraversalMode, TraversalReport, TRAVERSAL_ENV}; /// Plan phases still ahead of the GPU engine. @@ -44,13 +47,16 @@ pub const ARRIVES_IN: &str = "P3 GPU tracer"; /// What the GPU engine does not do yet or has not been shown to do, each with the plan phase it belongs to. pub fn refusals() -> Vec<&'static str> { vec![ - "no bytecode material interpreter: materials are parameter records (P3 GPU tracer)", + "material programs (textures, procedurals, graphs, labels) run in a WGSL interpreter; a program that fails its \ + check or names a procedural without a WGSL port is refused (material_program) and renders on the CPU \ + (P7 Materials)", + "texture footprints follow one ray cone per path (no curvature spread at bounces), so mip choices after a \ + bounce are approximate (P7 Materials)", "hardware ray-query traversal has run only on a software Vulkan implementation, never on ray-tracing hardware; \ the software BVH traversal is the fallback everywhere (P3 GPU tracer)", "no ray queries in WebAssembly: WebGPU offers none, so the browser engine always uses the software traversal \ (P4 Live viewport)", "the megakernel has not run in a browser here: software WebGPU runs out of memory compiling it (P4 Live viewport)", - "no GPU node-graph materials (P7 Materials)", "no GPU denoiser (P12 Denoise)", "no GPU nested media, subsurface, volumes or spectral mode (P15 Advanced transport)", ] diff --git a/native/crates/fsh-render-gpu/src/refusals.rs b/native/crates/fsh-render-gpu/src/refusals.rs index 3bd73872..25312826 100644 --- a/native/crates/fsh-render-gpu/src/refusals.rs +++ b/native/crates/fsh-render-gpu/src/refusals.rs @@ -1,9 +1,12 @@ use core::fmt; +use fsh_materials::{Op, Program, REGISTERS}; use fsh_scene::RenderSnapshot; use crate::context::LimitsReport; -use crate::layout::{AccumPixel, BvhNode, Instance, Light, Material, Triangle, Vertex, TRACE_STACK}; +use crate::layout::{ + vertex_stride, AccumPixel, BvhNode, Instance, Light, Material, Triangle, Vertex, MAX_GPU_UV_SETS, TRACE_STACK, +}; /// Largest image side, as on the CPU engine. pub const MAX_SIDE: u32 = 16384; @@ -48,7 +51,7 @@ pub struct SizeEstimate { pub nodes: u64, /// Triangles. pub triangles: u64, - /// Vertex normals. + /// Vertex attribute slots (upper bound: every normal, uv set and tangent packed). pub vertices: u64, /// Instance records. pub instances: u64, @@ -76,9 +79,8 @@ impl SizeEstimate { seen.push(k); if let Some(m) = s.meshes.get(k) { tris += (m.indices.len() / 3) as u64; - if m.has_normals() { - verts += m.normals.len() as u64; - } + let stride = vertex_stride(m.has_normals(), m.uvs.len() as u32, !m.tangents.is_empty()); + verts += m.positions.len() as u64 * stride as u64; } } let n_inst = s.instances.len() as u64; @@ -96,10 +98,64 @@ impl SizeEstimate { } } +/// Procedural kinds the WGSL port runs, bit n for `ProcKind` n (all ten: procedural.wgsl carries every kind). +pub const GPU_PROCEDURALS: u32 = 0x3ff; +/// Opcodes program.wgsl runs, bit n for opcode n: 0..=23 of the materials contract and 24 (`Label`). A program using +/// any other opcode is refused; `validate::program_report` checks the WGSL constants against this mask. +pub const GPU_OPCODES: u32 = (1 << 25) - 1; +/// Opcode number of `Label` (written by the labels compiler; not yet an `Op` variant on every branch). +pub const OP_LABEL: u32 = 24; + +/// Why the GPU interpreter cannot run a material program, or `None` when it can (constant programs always can). +pub fn program_refusal(p: &Program) -> Option<String> { + if p.is_constant() { + return None; + } + if let Err(e) = p.check() { + return Some(e.to_string()); + } + if p.registers as usize > REGISTERS { + return Some(format!("it uses {} registers, the GPU interpreter holds {REGISTERS}", p.registers)); + } + for i in &p.code { + let op = i.op as u32; + if op >= 32 || GPU_OPCODES & (1 << op) == 0 { + return Some(format!("opcode {} ({op}) has no GPU port", i.op.name())); + } + match i.op { + Op::Proc if i.flags >= 32 || GPU_PROCEDURALS & (1u32 << i.flags) == 0 => { + return Some(format!("procedural kind {} has no GPU port", i.flags)); + } + Op::Input if i.flags & 15 == fsh_materials::program::input::UV && i.a >= MAX_GPU_UV_SETS => { + return Some(format!("it reads uv set {}, the GPU vertex record carries {MAX_GPU_UV_SETS}", i.a)); + } + _ => {} + } + } + None +} + +fn program_refusals(s: &RenderSnapshot, list: &mut Vec<Refusal>) { + let mut used: Vec<usize> = s.instances.iter().map(|i| i.material.index()).collect(); + used.push(s.default_material.index()); + used.sort_unstable(); + used.dedup(); + for m in used.iter().filter_map(|&k| s.materials.get(k)) { + if let Some(why) = program_refusal(&m.program) { + list.push(Refusal { + kind: RefusalKind::Feature, + code: "material_program", + message: format!("material \"{}\" has a program the GPU cannot run: {why}", m.name), + }); + } + } +} + impl Refusals { /// Checks a snapshot against what the GPU path runs and, when given, the device's limits. pub fn check(s: &RenderSnapshot, limits: Option<&LimitsReport>) -> Self { let mut list = Vec::new(); + program_refusals(s, &mut list); let limit = |code: &'static str, message: String| Refusal { kind: RefusalKind::Limit, code, message }; let (w, h) = (s.render.width, s.render.height); if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { @@ -111,7 +167,7 @@ impl Refusals { for (code, name, bytes) in [ ("nodes", "BVH nodes", e.nodes), ("triangles", "triangles", e.triangles), - ("vertices", "vertex normals", e.vertices), + ("vertices", "vertex attributes", e.vertices), ("instances", "instance records", e.instances), ("materials", "material records", e.materials), ("lights", "light records", e.lights), diff --git a/native/crates/fsh-render-gpu/src/renderer.rs b/native/crates/fsh-render-gpu/src/renderer.rs index 05601483..034d9339 100644 --- a/native/crates/fsh-render-gpu/src/renderer.rs +++ b/native/crates/fsh-render-gpu/src/renderer.rs @@ -12,10 +12,11 @@ use crate::accum::{Accumulator, GpuFramebuffer}; use crate::context::GpuContext; use crate::error::{GpuError, Result}; use crate::host::HostScene; -use crate::layout::{LIGHT_EMISSIVE, WORKGROUP_X, WORKGROUP_Y}; +use crate::layout::{INST_NORMALS, LIGHT_EMISSIVE, MAT_PROGRAM, WORKGROUP_X, WORKGROUP_Y}; use crate::pipeline::{CacheStatus, Constants, Kernel}; use crate::refusals::{Refusal, RefusalKind, Refusals}; -use crate::scene::{Changes, GpuScene}; +use crate::scene::{Changes, GpuScene, TEXTURE_MEMORY}; +use fsh_materials::TextureSet; use crate::traversal::{GpuStats, Traversal, TraversalMode, TraversalReport}; /// Entry file of the path tracing megakernel `render_pass` dispatches. @@ -39,38 +40,55 @@ pub struct Features { pub catcher: bool, /// Some mesh has authored normals: `USE_NORMALS`. pub normals: bool, + /// Some material runs a program (textures, procedurals, graphs, labels): `USE_PROGRAMS`. The interpreter is + /// compiled out otherwise, so a material that starts running a program in a scene without one compiles a kernel. + pub programs: bool, } impl Features { /// Every feature on: the kernel that runs any scene. - pub const ALL: Self = Self { lamps: true, catcher: true, normals: true }; + pub const ALL: Self = Self { lamps: true, catcher: true, normals: true, programs: true }; /// Every feature off; as `RendererOptions::features` it asks for exactly the scene's own variant. - pub const NONE: Self = Self { lamps: false, catcher: false, normals: false }; + pub const NONE: Self = Self { lamps: false, catcher: false, normals: false, programs: false }; /// The features a host scene uses. pub fn of(host: &HostScene, snapshot: &RenderSnapshot) -> Self { Self { lamps: host.lights.records.iter().any(|r| r.kind != LIGHT_EMISSIVE), catcher: snapshot.ground.shadow_catcher, - normals: !host.vertices.is_empty(), + normals: host.vertex_flags.iter().any(|f| f & INST_NORMALS != 0), + programs: host.materials.iter().any(|m| m.flags & MAT_PROGRAM != 0), } } /// True when a kernel built for `self` renders a scene that uses `need` (every feature `need` has is on). pub fn covers(&self, need: &Features) -> bool { - (self.lamps || !need.lamps) && (self.catcher || !need.catcher) && (self.normals || !need.normals) + (self.lamps || !need.lamps) + && (self.catcher || !need.catcher) + && (self.normals || !need.normals) + && (self.programs || !need.programs) } /// The features on in either. pub fn union(&self, other: &Features) -> Self { - Self { lamps: self.lamps || other.lamps, catcher: self.catcher || other.catcher, normals: self.normals || other.normals } + Self { + lamps: self.lamps || other.lamps, + catcher: self.catcher || other.catcher, + normals: self.normals || other.normals, + programs: self.programs || other.programs, + } } /// The override constants of this specialisation. pub fn constants(&self) -> Constants { let b = |v: bool| if v { 1.0 } else { 0.0 }; - vec![("USE_LAMPS", b(self.lamps)), ("USE_CATCHER", b(self.catcher)), ("USE_NORMALS", b(self.normals))] + vec![ + ("USE_LAMPS", b(self.lamps)), + ("USE_CATCHER", b(self.catcher)), + ("USE_NORMALS", b(self.normals)), + ("USE_PROGRAMS", b(self.programs)), + ] } } @@ -470,6 +488,32 @@ impl GpuRenderer { /// Moves to a new snapshot, uploading only what changed; resets accumulation unless nothing but the display changed. pub fn set_snapshot(&mut self, snapshot: Arc<RenderSnapshot>) -> Result<Changes> { + let changes = self.apply_snapshot(snapshot)?; + self.reset(); + Ok(changes) + } + + /// Moves to a snapshot that differs from the current one only in the materials or part colours of `instances` + /// (snapshot indices; same meshes, placement, lights, environment and render settings), clearing accumulation + /// only over the film rectangle those parts covered, grown by `pad` pixels. Returns the cleared rectangle, `None` + /// when no pixel showed them. + #[cfg(not(target_arch = "wasm32"))] + pub fn update_region(&mut self, snapshot: Arc<RenderSnapshot>, instances: &[u32], pad: u32) -> Result<Option<PixelRect>> { + let rect = if instances.is_empty() { None } else { self.instances_rect(instances)? }; + let (fw, fh) = self.film_size(); + self.apply_snapshot(snapshot)?; + if self.film_size() != (fw, fh) { + self.reset(); + return Ok(Some(PixelRect { x0: 0, y0: 0, x1: fw, y1: fh })); + } + let rect = rect.map(|q| q.padded(pad, fw, fh)); + if let Some(q) = rect { + self.reset_region(q); + } + Ok(rect) + } + + fn apply_snapshot(&mut self, snapshot: Arc<RenderSnapshot>) -> Result<Changes> { let limits = crate::context::LimitsReport::from(&self.ctx.limits()); let mut refusals = Refusals::check(&snapshot, Some(&limits)); let blocking = refusals.blocking(); @@ -487,6 +531,7 @@ impl GpuRenderer { if let Some(r) = Refusals::stack(self.scene.host().bvh.stack_bound) { refusals.list.push(r); } + refusals.list.extend(self.refusals.list.iter().filter(|r| r.code == TEXTURE_MEMORY).cloned()); self.refusals = refusals; let blocking = self.refusals.blocking(); if !blocking.is_empty() { @@ -500,7 +545,6 @@ impl GpuRenderer { self.refit_film()?; self.specialise()?; self.refresh_refusals(); - self.reset(); Ok(changes) } @@ -527,6 +571,28 @@ impl GpuRenderer { c } + /// Supplies the pixels of the textures the snapshot's material programs sample (`RenderSnapshot::textures` order, + /// as the engine's texture loader builds them for the CPU renderer), or clears them with `None` (every lookup then + /// gives its fallback); resets accumulation. A set whose texels do not fit the `tables` binding with the lighting + /// tables and programs is refused (Limit code `texture_memory` in `refusals()`), keeping the current pixels. + pub fn set_textures(&mut self, textures: Option<TextureSet>) -> Changes { + self.refusals.list.retain(|r| r.code != TEXTURE_MEMORY); + match self.scene.set_textures(textures) { + Ok(c) => { + self.reset(); + c + } + Err(GpuError::Refused(list)) => { + self.refusals.list.extend(list); + Changes::default() + } + Err(e) => { + self.refusals.list.push(Refusal { kind: RefusalKind::Limit, code: TEXTURE_MEMORY, message: e.to_string() }); + Changes::default() + } + } + } + /// Moves the camera: writes only the camera block of the frame uniform (76 bytes); resets accumulation. pub fn update_camera(&mut self, camera: &RenderCamera) -> Changes { self.camera = *camera; diff --git a/native/crates/fsh-render-gpu/src/scene.rs b/native/crates/fsh-render-gpu/src/scene.rs index e6d695b1..844d1069 100644 --- a/native/crates/fsh-render-gpu/src/scene.rs +++ b/native/crates/fsh-render-gpu/src/scene.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use bytemuck::Pod; +use fsh_materials::TextureSet; use fsh_render_cpu::{EnvImage, IntegratorSettings}; use fsh_scene::{RenderCamera, RenderSnapshot}; @@ -9,7 +10,7 @@ use crate::error::{GpuError, Result}; use crate::host::{set_camera_film, set_settings, HostScene}; use crate::layout::{ BvhNode, Frame, Instance, Triangle, Vertex, B_FRAME, B_INSTANCES, B_LIGHTS, B_MATERIALS, B_NODES, B_SOBOL, B_TABLES, - B_TRIS, B_VERTS, FRAME_ADAPTIVE, FRAME_CAMERA_BYTES, FRAME_HW_TLAS, FRAME_REGION, FRAME_SAMPLES_OFFSET, + B_TRIS, B_VERTS, FRAME_ADAPTIVE, FRAME_CAMERA_BYTES, FRAME_HW_TLAS, FRAME_REGION, FRAME_SAMPLES_OFFSET, NONE, }; const RUN_FLAGS: u32 = FRAME_ADAPTIVE | FRAME_REGION; @@ -41,6 +42,17 @@ struct Slot { size: u64, } +/// Refusal code of a texture set that does not fit the `tables` binding with everything else in it. +pub const TEXTURE_MEMORY: &str = "texture_memory"; + +fn texture_refusal(bytes: u64, bind: u64) -> Refusal { + Refusal { + kind: RefusalKind::Limit, + code: TEXTURE_MEMORY, + message: format!("textures, programs and lighting tables need {bytes} bytes, the device binds at most {bind}"), + } +} + fn padded<T: Pod + Default>(v: &[T]) -> Vec<u8> { if v.is_empty() { bytemuck::bytes_of(&T::default()).to_vec() @@ -132,9 +144,9 @@ fn slot_bytes(h: &HostScene) -> [Vec<u8>; 7] { impl GpuScene { /// Builds the host records and uploads everything; refuses when a buffer exceeds the device's binding limit. pub fn new(ctx: Arc<GpuContext>, snapshot: Arc<RenderSnapshot>, image: Option<EnvImage>, settings: IntegratorSettings) -> Result<Self> { - let host = HostScene::build(&snapshot, image.as_ref(), &settings, None)?; + let host = HostScene::build(&snapshot, image.as_ref(), None, &settings, None)?; let bytes = slot_bytes(&host); - Self::check_sizes(&ctx, &bytes)?; + Self::check_sizes(&ctx, &bytes, false)?; let device = ctx.device(); let mk = |label: &str, data: &[u8], usage: wgpu::BufferUsages| { let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: data.len() as u64, usage: usage | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); @@ -149,16 +161,19 @@ impl GpuScene { Ok(Self { ctx, host, snapshot, image, settings, frame, sobol, slots, layout, group, revision: 0, hw_tlas: false, run_flags: 0, region: [0; 4] }) } - fn check_sizes(ctx: &GpuContext, bytes: &[Vec<u8>; 7]) -> Result<()> { + fn check_sizes(ctx: &GpuContext, bytes: &[Vec<u8>; 7], textures: bool) -> Result<()> { let bind = ctx.limits().max_storage_buffer_binding_size; let over: Vec<Refusal> = bytes .iter() .zip(SLOT_NAMES) .filter(|(b, _)| b.len() as u64 > bind) - .map(|(b, name)| Refusal { - kind: RefusalKind::Limit, - code: name, - message: format!("{name} need {} bytes, the device binds at most {bind}", b.len()), + .map(|(b, name)| match name { + "tables" if textures => texture_refusal(b.len() as u64, bind), + _ => Refusal { + kind: RefusalKind::Limit, + code: name, + message: format!("{name} need {} bytes, the device binds at most {bind}", b.len()), + }, }) .collect(); if over.is_empty() { @@ -218,12 +233,11 @@ impl GpuScene { } } - fn write_tables_tail(&mut self, changes: &mut Changes) { - let fixed = self.host.tables_fixed; + fn write_tables_from(&mut self, from: usize, changes: &mut Changes) { let total = (self.host.tables.len().max(1) * 4) as u64; - if total <= self.slots[S_TABLES].size && fixed < self.host.tables.len() { - let tail = bytemuck::cast_slice(&self.host.tables[fixed..]).to_vec(); - self.ctx.queue().write_buffer(&self.slots[S_TABLES].buffer, (fixed * 4) as u64, &tail); + if total <= self.slots[S_TABLES].size && from < self.host.tables.len() { + let tail = bytemuck::cast_slice(&self.host.tables[from..]).to_vec(); + self.ctx.queue().write_buffer(&self.slots[S_TABLES].buffer, (from * 4) as u64, &tail); changes.bytes += tail.len() as u64; } else if total > self.slots[S_TABLES].size { let t = padded(&self.host.tables); @@ -231,9 +245,19 @@ impl GpuScene { } } + fn write_tables_tail(&mut self, changes: &mut Changes) { + self.write_tables_from(self.host.tables_fixed, changes); + } + + fn write_materials(&mut self, changes: &mut Changes) { + let m = padded(&self.host.materials); + self.write_slot(S_MATERIALS, &m, changes); + changes.materials = true; + } + fn upload_all(&mut self, changes: &mut Changes) -> Result<()> { let bytes = slot_bytes(&self.host); - Self::check_sizes(&self.ctx, &bytes)?; + Self::check_sizes(&self.ctx, &bytes, self.host.texture_dir != NONE)?; for (i, b) in bytes.iter().enumerate() { self.write_slot(i, b, changes); } @@ -271,26 +295,32 @@ impl GpuScene { c.instances = true; } } + if !full && !materials_same && !self.host.attributes_match(&snapshot) { + full = true; + } if full { - self.host = HostScene::build(&snapshot, self.image.as_ref(), &self.settings, Some(&self.host))?; + let textures = self.host.textures.clone(); + self.host = HostScene::build(&snapshot, self.image.as_ref(), textures.as_ref(), &self.settings, Some(&self.host))?; self.upload_all(&mut c)?; c.environment = true; } else { + let mut tables_from = None; if !materials_same { self.host.update_materials(&snapshot); - let m = padded(&self.host.materials); - self.write_slot(S_MATERIALS, &m, &mut c); - c.materials = true; + self.write_materials(&mut c); + tables_from = Some(self.host.programs_start); } let relight = !lights_same || !materials_same || !instances_same; if !env_same { self.host.update_lighting(&snapshot, self.image.as_ref()); let t = padded(&self.host.tables); self.write_slot(S_TABLES, &t, &mut c); + self.write_materials(&mut c); c.environment = true; } else if relight { self.host.update_lights(&snapshot); - self.write_tables_tail(&mut c); + let from = tables_from.unwrap_or(self.host.tables_fixed); + self.write_tables_from(from, &mut c); } if !env_same || relight { let l = padded(&self.host.light_records()); @@ -312,6 +342,7 @@ impl GpuScene { self.host.update_lighting(&self.snapshot, self.image.as_ref()); let t = padded(&self.host.tables); self.write_slot(S_TABLES, &t, &mut c); + self.write_materials(&mut c); let l = padded(&self.host.light_records()); self.write_slot(S_LIGHTS, &l, &mut c); c.environment = true; @@ -324,6 +355,31 @@ impl GpuScene { c } + /// Supplies (or clears) the texture pixels the snapshot's programs sample, in `RenderSnapshot::textures` order: + /// rewrites `tables` from the texture block on, the material records (their program offsets move) and the + /// lights. Refuses with `texture_memory`, keeping the current pixels, when `tables` would not fit one binding. + pub fn set_textures(&mut self, textures: Option<TextureSet>) -> Result<Changes> { + let bind = self.ctx.limits().max_storage_buffer_binding_size; + let bytes = (self.host.tables_len_with(textures.as_ref()).max(1) * 4) as u64; + if bytes > bind { + return Err(GpuError::Refused(vec![texture_refusal(bytes, bind)])); + } + let mut c = Changes::default(); + self.host.set_textures(&self.snapshot, textures); + let from = self.host.textures_start; + self.write_tables_from(from, &mut c); + self.write_materials(&mut c); + let l = padded(&self.host.light_records()); + self.write_slot(S_LIGHTS, &l, &mut c); + c.lights = true; + let mut f = self.host.frame; + self.host.scene_fields(&mut f, &self.snapshot); + self.host.frame = f; + self.write_frame(&mut c); + self.finish(&mut c); + Ok(c) + } + /// Sets the camera and the film size (`width` x `height` film pixels framing the output `aspect`) and rewrites the /// whole frame uniform. pub fn update_camera(&mut self, camera: &RenderCamera, width: u32, height: u32, aspect: f32) -> Changes { diff --git a/native/crates/fsh-render-gpu/src/shaders.rs b/native/crates/fsh-render-gpu/src/shaders.rs index 7cf19800..0e1b730c 100644 --- a/native/crates/fsh-render-gpu/src/shaders.rs +++ b/native/crates/fsh-render-gpu/src/shaders.rs @@ -16,6 +16,9 @@ pub const SOURCES: &[(&str, &str)] = &[ ("trace.wgsl", include_str!("shaders/trace.wgsl")), ("traverse_hw.wgsl", include_str!("shaders/traverse_hw.wgsl")), ("trace_hw.wgsl", include_str!("shaders/trace_hw.wgsl")), + ("texture.wgsl", include_str!("shaders/texture.wgsl")), + ("procedural.wgsl", include_str!("shaders/procedural.wgsl")), + ("program.wgsl", include_str!("shaders/program.wgsl")), ("surface.wgsl", include_str!("shaders/surface.wgsl")), ("lights.wgsl", include_str!("shaders/lights.wgsl")), ("catcher.wgsl", include_str!("shaders/catcher.wgsl")), diff --git a/native/crates/fsh-render-gpu/src/shaders/bindings.wgsl b/native/crates/fsh-render-gpu/src/shaders/bindings.wgsl index 5f67adf5..c11ad7b5 100644 --- a/native/crates/fsh-render-gpu/src/shaders/bindings.wgsl +++ b/native/crates/fsh-render-gpu/src/shaders/bindings.wgsl @@ -10,6 +10,11 @@ const MASK_SHIFT: u32 = 8u; const INST_FLIP: u32 = 1u; const INST_IN_TREE: u32 = 2u; const INST_TINT: u32 = 4u; +const INST_NORMALS: u32 = 8u; +const INST_UV_SHIFT: u32 = 4u; +const INST_UV_MASK: u32 = 7u; +const INST_TANGENTS: u32 = 128u; +const MAT_PROGRAM: u32 = 1u; const M_CAMERA: u32 = 1u; const M_SHADOW: u32 = 2u; @@ -115,6 +120,10 @@ struct Frame { region_y0: u32, region_x1: u32, region_y1: u32, + textures: u32, + pad0: u32, + pad1: u32, + pad2: u32, } struct Sobol { @@ -138,8 +147,7 @@ struct Triangle { } struct Vertex { - normal: vec3<f32>, - pad: f32, + v: vec4<f32>, } struct Instance { @@ -178,6 +186,10 @@ struct Material { eta: f32, program: u32, flags: u32, + film_weight: f32, + film_thickness: f32, + film_ior: f32, + dispersion: f32, } struct Light { @@ -297,6 +309,14 @@ fn instance_normal(inv: array<vec4<f32>, 3>, n: vec3<f32>) -> vec3<f32> { ); } +fn vertex_uv_sets(flags: u32) -> u32 { + return (flags >> INST_UV_SHIFT) & INST_UV_MASK; +} + +fn vertex_stride(flags: u32) -> u32 { + return select(0u, 1u, (flags & INST_NORMALS) != 0u) + (vertex_uv_sets(flags) + 1u) / 2u + select(0u, 1u, (flags & INST_TANGENTS) != 0u); +} + fn env_pixel(i: u32) -> vec3<f32> { let o = frame.env_pixels + 3u * i; return vec3<f32>(tables[o], tables[o + 1u], tables[o + 2u]); diff --git a/native/crates/fsh-render-gpu/src/shaders/bsdf.wgsl b/native/crates/fsh-render-gpu/src/shaders/bsdf.wgsl index 98ee888c..e28526be 100644 --- a/native/crates/fsh-render-gpu/src/shaders/bsdf.wgsl +++ b/native/crates/fsh-render-gpu/src/shaders/bsdf.wgsl @@ -125,6 +125,154 @@ fn f82_average(f: F82) -> vec3<f32> { return clamp01_3(f.f0 + (vec3<f32>(1.0) - f.f0) * F82_INV_21 - f.b * F82_INV_126); } +const FILM_SENS_AMP: vec3<f32> = vec3<f32>(8.465900e-1, 1.0002219, 1.0011225); +const FILM_SENS_A: vec3<f32> = vec3<f32>(1.0562034e1, 1.1280203e1, 1.3875786e1); +const FILM_SENS_B: vec3<f32> = vec3<f32>(1.708547e-1, 3.673309e-1, 2.6103524e-1); +const FILM_X2_AMP: f32 = 1.538683e-1; +const FILM_X2_A: f32 = 1.4073707e1; +const FILM_X2_B: f32 = 1.7876617e-1; +const FILM_XYZ_R: vec3<f32> = vec3<f32>(1.5935888, -0.3677006, -0.22628292); +const FILM_XYZ_G: vec3<f32> = vec3<f32>(-0.69046715, 1.6721781, 0.01821402); +const FILM_XYZ_B: vec3<f32> = vec3<f32>(0.01109439, -0.00668605, 0.9944718); +const FILM_THIN_LIMIT: f32 = 0.03; +const FILM_ORDERS: u32 = 3u; + +struct FilmFresnel { + r: vec2<f32>, + phi: vec2<f32>, +} + +struct FilmAiry { + dc: f32, + xyz: vec3<f32>, + ok: bool, +} + +fn film_sensitivity(opd: f32, shift: f32) -> vec3<f32> { + let x2 = opd * opd; + var s = vec3<f32>( + FILM_SENS_AMP.x * sin_cos(FILM_SENS_A.x * opd + shift).y * exp(-FILM_SENS_B.x * x2), + FILM_SENS_AMP.y * sin_cos(FILM_SENS_A.y * opd + shift).y * exp(-FILM_SENS_B.y * x2), + FILM_SENS_AMP.z * sin_cos(FILM_SENS_A.z * opd + shift).y * exp(-FILM_SENS_B.z * x2), + ); + s.x += FILM_X2_AMP * sin_cos(FILM_X2_A * opd + shift).y * exp(-FILM_X2_B * x2); + return s; +} + +fn film_dielectric_sp(ct1: f32, n1: f32, n2: f32) -> FilmFresnel { + let st1 = 1.0 - ct1 * ct1; + let nr = n1 / n2; + let nr2 = nr * nr; + if (nr2 * st1 > 1.0) { + let s = sqrt(maxf(st1 - 1.0 / nr2, 0.0)); + let c = maxf(ct1, 1e-7); + return FilmFresnel(vec2<f32>(1.0), vec2<f32>(2.0 * atan(-nr2 * s / c), 2.0 * atan(-s / c))); + } + let ct2 = sqrt(maxf(1.0 - nr2 * st1, 0.0)); + let rp = (n2 * ct1 - n1 * ct2) / (n2 * ct1 + n1 * ct2); + let rs = (n1 * ct1 - n2 * ct2) / (n1 * ct1 + n2 * ct2); + return FilmFresnel(vec2<f32>(rp * rp, rs * rs), vec2<f32>(select(0.0, PI, rp < 0.0), select(0.0, PI, rs < 0.0))); +} + +fn film_conductor_sp(ct1: f32, n1: f32, n: f32, k: f32) -> FilmFresnel { + if (k <= 0.0) { + return film_dielectric_sp(ct1, n1, n); + } + let nk2 = n * n - k * k; + let a = nk2 - n1 * n1 * (1.0 - ct1 * ct1); + let b = sqrt(a * a + 4.0 * n * n * k * k); + let u = sqrt(maxf(0.5 * (a + b), 0.0)); + let v = sqrt(maxf(0.5 * (b - a), 0.0)); + let n1c = n1 * ct1; + let rs = ((n1c - u) * (n1c - u) + v * v) / ((n1c + u) * (n1c + u) + v * v); + let phis = atan2(2.0 * n1 * v * ct1, u * u + v * v - n1c * n1c) + PI; + let x = nk2 * ct1; + let y = 2.0 * n * k * ct1; + let rp = ((x - n1 * u) * (x - n1 * u) + (y - n1 * v) * (y - n1 * v)) + / ((x + n1 * u) * (x + n1 * u) + (y + n1 * v) * (y + n1 * v)); + let w = (n * n + k * k) * ct1; + let phip = atan2(2.0 * n1 * ct1 * (2.0 * n * k * u - nk2 * v), w * w - n1 * n1 * (u * u + v * v)); + return FilmFresnel(vec2<f32>(rp, rs), vec2<f32>(phip, phis)); +} + +fn film_airy(ct1_in: f32, n2: f32, n3: f32, k3: f32, d: f32) -> FilmAiry { + let ct1 = clamp(ct1_in, 0.0, 1.0); + let eta2 = 1.0 + (n2 - 1.0) * smooth_step(0.0, FILM_THIN_LIMIT, d); + let s2 = (1.0 - ct1 * ct1) / (eta2 * eta2); + if (s2 >= 1.0) { + return FilmAiry(0.0, vec3<f32>(0.0), false); + } + let ct2 = sqrt(1.0 - s2); + let f12 = film_dielectric_sp(ct1, 1.0, eta2); + let f23 = film_conductor_sp(ct2, eta2, n3, k3); + let opd = 2.0 * eta2 * d * ct2; + var dc = 0.0; + var xyz = vec3<f32>(0.0); + for (var p = 0u; p < 2u; p++) { + let t121 = 1.0 - f12.r[p]; + let r123 = f12.r[p] * f23.r[p]; + var rs = 0.0; + if (1.0 - r123 > 1e-7) { + rs = t121 * t121 * f23.r[p] / (1.0 - r123); + } + dc += 0.5 * (f12.r[p] + rs); + let phi2 = PI - f12.phi[p] + f23.phi[p]; + let root = sqrt(maxf(r123, 0.0)); + var cm = rs - t121; + for (var m = 1u; m <= FILM_ORDERS; m++) { + cm *= root; + let mf = f32(m); + let s = film_sensitivity(mf * opd, mf * phi2); + xyz.x += cm * s.x; + xyz.y += cm * s.y; + xyz.z += cm * s.z; + } + } + return FilmAiry(dc, xyz, true); +} + +fn film_row(c: u32, xyz: vec3<f32>) -> f32 { + var m = FILM_XYZ_R; + if (c == 1u) { + m = FILM_XYZ_G; + } else if (c == 2u) { + m = FILM_XYZ_B; + } + return m.x * xyz.x + m.y * xyz.y + m.z * xyz.z; +} + +fn film_dielectric(ct1: f32, n2: f32, n3: f32, d: f32) -> vec3<f32> { + let a = film_airy(ct1, n2, n3, 0.0, d); + if (!a.ok) { + return vec3<f32>(1.0); + } + return vec3<f32>( + clamp(a.dc + film_row(0u, a.xyz), 0.0, 1.0), + clamp(a.dc + film_row(1u, a.xyz), 0.0, 1.0), + clamp(a.dc + film_row(2u, a.xyz), 0.0, 1.0), + ); +} + +fn film_conductor(ct1: f32, n2: f32, n3: vec3<f32>, k3: vec3<f32>, d: f32) -> vec3<f32> { + var out = vec3<f32>(1.0); + for (var c = 0u; c < 3u; c++) { + let a = film_airy(ct1, n2, n3[c], k3[c], d); + if (a.ok) { + out[c] = clamp(a.dc + film_row(c, a.xyz), 0.0, 1.0); + } + } + return out; +} + +fn film_gulbrandsen(r_in: f32, g_in: f32) -> vec2<f32> { + let r = clamp(r_in, 0.0, 0.99); + let g = clamp(g_in, 0.0, 1.0); + let sr = sqrt(r); + let n = g * (1.0 - r) / (1.0 + r) + (1.0 - g) * (1.0 + sr) / (1.0 - sr); + let k2 = (r * (n + 1.0) * (n + 1.0) - (n - 1.0) * (n - 1.0)) / (1.0 - r); + return vec2<f32>(n, sqrt(maxf(k2, 0.0))); +} + struct Ggx { ax: f32, ay: f32, @@ -349,6 +497,12 @@ struct Bsdf { e_avg: f32, emission: vec3<f32>, opacity: f32, + film_weight: f32, + film_d: f32, + film_n2_front: f32, + film_n2_ext: f32, + film_metal_n: vec3<f32>, + film_metal_k: vec3<f32>, } fn bsdf_new(s: BsdfInputs, frame: ShadingFrame, eta_in: f32) -> Bsdf { @@ -427,9 +581,44 @@ fn bsdf_new(s: BsdfInputs, frame: ShadingFrame, eta_in: f32) -> Bsdf { e_avg, s.emission, s.opacity, + 0.0, + 0.0, + 1.0, + 1.0, + vec3<f32>(1.0), + vec3<f32>(0.0), ); } +fn bsdf_add_film(b: ptr<function, Bsdf>, s: BsdfInputs, eta_in: f32, weight: f32, thickness: f32, film_ior: f32) { + if (!(weight > 0.0)) { + return; + } + var eta = s.specular_ior; + if (finite_f32(eta_in) && eta_in > 0.0) { + eta = clamp(eta_in, 0.25, 4.0); + } + let exterior = s.specular_ior / eta; + let above = lerpf(exterior, s.coat_ior, s.coat_weight); + var metal_n = vec3<f32>(1.0); + var metal_k = vec3<f32>(0.0); + for (var c = 0u; c < 3u; c++) { + let nk = film_gulbrandsen((*b).rho[c], (*b).spec_color[c]); + metal_n[c] = nk.x / above; + metal_k[c] = nk.y / above; + } + (*b).film_weight = weight; + (*b).film_d = thickness; + (*b).film_n2_front = film_ior / above; + (*b).film_n2_ext = film_ior / exterior; + (*b).film_metal_n = metal_n; + (*b).film_metal_k = metal_k; +} + +fn bsdf_film_on(b: Bsdf) -> bool { + return b.film_weight > 0.0; +} + fn bsdf_built_delta_only(b: Bsdf) -> bool { let diffuse = (1.0 - b.metalness) * (1.0 - b.trans_weight) * max_element3(b.rho) > 0.0; let rough_spec = !b.spec_delta; @@ -453,6 +642,7 @@ struct BsdfCtx { wo: vec3<f32>, eta: f32, eta_r: f32, + film_n2: f32, r_opaque: f32, r_trans: f32, front: bool, @@ -474,6 +664,43 @@ fn bsdf_diel(mu: f32, g: Ggx, eta: f32) -> vec2<f32> { return bsdf_table_diel(mu, ggx_alpha_eff(g), eta); } +fn diel_film(b: Bsdf, c: ptr<function, BsdfCtx>, cos: f32, eta: f32) -> vec3<f32> { + let f = fresnel_dielectric(cos, eta); + let a = film_dielectric(cos, (*c).film_n2, eta, b.film_d); + return vec3<f32>(f) + (a - vec3<f32>(f)) * b.film_weight; +} + +fn trans_fresnel(b: Bsdf, c: ptr<function, BsdfCtx>, cos: f32) -> vec3<f32> { + return non_negative3(vec3<f32>(1.0) - diel_film(b, c, cos, (*c).eta)); +} + +fn metal_fresnel(b: Bsdf, c: ptr<function, BsdfCtx>, cos: f32) -> vec3<f32> { + let f = f82_eval(b.f82, cos); + if (!bsdf_film_on(b)) { + return f; + } + let a = film_conductor(cos, (*c).film_n2, b.film_metal_n, b.film_metal_k, b.film_d); + return f + (a - f) * b.film_weight; +} + +fn film_change(b: Bsdf, c: ptr<function, BsdfCtx>, cos: f32, eta: f32) -> vec3<f32> { + return diel_film(b, c, cos, eta) - vec3<f32>(fresnel_dielectric(cos, eta)); +} + +fn film_delta(b: Bsdf, c: ptr<function, BsdfCtx>, mu: f32, eta: f32) -> vec3<f32> { + if (b.spec_delta) { + return film_change(b, c, mu, eta); + } + let e1 = clamp(bsdf_table_cond(mu, ggx_alpha_eff(b.spec)), 0.0, 1.0); + let wo = (*c).wo; + var sum = vec3<f32>(0.0); + for (var k = 0u; k < 4u; k++) { + let u = vec2<f32>(select(0.25, 0.75, (k & 1u) != 0u), select(0.25, 0.75, k >= 2u)); + sum += film_change(b, c, clamp(dot3(wo, ggx_sample_visible(b.spec, wo, u)), 0.0, 1.0), eta); + } + return sum * (0.25 * e1); +} + fn interface_albedo(b: Bsdf, c: ptr<function, BsdfCtx>, mu: f32) -> vec2<f32> { let eta = (*c).eta; if (b.spec_delta) { @@ -524,6 +751,7 @@ fn bsdf_prepare(b: Bsdf, wo_in: vec3<f32>) -> BsdfCtx { c.wo = wo; c.eta = 1.0; c.eta_r = 1.0; + c.film_n2 = select(b.film_n2_front, b.film_n2_ext * b.eta_back, interior); c.r_opaque = 0.0; c.r_trans = 0.0; c.front = front; @@ -551,6 +779,11 @@ fn bsdf_prepare(b: Bsdf, wo_in: vec3<f32>) -> BsdfCtx { c.a[L_SPEC_R] = vec3<f32>(e.x * norm); c.w[L_SPEC_T] = vec3<f32>(norm); c.a[L_SPEC_T] = vec3<f32>(e.y); + if (bsdf_film_on(b)) { + let dt = film_delta(b, &c, mu, c.eta); + c.a[L_SPEC_R] = non_negative3((vec3<f32>(e.x) + dt) * norm); + c.a[L_SPEC_T] = non_negative3(vec3<f32>(e.y) - dt); + } c.above = vec3<f32>(0.0); } else { c.eta = b.eta_trans; @@ -592,7 +825,7 @@ fn bsdf_prepare(b: Bsdf, wo_in: vec3<f32>) -> BsdfCtx { c.ms_p = 1.0 - e; } c.w[L_METAL] = above * (b.metalness * b.spec_weight); - c.a[L_METAL] = f82_eval(b.f82, mu) * e + b.f_ms * (1.0 - e); + c.a[L_METAL] = metal_fresnel(b, &c, mu) * e + b.f_ms * (1.0 - e); } let dw = above * (1.0 - b.metalness); if (max_element3(dw) > 0.0) { @@ -622,6 +855,17 @@ fn bsdf_prepare(b: Bsdf, wo_in: vec3<f32>) -> BsdfCtx { c.a[L_SPEC_T] = vec3<f32>(et); c.w[L_DIFFUSE] = dw * ((1.0 - tw) * maxf(1.0 - erf, 0.0)); c.a[L_DIFFUSE] = eon_albedo(b.rho, b.sigma, mu); + if (bsdf_film_on(b)) { + let dt = film_delta(b, &c, mu, c.eta); + var d_o = dt; + if (c.eta_r != c.eta) { + d_o = film_delta(b, &c, mu, c.eta_r); + } + let rf = vec3<f32>(erf) + d_o; + c.a[L_SPEC_R] = non_negative3((rf * c.r_opaque) + (vec3<f32>(er) + dt) * c.r_trans); + c.a[L_SPEC_T] = non_negative3(vec3<f32>(et) - dt); + c.w[L_DIFFUSE] = dw * (non_negative3(vec3<f32>(1.0) - rf) * (1.0 - tw)); + } } } var total = 0.0; @@ -654,6 +898,17 @@ fn spec_fresnel(c: ptr<function, BsdfCtx>, cos: f32) -> f32 { return f; } +fn spec_fresnel_rgb(b: Bsdf, c: ptr<function, BsdfCtx>, cos: f32) -> vec3<f32> { + if (!bsdf_film_on(b)) { + return vec3<f32>(spec_fresnel(c, cos)); + } + var f = diel_film(b, c, cos, (*c).eta) * (*c).r_trans; + if ((*c).r_opaque > 0.0) { + f += diel_film(b, c, cos, (*c).eta_r) * (*c).r_opaque; + } + return f; +} + fn eval_lobe(b: Bsdf, c: ptr<function, BsdfCtx>, i: u32, wi: vec3<f32>) -> BsdfEval { let wo = (*c).wo; let none = BsdfEval(vec3<f32>(0.0), 0.0); @@ -673,7 +928,7 @@ fn eval_lobe(b: Bsdf, c: ptr<function, BsdfCtx>, i: u32, wi: vec3<f32>) -> BsdfE var p = 0.0; let r = ggx_reflection(b.spec, wo, wi); if (r.ok) { - v = f82_eval(b.f82, r.c) * r.core; + v = metal_fresnel(b, c, r.c) * r.core; p = (1.0 - (*c).ms_p) * r.pdf; } if ((*c).ms_p > 0.0) { @@ -689,6 +944,9 @@ fn eval_lobe(b: Bsdf, c: ptr<function, BsdfCtx>, i: u32, wi: vec3<f32>) -> BsdfE if (!r.ok) { return none; } + if (bsdf_film_on(b)) { + return BsdfEval(spec_fresnel_rgb(b, c, r.c) * r.core, r.pdf); + } return BsdfEval(vec3<f32>(r.core * spec_fresnel(c, r.c)), r.pdf); } case 4u: { @@ -698,12 +956,18 @@ fn eval_lobe(b: Bsdf, c: ptr<function, BsdfCtx>, i: u32, wi: vec3<f32>) -> BsdfE if (!r.ok) { return none; } + if (bsdf_film_on(b)) { + return BsdfEval(trans_fresnel(b, c, r.c) * r.core, r.pdf); + } return BsdfEval(vec3<f32>(r.core * (1.0 - fresnel_dielectric(r.c, eta))), r.pdf); } let r = ggx_transmission(b.spec, wo, wi, eta); if (!r.ok) { return none; } + if (bsdf_film_on(b)) { + return BsdfEval(trans_fresnel(b, c, r.c) * (r.core / (eta * eta)), r.pdf); + } let f = 1.0 - fresnel_dielectric(r.c, eta); return BsdfEval(vec3<f32>(r.core * f / (eta * eta)), r.pdf); } @@ -837,19 +1101,29 @@ fn sample_delta(b: Bsdf, c: ptr<function, BsdfCtx>, i: u32) -> DeltaSample { return DeltaSample(mirror, vec3<f32>(fresnel_dielectric(wo.z, b.coat_eta)), false, true); } case 2u: { - return DeltaSample(mirror, f82_eval(b.f82, wo.z), false, true); + return DeltaSample(mirror, metal_fresnel(b, c, wo.z), false, true); } case 3u: { - return DeltaSample(mirror, vec3<f32>(spec_fresnel(c, wo.z)), false, true); + return DeltaSample(mirror, spec_fresnel_rgb(b, c, wo.z), false, true); } case 4u: { let eta = (*c).eta; let f = 1.0 - fresnel_dielectric(wo.z, eta); + let film = bsdf_film_on(b); + var fc = vec3<f32>(f); + if (film) { + fc = trans_fresnel(b, c, wo.z); + } if (b.thin || abs(eta - 1.0) < BSDF_ETA_PASS) { - return DeltaSample(-wo, vec3<f32>(f), true, true); + return DeltaSample(-wo, fc, true, true); } let t = refract_dir(wo, vec3<f32>(0.0, 0.0, 1.0), eta); - return DeltaSample(t.v, vec3<f32>(f / (eta * eta)), true, t.ok); + if (film) { + fc = fc / (eta * eta); + } else { + fc = vec3<f32>(f / (eta * eta)); + } + return DeltaSample(t.v, fc, true, t.ok); } default: { return DeltaSample(vec3<f32>(0.0), vec3<f32>(0.0), false, false); diff --git a/native/crates/fsh-render-gpu/src/shaders/camera.wgsl b/native/crates/fsh-render-gpu/src/shaders/camera.wgsl index 05536771..050ae384 100644 --- a/native/crates/fsh-render-gpu/src/shaders/camera.wgsl +++ b/native/crates/fsh-render-gpu/src/shaders/camera.wgsl @@ -22,6 +22,13 @@ fn filter_offset(u: vec2<f32>) -> vec2<f32> { return vec2<f32>(r * cos(phi) * s, r * sin(phi) * s); } +fn camera_cone() -> vec2<f32> { + if frame.cam_projection == PROJ_ORTHOGRAPHIC { + return vec2<f32>(2.0 * frame.cam_half_h / frame.film_h, 0.0); + } + return vec2<f32>(0.0, atan(2.0 * frame.cam_tan_y / frame.film_h)); +} + fn camera_ray(fx: f32, fy: f32, lens: vec2<f32>) -> TraceRay { let sx = 2.0 * fx / frame.film_w - 1.0; let sy = 1.0 - 2.0 * fy / frame.film_h; diff --git a/native/crates/fsh-render-gpu/src/shaders/features.wgsl b/native/crates/fsh-render-gpu/src/shaders/features.wgsl index 4c4e0c79..54ea38de 100644 --- a/native/crates/fsh-render-gpu/src/shaders/features.wgsl +++ b/native/crates/fsh-render-gpu/src/shaders/features.wgsl @@ -1,6 +1,7 @@ override USE_LAMPS: bool = true; override USE_CATCHER: bool = true; override USE_NORMALS: bool = true; +override USE_PROGRAMS: bool = true; const RETIRED_BIT: u32 = 0x80000000u; const RAY_COUNT_MASK: u32 = 0x7fffffffu; diff --git a/native/crates/fsh-render-gpu/src/shaders/integrator.wgsl b/native/crates/fsh-render-gpu/src/shaders/integrator.wgsl index 607bec11..96d9f0b5 100644 --- a/native/crates/fsh-render-gpu/src/shaders/integrator.wgsl +++ b/native/crates/fsh-render-gpu/src/shaders/integrator.wgsl @@ -20,6 +20,31 @@ struct SampleOut { instance: u32, } +const CONE_MIN_COS: f32 = 0.05; +const NORMAL_CLAMP_LIFT: f32 = 0.01; + +fn clamp_bent_normal(ns: vec3<f32>, ng: vec3<f32>, wo: vec3<f32>) -> vec3<f32> { + let ngf = select(ng, -ng, dot3(ng, wo) < 0.0); + let r = ns * (2.0 * dot3(wo, ns)) - wo; + let d = dot3(r, ngf); + if d >= NORMAL_CLAMP_LIFT { + return ns; + } + let h = normalize_or(wo + normalize_or(r + ngf * (NORMAL_CLAMP_LIFT - d), vec3<f32>(0.0)), vec3<f32>(0.0)); + return select(ns, h, finite_v3(h)); +} + +fn cone_widening(flags: u32, m: BsdfInputs) -> f32 { + if (flags & LOBE_DELTA) != 0u { + return 0.0; + } + if (flags & LOBE_DIFFUSE) != 0u { + return 2.0; + } + let r = clampf(m.specular_roughness, 0.0, 1.0); + return 2.0 * r * r; +} + fn background(d: vec3<f32>, from_camera: bool) -> vec3<f32> { if frame.background == BG_COLOUR { return frame.background_colour; @@ -58,6 +83,17 @@ fn ground_distance(ray: TraceRay, t_geo: f32) -> f32 { return f32_inf(); } +const CHANNEL_DISPERSION: vec3<f32> = vec3<f32>(-6.2823046e-3, 5.049531e-1, 1.9850688); + +fn dispersion_channel(u: f32) -> u32 { + return min(u32(u * 3.0), 2u); +} + +fn dispersion_ior(ior_d: f32, dispersion: f32, c: u32) -> f32 { + let k = CHANNEL_DISPERSION; + return ior_d + (ior_d - 1.0) * dispersion * k[c]; +} + fn lamp_visible(flags: u32, vertex: u32, camera_chain: bool) -> bool { if vertex == 0u { return (flags & LF_CAMERA) != 0u; @@ -101,6 +137,8 @@ fn path_sample(x: u32, y: u32, pixel: u32, sample: u32, centre: bool) -> SampleO var mirror_b = vec3<f32>(0.0); var mirror_f = 0.0; var mirror_w = vec3<f32>(0.0); + var cone = camera_cone(); + var hero = false; loop { let h = trace_closest_counted(ray, mask); @@ -176,12 +214,17 @@ fn path_sample(x: u32, y: u32, pixel: u32, sample: u32, centre: bool) -> SampleO let dir = normalize_or(ray.dir, vec3<f32>(0.0)); let wo = -dir; + let seg = select(h.t, t_ground, catcher) * length3(ray.dir); + let footprint = abs(cone.x + cone.y * seg) / maxf(abs(dot3(h.ng, dir)), CONE_MIN_COS); + cone.x += cone.y * seg; var p: vec3<f32>; var ng = UP; var ns = UP; var m: BsdfInputs; var eta = 1.5; var b = vec3<f32>(0.0); + var film = vec3<f32>(0.0); + var channel = NONE; if catcher { p = ray.origin + ray.dir * t_ground; p = vec3<f32>(p.x, frame.ground_height, p.z); @@ -198,7 +241,11 @@ fn path_sample(x: u32, y: u32, pixel: u32, sample: u32, centre: bool) -> SampleO ng = h.ng; let sn = shading_normal(h.instance, h.slot, h.u, h.v); ns = select(ng, sn.v, sn.ok); - m = instance_inputs(h.instance); + let ns0 = ns; + m = shade_inputs(h.instance, h.slot, h.u, h.v, p, ng, &ns, footprint); + if any(ns != ns0) { + ns = clamp_bent_normal(ns, ng, wo); + } if regularize { m = bsdf_regularized(m, frame.roughness_floor); } @@ -224,9 +271,17 @@ fn path_sample(x: u32, y: u32, pixel: u32, sample: u32, centre: bool) -> SampleO continue; } } - eta = instance_eta(h.instance); + eta = m.eta; + let optics = materials[instances[h.instance].material]; + if optics.dispersion > 0.0 && m.transmission_weight > 0.0 && m.thin_walled == 0u { + channel = dispersion_channel(sampler_1d(sp, DIM_WAVELENGTH)); + m.specular_ior = clamp(dispersion_ior(m.specular_ior, optics.dispersion, channel), 1.0, 4.0); + eta = m.specular_ior; + } + film = vec3<f32>(optics.film_weight, optics.film_thickness, optics.film_ior); } - let bsdf = bsdf_new(m, make_shading_frame(ns, ng), eta); + var bsdf = bsdf_new(m, make_shading_frame(ns, ng), eta); + bsdf_add_film(&bsdf, m, eta, film.x, film.y, film.z); var ctx = bsdf_prepare(bsdf, wo); if !catcher { if first { @@ -299,12 +354,18 @@ fn path_sample(x: u32, y: u32, pixel: u32, sample: u32, centre: bool) -> SampleO let pdf_l = ls.pdf * choice.prob; if ls.valid && pdf_l > 0.0 && !is_black3(ls.radiance) { let ev = bsdf_eval_ctx(bsdf, &ctx, ls.wi); - if !is_black3(ev.value) { + var f = ev.value; + if channel != NONE && !hero && dot3(ls.wi, ng) * dot3(wo, ng) < 0.0 { + var one = vec3<f32>(0.0); + one[channel] = 3.0; + f *= one; + } + if !is_black3(f) { var w = 1.0; if !ls.delta { w = power_heuristic(1.0, pdf_l, 1.0, ev.pdf); } - let c = tp * ev.value * ls.radiance * (w / pdf_l); + let c = tp * f * ls.radiance * (w / pdf_l); if ls.shadows { shadow_rays[0] = shadow_ray(p, ng, ls.wi, ls.aim, ls.has_aim); shadow_value[0] = c; @@ -336,6 +397,7 @@ fn path_sample(x: u32, y: u32, pixel: u32, sample: u32, centre: bool) -> SampleO f = clamp(lit / total, 0.0, 1.0); } if bs.valid != 0u { + cone.y += cone_widening(bs.flags, m); mirror = true; mirror_b = b; mirror_f = f; @@ -368,6 +430,12 @@ fn path_sample(x: u32, y: u32, pixel: u32, sample: u32, centre: bool) -> SampleO bounces += 1u; } tp *= bs.weight; + if channel != NONE && is_trans && !hero { + var one = vec3<f32>(0.0); + one[channel] = 3.0; + tp *= one; + hero = true; + } if !finite_v3(tp) || is_black3(tp) { break; } @@ -376,6 +444,7 @@ fn path_sample(x: u32, y: u32, pixel: u32, sample: u32, centre: bool) -> SampleO camera_chain = camera_chain && spec; prev_delta = spec; prev_pdf = bs.pdf; + cone.y += cone_widening(bs.flags, m); if diffuse { regularize = true; } diff --git a/native/crates/fsh-render-gpu/src/shaders/lights.wgsl b/native/crates/fsh-render-gpu/src/shaders/lights.wgsl index 11378f0b..a76b01ef 100644 --- a/native/crates/fsh-render-gpu/src/shaders/lights.wgsl +++ b/native/crates/fsh-render-gpu/src/shaders/lights.wgsl @@ -114,9 +114,9 @@ fn emissive_radiance(r: u32, q: vec3<f32>, b1: f32, b2: f32, wo: vec3<f32>) -> v let slot = tword(r + 18u); let ng = emissive_normal(r); let sn = shading_normal(inst, slot, b1, b2); - let ns = select(ng, sn.v, sn.ok); - let m = instance_inputs(inst); - return bsdf_emitted(m, make_shading_frame(ns, ng), instance_eta(inst), wo) * m.opacity; + var ns = select(ng, sn.v, sn.ok); + let m = shade_inputs(inst, slot, b1, b2, q, ng, &ns, 0.0); + return bsdf_emitted(m, make_shading_frame(ns, ng), m.eta, wo) * m.opacity; } fn emissive_sample(k: u32, pick_prob: f32, p: vec3<f32>, u: vec2<f32>) -> LightSample { diff --git a/native/crates/fsh-render-gpu/src/shaders/procedural.wgsl b/native/crates/fsh-render-gpu/src/shaders/procedural.wgsl new file mode 100644 index 00000000..53850b71 --- /dev/null +++ b/native/crates/fsh-render-gpu/src/shaders/procedural.wgsl @@ -0,0 +1,521 @@ +const PROC_SEED_MIX: vec3<u32> = vec3<u32>(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u); +const PROC_OCTAVE_MIX: u32 = 0x632BE5ABu; +const PROC_CHANNEL_MIX: u32 = 0x2545F491u; +const PROC_COORD_LIMIT: f32 = 1.0e9; +const PROC_SEED_LIMIT: f32 = 4294967040.0; +const PROC_TURBULENCE_MEAN: f32 = 0.2199; + +fn proc_pcg3d(v0: vec3<u32>) -> vec3<u32> { + var v = v0 * 1664525u + 1013904223u; + v.x += v.y * v.z; + v.y += v.z * v.x; + v.z += v.x * v.y; + v ^= v >> vec3<u32>(16u); + v.x += v.y * v.z; + v.y += v.z * v.x; + v.z += v.x * v.y; + return v; +} + +fn proc_hash(c: vec3<i32>, seed: u32) -> vec3<u32> { + return proc_pcg3d(bitcast<vec3<u32>>(c) + seed * PROC_SEED_MIX); +} + +fn proc_unit(h: u32) -> f32 { + return f32(h >> 8u) * (1.0 / 16777216.0); +} + +fn proc_octave_seed(seed: u32, i: u32) -> u32 { + return seed + i * PROC_OCTAVE_MIX; +} + +fn proc_channel_seed(seed: u32, c: u32) -> u32 { + return seed + c * PROC_CHANNEL_MIX; +} + +fn proc_finite(x: f32) -> bool { + return (bitcast<u32>(x) & 0x7f800000u) != 0x7f800000u; +} + +fn proc_seed(v: f32) -> u32 { + if (proc_finite(v) && v > 0.0) { + return u32(min(v, PROC_SEED_LIMIT)); + } + return 0u; +} + +fn proc_coord(v: f32) -> f32 { + if (proc_finite(v)) { + return clamp(v, -PROC_COORD_LIMIT, PROC_COORD_LIMIT); + } + return 0.0; +} + +fn proc_num(v: f32) -> f32 { + return select(0.0, v, proc_finite(v)); +} + +fn proc_smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = clamp((x - e0) / (e1 - e0), 0.0, 1.0); + return t * t * (3.0 - 2.0 * t); +} + +fn proc_aa(r: f32) -> f32 { + return 1.0 - proc_smooth(0.5, 1.0, r); +} + +fn proc_lerp(a: f32, b: f32, t: f32) -> f32 { + return a + (b - a) * t; +} + +fn proc_mix3(a: vec4<f32>, b: vec4<f32>, t: f32) -> vec4<f32> { + return vec4<f32>(proc_lerp(a.x, b.x, t), proc_lerp(a.y, b.y, t), proc_lerp(a.z, b.z, t), 1.0); +} + +fn proc_footprint(v: vec4<f32>) -> f32 { + if (proc_finite(v.w) && v.w > 0.0) { + return v.w; + } + return 0.0; +} + +fn proc_position(v: vec4<f32>, scale: f32) -> vec3<f32> { + return vec3<f32>(proc_coord(v.x * scale), proc_coord(v.y * scale), proc_coord(v.z * scale)); +} + +fn proc_arg(args: ptr<function, array<vec4<f32>, 12>>, count: u32, i: u32) -> vec4<f32> { + if (i >= count || i >= 12u) { + return vec4<f32>(0.0); + } + return (*args)[i]; +} + +fn proc_fade(t: f32) -> f32 { + return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); +} + +fn proc_grad(h0: u32, x: f32, y: f32, z: f32) -> f32 { + let h = h0 & 15u; + let u = select(y, x, h < 8u); + var v = z; + if (h < 4u) { + v = y; + } else if (h == 12u || h == 14u) { + v = x; + } + let a = select(-u, u, (h & 1u) == 0u); + let b = select(-v, v, (h & 2u) == 0u); + return a + b; +} + +fn proc_corner(i: vec3<i32>, d: vec3<i32>, f: vec3<f32>, seed: u32) -> f32 { + let h = proc_hash(i + d, seed).x; + return proc_grad(h, f.x - f32(d.x), f.y - f32(d.y), f.z - f32(d.z)); +} + +fn proc_perlin(p: vec3<f32>, seed: u32) -> f32 { + let fl = floor(p); + let i = vec3<i32>(fl); + let f = p - fl; + let u = proc_fade(f.x); + let v = proc_fade(f.y); + let w = proc_fade(f.z); + let x00 = proc_lerp(proc_corner(i, vec3<i32>(0, 0, 0), f, seed), proc_corner(i, vec3<i32>(1, 0, 0), f, seed), u); + let x10 = proc_lerp(proc_corner(i, vec3<i32>(0, 1, 0), f, seed), proc_corner(i, vec3<i32>(1, 1, 0), f, seed), u); + let x01 = proc_lerp(proc_corner(i, vec3<i32>(0, 0, 1), f, seed), proc_corner(i, vec3<i32>(1, 0, 1), f, seed), u); + let x11 = proc_lerp(proc_corner(i, vec3<i32>(0, 1, 1), f, seed), proc_corner(i, vec3<i32>(1, 1, 1), f, seed), u); + return proc_lerp(proc_lerp(x00, x10, v), proc_lerp(x01, x11, v), w); +} + +fn proc_fractal(p: vec3<f32>, seed: u32, octaves: f32, lacunarity: f32, gain0: f32, fw: f32, turbulent: bool) -> f32 { + let n = select(1.0, clamp(octaves, 1.0, 16.0), proc_finite(octaves)); + let whole = floor(n); + let part = n - whole; + let count = u32(whole) + select(0u, 1u, part > 0.0); + let lac = select(2.0, clamp(lacunarity, 0.0, 16.0), proc_finite(lacunarity)); + let gain = select(0.5, clamp(gain0, 0.0, 4.0), proc_finite(gain0)); + var sum = 0.0; + var norm = 0.0; + var amp = 1.0; + var freq = 1.0; + for (var i = 0u; i < count; i++) { + let weight = select(amp, amp * part, f32(i) >= whole); + let q = vec3<f32>(p.x * freq, p.y * freq, p.z * freq); + var v = proc_perlin(q, proc_octave_seed(seed, i)); + if (turbulent) { + v = abs(v) - PROC_TURBULENCE_MEAN; + } + sum += weight * proc_aa(fw * freq) * v; + norm += weight; + amp *= gain; + freq *= lac; + } + if (norm > 0.0) { + return sum / norm; + } + return 0.0; +} + +fn proc_unit_value(n: f32) -> f32 { + return clamp(0.5 + 0.5 * n, 0.0, 1.0); +} + +fn proc_fractal_out(output: u32, p: vec3<f32>, seed: u32, octaves: f32, lacunarity: f32, gain: f32, fw: f32) -> vec4<f32> { + if (output == 1u) { + let r = proc_unit_value(proc_fractal(p, proc_channel_seed(seed, 0u), octaves, lacunarity, gain, fw, false)); + let g = proc_unit_value(proc_fractal(p, proc_channel_seed(seed, 1u), octaves, lacunarity, gain, fw, false)); + let b = proc_unit_value(proc_fractal(p, proc_channel_seed(seed, 2u), octaves, lacunarity, gain, fw, false)); + return vec4<f32>(r, g, b, 1.0); + } + return vec4<f32>(proc_unit_value(proc_fractal(p, seed, octaves, lacunarity, gain, fw, false))); +} + +fn proc_noise(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let scale = proc_num(proc_arg(args, count, 1u).x); + let detail = clamp(proc_num(proc_arg(args, count, 2u).x), 0.0, 15.0); + let roughness = proc_num(proc_arg(args, count, 3u).x); + let distortion = proc_num(proc_arg(args, count, 4u).x); + let seed = proc_seed(proc_arg(args, count, 5u).x); + let fw = proc_footprint(v) * abs(scale); + var p = proc_position(v, scale); + if (distortion != 0.0) { + let dx = distortion * proc_aa(fw) * proc_perlin(p, proc_channel_seed(seed, 17u)); + let dy = distortion * proc_aa(fw) * proc_perlin(p, proc_channel_seed(seed, 18u)); + let dz = distortion * proc_aa(fw) * proc_perlin(p, proc_channel_seed(seed, 19u)); + p = vec3<f32>(p.x + dx, p.y + dy, p.z + dz); + } + return proc_fractal_out(output, p, seed, detail + 1.0, 2.0, roughness, fw); +} + +fn proc_fbm(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let scale = proc_num(proc_arg(args, count, 1u).x); + let octaves = proc_num(proc_arg(args, count, 2u).x); + let lacunarity = proc_num(proc_arg(args, count, 3u).x); + let gain = proc_num(proc_arg(args, count, 4u).x); + let seed = proc_seed(proc_arg(args, count, 5u).x); + let fw = proc_footprint(v) * abs(scale); + return proc_fractal_out(output, proc_position(v, scale), seed, octaves, lacunarity, gain, fw); +} + +const PROC_FAR: f32 = 1.0e30; +const PROC_VORONOI_MEAN: array<f32, 18> = array<f32, 18>( + 0.4801, 0.7027, 0.2227, 0.7498, 1.0003, 0.2498, 0.3749, 0.6250, 0.2501, + 0.5205, 0.7171, 0.1963, 0.7659, 1.0520, 0.2866, 0.4205, 0.5793, 0.1585, +); + +struct ProcNearest { + f1: f32, + f2: f32, + point: vec3<f32>, + hash: vec3<u32>, +} + +fn proc_mode(v: f32, hi: u32) -> u32 { + return min(u32(clamp(proc_num(v), 0.0, 255.0)), hi); +} + +fn proc_distance(d: vec3<f32>, metric: u32) -> f32 { + let a = abs(d); + if (metric == 1u) { + return a.x + a.y + a.z; + } + if (metric == 2u) { + return max(max(a.x, a.y), a.z); + } + return sqrt(d.x * d.x + d.y * d.y + d.z * d.z); +} + +fn proc_nearest(p: vec3<f32>, seed: u32, randomness: f32, metric: u32) -> ProcNearest { + let fl = floor(p); + let i = vec3<i32>(fl); + let f = p - fl; + var best = ProcNearest(PROC_FAR, PROC_FAR, vec3<f32>(0.5), vec3<u32>(0u)); + for (var dz = -1; dz <= 1; dz++) { + for (var dy = -1; dy <= 1; dy++) { + for (var dx = -1; dx <= 1; dx++) { + let h = proc_hash(i + vec3<i32>(dx, dy, dz), seed); + let pt = vec3<f32>( + f32(dx) + 0.5 + randomness * (proc_unit(h.x) - 0.5), + f32(dy) + 0.5 + randomness * (proc_unit(h.y) - 0.5), + f32(dz) + 0.5 + randomness * (proc_unit(h.z) - 0.5), + ); + let d = proc_distance(vec3<f32>(pt.x - f.x, pt.y - f.y, pt.z - f.z), metric); + if (d < best.f1) { + best.f2 = best.f1; + best.f1 = d; + best.point = pt; + best.hash = h; + } else if (d < best.f2) { + best.f2 = d; + } + } + } + } + best.point = vec3<f32>(fl.x + best.point.x, fl.y + best.point.y, fl.z + best.point.z); + return best; +} + +fn proc_flakes(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let scale = proc_num(proc_arg(args, count, 1u).x); + let density = clamp(proc_num(proc_arg(args, count, 2u).x), 0.0, 1.0); + let spread = clamp(proc_num(proc_arg(args, count, 3u).x), 0.0, 1.0); + let seed = proc_seed(proc_arg(args, count, 4u).x); + let t = proc_aa(proc_footprint(v) * abs(scale)); + let n = proc_nearest(proc_position(v, scale), seed, 1.0, 0u); + let h = proc_pcg3d(n.hash); + let on = proc_unit(h.x) < density; + let mask = proc_lerp(density, select(0.0, 1.0, on), t); + var tilt = vec3<f32>(0.0, 0.0, 1.0); + if (on) { + let cos_t = 1.0 - proc_unit(h.y) * spread; + let sin_t = sqrt(max(1.0 - cos_t * cos_t, 0.0)); + let phi = PROC_TAU * proc_unit(h.z); + tilt = vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t); + } + var m = vec3<f32>(tilt.x * t, tilt.y * t, proc_lerp(1.0, tilt.z, t)); + let len = sqrt(m.x * m.x + m.y * m.y + m.z * m.z); + if (len > 0.0) { + m = vec3<f32>(m.x / len, m.y / len, m.z / len); + } else { + m = vec3<f32>(0.0, 0.0, 1.0); + } + if (output == 1u) { + return vec4<f32>(mask); + } + if (output == 2u) { + return vec4<f32>(0.5 + 0.5 * m.x, 0.5 + 0.5 * m.y, 0.5 + 0.5 * m.z, 1.0); + } + return vec4<f32>(m, 0.0); +} + +fn proc_voronoi(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let scale = proc_num(proc_arg(args, count, 1u).x); + let randomness = clamp(proc_num(proc_arg(args, count, 2u).x), 0.0, 1.0); + let settings = proc_arg(args, count, 3u); + let seed = proc_seed(settings.x); + let metric = proc_mode(settings.y, 2u); + let feature = proc_mode(settings.z, 2u); + let t = proc_aa(proc_footprint(v) * abs(scale)); + let n = proc_nearest(proc_position(v, scale), seed, randomness, metric); + if (output == 1u) { + let h = proc_pcg3d(n.hash); + return vec4<f32>(proc_lerp(0.5, proc_unit(h.x), t), proc_lerp(0.5, proc_unit(h.y), t), proc_lerp(0.5, proc_unit(h.z), t), 1.0); + } + if (output == 2u) { + if (scale == 0.0) { + return v; + } + let w = vec3<f32>(n.point.x / scale, n.point.y / scale, n.point.z / scale); + return vec4<f32>(proc_lerp(v.x, w.x, t), proc_lerp(v.y, w.y, t), proc_lerp(v.z, w.z, t), v.w); + } + var d = n.f1; + if (feature == 1u) { + d = n.f2; + } else if (feature == 2u) { + d = n.f2 - n.f1; + } + let mean = proc_lerp(PROC_VORONOI_MEAN[metric * 3u + feature], PROC_VORONOI_MEAN[9u + metric * 3u + feature], randomness); + return vec4<f32>(proc_lerp(mean, d, t)); +} + +const PROC_TAU: f32 = 6.28318530717958647692; +const PROC_PI: f32 = 3.14159265358979323846; +const PROC_CHECKER_OFFSET: f32 = 1.0e-4; + +fn proc_checker(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let scale = proc_num(proc_arg(args, count, 1u).x); + let p = proc_position(v, scale); + let i = vec3<i32>(floor(p + vec3<f32>(PROC_CHECKER_OFFSET))); + let parity = (i.x + i.y + i.z) & 1; + let pick = select(0.0, 1.0, parity == 0); + let fac = proc_lerp(0.5, pick, proc_aa(proc_footprint(v) * abs(scale))); + if (output == 1u) { + return vec4<f32>(fac); + } + return proc_mix3(proc_arg(args, count, 3u), proc_arg(args, count, 2u), fac); +} + +fn proc_grey(output: u32, value: f32, colour_output: u32) -> vec4<f32> { + if (output == colour_output) { + return vec4<f32>(value, value, value, 1.0); + } + return vec4<f32>(value); +} + +fn proc_wave(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let scale = proc_num(proc_arg(args, count, 1u).x); + let distortion = proc_num(proc_arg(args, count, 2u).x); + let detail = clamp(proc_num(proc_arg(args, count, 3u).x), 0.0, 15.0); + let phase = proc_num(proc_arg(args, count, 4u).x); + let settings = proc_arg(args, count, 5u); + let seed = proc_seed(settings.x); + let rings = proc_mode(settings.y, 1u) == 1u; + let profile = proc_mode(settings.z, 2u); + let fw = proc_footprint(v) * abs(scale); + let p = proc_position(v, scale); + var s = p.x; + if (rings) { + s = sqrt(p.x * p.x + p.y * p.y + p.z * p.z); + } + if (distortion != 0.0) { + s += distortion * proc_fractal(p, seed, detail + 1.0, 2.0, 0.5, fw, false); + } + s += phase; + let fr = s - floor(s); + var y = 0.5 - 0.5 * cos(PROC_TAU * fr); + if (profile == 1u) { + y = fr; + } else if (profile == 2u) { + y = 1.0 - abs(2.0 * fr - 1.0); + } + return proc_grey(output, proc_lerp(0.5, y, proc_aa(fw * (1.0 + abs(distortion)))), 1u); +} + +const PROC_FINE_ACROSS: f32 = 3.1; +const PROC_FINE_ALONG: f32 = 0.6; + +fn proc_brushed(args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let lines = abs(proc_num(proc_arg(args, count, 1u).x)); + let length = max(abs(proc_num(proc_arg(args, count, 2u).x)), 1.0e-6); + let strength = proc_num(proc_arg(args, count, 3u).x); + let seed = proc_seed(proc_arg(args, count, 4u).x); + let w = proc_footprint(v); + let x = proc_coord(v.x); + let y = proc_coord(v.y); + let z = proc_coord(v.z); + let qa = vec3<f32>(proc_coord(x / length), proc_coord(y * lines), proc_coord(z * lines)); + let a = proc_perlin(qa, seed) * proc_aa(max(w * lines, w / length)); + let fine = lines * PROC_FINE_ACROSS; + let short = length * PROC_FINE_ALONG; + let qb = vec3<f32>(proc_coord(x / short), proc_coord(y * fine), proc_coord(z * fine)); + let b = proc_perlin(qb, proc_octave_seed(seed, 1u)) * proc_aa(max(w * fine, w / short)); + return vec4<f32>(clamp(0.5 + strength * (0.6 * a + 0.4 * b), 0.0, 1.0)); +} + +const PROC_GRAIN_ACROSS: f32 = 6.0; +const PROC_GRAIN_ALONG: f32 = 0.1875; +const PROC_WOBBLE_ACROSS: f32 = 0.1; +const PROC_WOBBLE_ALONG: f32 = 0.0125; +const PROC_RING_MEAN: f32 = 0.25; + +fn proc_wood(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let scale = proc_num(proc_arg(args, count, 1u).x); + let rings = abs(proc_num(proc_arg(args, count, 2u).x)); + let distortion = proc_num(proc_arg(args, count, 3u).x); + let seed = proc_seed(proc_arg(args, count, 6u).x); + let fw = proc_footprint(v) * abs(scale); + let p = proc_position(v, scale); + let wa = rings * PROC_WOBBLE_ACROSS; + let wl = rings * PROC_WOBBLE_ALONG; + let wq = vec3<f32>(proc_coord(p.x * wa), proc_coord(p.y * wl), proc_coord(p.z * wa)); + let wobble = proc_fractal(wq, seed, 2.0, 2.0, 0.5, fw * wa, false); + let r = sqrt(p.x * p.x + p.z * p.z); + let t = r * rings + distortion * 2.0 * wobble; + let s = t - floor(t); + let ring = proc_lerp(PROC_RING_MEAN, s * s * s, proc_aa(fw * rings * (1.0 + 0.3 * abs(distortion)))); + let ga = rings * PROC_GRAIN_ACROSS; + let gl = rings * PROC_GRAIN_ALONG; + let q = vec3<f32>(proc_coord(p.x * ga), proc_coord(p.y * gl), proc_coord(p.z * ga)); + let grain = proc_perlin(q, proc_octave_seed(seed, 7u)) * proc_aa(fw * ga); + let value = clamp(0.85 * ring + 0.15 * (0.5 + grain), 0.0, 1.0); + if (output == 1u) { + return vec4<f32>(value); + } + return proc_mix3(proc_arg(args, count, 4u), proc_arg(args, count, 5u), value); +} + +fn proc_gradient(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let p = proc_position(v, 1.0); + let w = proc_footprint(v); + let kind = proc_mode(proc_arg(args, count, 1u).y, 3u); + var value = clamp(p.x, 0.0, 1.0); + if (kind == 1u) { + let x = clamp(p.x, 0.0, 1.0); + value = x * x; + } else if (kind == 2u) { + let r = sqrt(p.x * p.x + p.y * p.y); + value = 0.5; + if (r > 0.0) { + let angle = atan2(p.y, p.x) / PROC_TAU + 0.5; + value = proc_lerp(0.5, angle, proc_aa(w / (PROC_TAU * r))); + } + } else if (kind == 3u) { + value = max(1.0 - sqrt(p.x * p.x + p.y * p.y + p.z * p.z), 0.0); + } + if (output == 1u) { + return vec4<f32>(value, value, value, 1.0); + } + return vec4<f32>(value); +} + +const PROC_TURBULENCE_FREQUENCY: f32 = 3.0; +const PROC_VEIN_MEAN: f32 = 0.1309; + +fn proc_marble(output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + let v = proc_arg(args, count, 0u); + let scale = proc_num(proc_arg(args, count, 1u).x); + let veins = proc_num(proc_arg(args, count, 2u).x); + let distortion = proc_num(proc_arg(args, count, 3u).x); + let seed = proc_seed(proc_arg(args, count, 6u).x); + let fw = proc_footprint(v) * abs(scale); + let p = proc_position(v, scale); + let q = vec3<f32>(proc_coord(p.x * PROC_TURBULENCE_FREQUENCY), proc_coord(p.y * PROC_TURBULENCE_FREQUENCY), proc_coord(p.z * PROC_TURBULENCE_FREQUENCY)); + let turbulence = PROC_TURBULENCE_MEAN + proc_fractal(q, seed, 5.0, 2.0, 0.5, fw * PROC_TURBULENCE_FREQUENCY, true); + let phase = veins * p.x + distortion * 2.0 * turbulence; + let fr = phase - floor(phase); + let u = 1.0 - sin(PROC_PI * fr); + let u2 = u * u; + let vein = u2 * u2; + let value = proc_lerp(PROC_VEIN_MEAN, vein, proc_aa(fw * abs(veins) * (1.0 + abs(distortion)))); + if (output == 1u) { + return vec4<f32>(value); + } + return proc_mix3(proc_arg(args, count, 4u), proc_arg(args, count, 5u), value); +} + +fn procedural(kind: u32, output: u32, args: ptr<function, array<vec4<f32>, 12>>, count: u32) -> vec4<f32> { + switch kind { + case 0u: { + return proc_noise(output, args, count); + } + case 1u: { + return proc_fbm(output, args, count); + } + case 2u: { + return proc_voronoi(output, args, count); + } + case 3u: { + return proc_checker(output, args, count); + } + case 4u: { + return proc_gradient(output, args, count); + } + case 5u: { + return proc_wave(output, args, count); + } + case 6u: { + return proc_brushed(args, count); + } + case 7u: { + return proc_flakes(output, args, count); + } + case 8u: { + return proc_wood(output, args, count); + } + case 9u: { + return proc_marble(output, args, count); + } + default: { + return vec4<f32>(0.0); + } + } +} diff --git a/native/crates/fsh-render-gpu/src/shaders/program.wgsl b/native/crates/fsh-render-gpu/src/shaders/program.wgsl new file mode 100644 index 00000000..8cf8f2af --- /dev/null +++ b/native/crates/fsh-render-gpu/src/shaders/program.wgsl @@ -0,0 +1,652 @@ +#include "bindings.wgsl" +#include "math.wgsl" +#include "bsdf.wgsl" +#include "texture.wgsl" +#include "procedural.wgsl" + +const PROGRAM_HEADER: u32 = 8u; +const PROGRAM_REGISTERS: u32 = 32u; + +const OP_CONST: u32 = 1u; +const OP_INPUT: u32 = 2u; +const OP_SWIZZLE: u32 = 3u; +const OP_COMBINE: u32 = 4u; +const OP_ADD: u32 = 5u; +const OP_SUB: u32 = 6u; +const OP_MUL: u32 = 7u; +const OP_DIV: u32 = 8u; +const OP_MIN: u32 = 9u; +const OP_MAX: u32 = 10u; +const OP_POW: u32 = 11u; +const OP_LERP: u32 = 12u; +const OP_CLAMP: u32 = 13u; +const OP_INVERT: u32 = 14u; +const OP_LUMINANCE: u32 = 15u; +const OP_RAMP: u32 = 16u; +const OP_XFORM2: u32 = 17u; +const OP_PROJECT: u32 = 18u; +const OP_TEX: u32 = 19u; +const OP_TEXBOX: u32 = 20u; +const OP_NORMALMAP: u32 = 21u; +const OP_BUMP: u32 = 22u; +const OP_PROC: u32 = 23u; +const OP_LABEL: u32 = 24u; + +const IN_POSITION: u32 = 0u; +const IN_POSITION_OBJECT: u32 = 1u; +const IN_NORMAL: u32 = 2u; +const IN_GEOMETRIC_NORMAL: u32 = 3u; +const IN_NORMAL_OBJECT: u32 = 4u; +const IN_UV: u32 = 5u; +const IN_TANGENT: u32 = 6u; +const IN_FOOTPRINT: u32 = 7u; + +const FIELD_NORMAL: u32 = 20u; +const FIELD_DISPLACEMENT: u32 = 21u; + +struct HitCtx { + p: vec3<f32>, + footprint: f32, + p_object: vec3<f32>, + uv_count: u32, + ng: vec3<f32>, + tangent_sign: f32, + ns: vec3<f32>, + n_object: vec3<f32>, + uv01: vec4<f32>, + uv23: vec4<f32>, + dpdu: vec3<f32>, + dpdv: vec3<f32>, + dpdu_object: vec3<f32>, + dpdv_object: vec3<f32>, + tangent: vec3<f32>, +} + +struct ProgramView { + code: u32, + count: u32, + consts: u32, + nconsts: u32, + outputs: u32, + noutputs: u32, +} + +fn program_view(offset: u32) -> ProgramView { + let n = u32(tables[offset + 2u]); + let k = u32(tables[offset + 3u]); + let o = u32(tables[offset + 4u]); + let code = offset + PROGRAM_HEADER; + let consts = code + 4u * n; + return ProgramView(code, n, consts, k, consts + k, o); +} + +fn pk(pv: ProgramView, i: u32) -> f32 { + if i >= pv.nconsts { + return 0.0; + } + return tables[pv.consts + i]; +} + +fn pk4(pv: ProgramView, i: u32) -> vec4<f32> { + return vec4<f32>(pk(pv, i), pk(pv, i + 1u), pk(pv, i + 2u), pk(pv, i + 3u)); +} + +fn reg(r: ptr<function, array<vec4<f32>, 32>>, n: u32) -> vec4<f32> { + if n >= PROGRAM_REGISTERS { + return vec4<f32>(0.0); + } + return (*r)[n]; +} + +fn unit_or(v: vec3<f32>, d: vec3<f32>) -> vec3<f32> { + let r = try_normalize(v); + if r.ok && finite_v3(r.v) { + return r.v; + } + return d; +} + +fn pow_rs(x: f32, y: f32) -> f32 { + var r: f32; + if y == 0.0 || x == 1.0 { + r = 1.0; + } else if x == 0.0 { + r = select(f32_inf(), 0.0, y > 0.0); + } else { + r = pow(x, y); + } + return select(0.0, r, finite_f32(r)); +} + +fn bump_step(c: HitCtx) -> vec2<f32> { + let eps = clampf(0.5 * c.footprint, 1e-6, 1e-2); + let lu = length3(c.dpdu); + let lv = length3(c.dpdv); + let du = select(0.0, eps / lu, lu > 0.0 && finite_f32(lu)); + let dv = select(0.0, eps / lv, lv > 0.0 && finite_f32(lv)); + return vec2<f32>(du, dv); +} + +fn uv_footprint(c: HitCtx) -> f32 { + let area = length3(cross3(c.dpdu, c.dpdv)); + if area > 0.0 && finite_f32(area) { + return c.footprint / sqrt(area); + } + return 0.0; +} + +fn ctx_uv(c: HitCtx, uv_set: u32) -> vec2<f32> { + let s = select(uv_set, 0u, uv_set >= c.uv_count); + switch s { + case 1u: { + return c.uv01.zw; + } + case 2u: { + return c.uv23.xy; + } + case 3u: { + return c.uv23.zw; + } + default: { + return c.uv01.xy; + } + } +} + +fn read_input(c: HitCtx, which: u32, offset: u32, uv_set: u32) -> vec4<f32> { + let d = bump_step(c); + var s = vec2<f32>(0.0); + if offset == 1u { + s = vec2<f32>(d.x, 0.0); + } else if offset == 2u { + s = vec2<f32>(0.0, d.y); + } + let fp = c.footprint; + switch which { + case IN_POSITION: { + return vec4<f32>(c.p + c.dpdu * s.x + c.dpdv * s.y, fp); + } + case IN_POSITION_OBJECT: { + return vec4<f32>(c.p_object + c.dpdu_object * s.x + c.dpdv_object * s.y, fp); + } + case IN_NORMAL: { + return vec4<f32>(c.ns, 0.0); + } + case IN_GEOMETRIC_NORMAL: { + return vec4<f32>(c.ng, 0.0); + } + case IN_NORMAL_OBJECT: { + return vec4<f32>(c.n_object, 0.0); + } + case IN_UV: { + let uv = ctx_uv(c, uv_set); + return vec4<f32>(uv.x + s.x, uv.y + s.y, uv_footprint(c), 0.0); + } + case IN_TANGENT: { + return vec4<f32>(c.tangent, c.tangent_sign); + } + case IN_FOOTPRINT: { + return vec4<f32>(fp, 0.0, 0.0, 0.0); + } + default: { + return vec4<f32>(0.0); + } + } +} + +fn tangent_frame(c: HitCtx, n: vec3<f32>) -> LocalFrame { + let has = dot3(c.tangent, c.tangent) > 0.0; + let raw = select(c.dpdu, c.tangent, has); + var t = orthonormal_basis(n).t; + let tr = try_normalize(raw - n * dot3(n, raw)); + if tr.ok && finite_v3(tr.v) { + t = tr.v; + } + var sign = 1.0; + if has { + sign = select(1.0, -1.0, c.tangent_sign < 0.0); + } else if dot3(cross3(n, t), c.dpdv) < 0.0 { + sign = -1.0; + } + return LocalFrame(t, cross3(n, t) * sign, n); +} + +fn normal_map(c: HitCtx, col: vec4<f32>, strength: f32, flip_y: bool) -> vec4<f32> { + let n = c.ns; + let f = tangent_frame(c, n); + var x = (2.0 * col.x - 1.0) * strength; + var y = (2.0 * col.y - 1.0) * strength; + let z = 2.0 * col.z - 1.0; + if flip_y { + y = -y; + } + if !finite_f32(x) || !finite_f32(y) { + x = 0.0; + y = 0.0; + } + return vec4<f32>(unit_or(f.t * x + f.b * y + n * maxf(z, 0.0), n), 0.0); +} + +fn bump_normal(c: HitCtx, base: vec4<f32>, h: vec4<f32>) -> vec4<f32> { + let n = unit_or(base.xyz, c.ns); + let d = bump_step(c); + let dhdu = select(0.0, (h.y - h.x) / d.x, d.x > 0.0); + let dhdv = select(0.0, (h.z - h.x) / d.y, d.y > 0.0); + let r1 = cross3(c.dpdv, n); + let r2 = cross3(n, c.dpdu); + let det = dot3(c.dpdu, r1); + let grad = (r1 * dhdu + r2 * dhdv) * select(1.0, -1.0, det < 0.0); + return vec4<f32>(unit_or(n * abs(det) - grad, n), 0.0); +} + +fn xform2(a: vec4<f32>, sx: f32, sy: f32, cs: f32, sn: f32, ox: f32, oy: f32) -> vec4<f32> { + let u = a.x * sx; + let v = a.y * sy; + return vec4<f32>(cs * u - sn * v + ox, sn * u + cs * v + oy, a.z * maxf(abs(sx), abs(sy)), a.w); +} + +fn atan_p(x_in: f32) -> f32 { + let s = select(1.0, -1.0, x_in < 0.0); + var x = abs(x_in); + var y = 0.0; + if x > 2.414213562373095 { + y = HALF_PI; + x = -1.0 / x; + } else if x > 0.4142135623730950 { + y = QUARTER_PI; + x = (x - 1.0) / (x + 1.0); + } + let z = x * x; + y += (((8.05374449538e-2 * z - 1.38776856032e-1) * z + 1.99777106478e-1) * z - 3.33329491539e-1) * z * x + x; + return s * y; +} + +fn atan2_p(y: f32, x: f32) -> f32 { + if x == 0.0 { + if y > 0.0 { + return HALF_PI; + } + if y < 0.0 { + return -HALF_PI; + } + return 0.0; + } + var z = atan_p(y / x); + if x < 0.0 { + z += select(PI, -PI, y < 0.0); + } + return z; +} + +fn asin_small(x: f32) -> f32 { + let z = x * x; + return ((((4.2163199048e-2 * z + 2.4181311049e-2) * z + 4.5470025998e-2) * z + 7.4953002686e-2) * z + 1.6666752422e-1) * z * x + x; +} + +fn acos_p(x: f32) -> f32 { + if x < -0.5 { + return PI - 2.0 * asin_small(sqrt(0.5 * (1.0 + x))); + } + if x > 0.5 { + return 2.0 * asin_small(sqrt(0.5 * (1.0 - x))); + } + return HALF_PI - asin_small(x); +} + +fn project(a: vec4<f32>, kind: u32) -> vec4<f32> { + if kind == 1u { + let r = maxf(sqrt(a.x * a.x + a.z * a.z), 1e-3); + return vec4<f32>(atan2_p(a.x, a.z) / TWO_PI + 0.5, a.y, a.w * maxf(1.0 / (TWO_PI * r), 1.0), 0.0); + } + if kind == 2u { + let len = sqrt(a.x * a.x + a.y * a.y + a.z * a.z); + var v = 0.5; + if len > 0.0 { + v = acos_p(clampf(a.y / len, -1.0, 1.0)) * INV_PI; + } + return vec4<f32>(atan2_p(a.x, a.z) / TWO_PI + 0.5, v, a.w * INV_PI / maxf(len, 1e-3), 0.0); + } + return vec4<f32>(a.x, a.y, a.w, 0.0); +} + +fn ramp(pv: ProgramView, x_in: f32, at: u32, mode: u32) -> vec4<f32> { + let want = u32(maxf(pk(pv, at), 0.0)); + let room = select(0u, (pv.nconsts - at - 1u) / 5u, pv.nconsts > at + 1u); + let n = min(want, room); + if n == 0u { + return vec4<f32>(0.0); + } + let s = at + 1u; + let x = select(0.0, x_in, finite_f32(x_in)); + if x <= pk(pv, s) { + return pk4(pv, s + 1u); + } + for (var i = 1u; i < n; i += 1u) { + let p1 = pk(pv, s + 5u * i); + if x < p1 { + let p0 = pk(pv, s + 5u * (i - 1u)); + let c0 = pk4(pv, s + 5u * (i - 1u) + 1u); + if mode == 1u { + return c0; + } + let c1 = pk4(pv, s + 5u * i + 1u); + let span = p1 - p0; + var t = select(1.0, (x - p0) / span, span > 0.0); + if mode == 2u { + t = smooth_step(0.0, 1.0, t); + } + return c0 + (c1 - c0) * t; + } + } + return pk4(pv, s + 5u * (n - 1u) + 1u); +} + +fn tex_box(pv: ProgramView, c: HitCtx, flags: u32, t: u32, a: vec4<f32>, k: u32) -> vec4<f32> { + let fallback = pk4(pv, k); + let sx = pk(pv, k + 4u); + let sy = pk(pv, k + 5u); + let cs = pk(pv, k + 6u); + let sn = pk(pv, k + 7u); + let ox = pk(pv, k + 8u); + let oy = pk(pv, k + 9u); + let blend = clampf(pk(pv, k + 10u), 0.0, 1.0) * 0.5; + let n = select(c.n_object, c.ns, (flags & 16u) != 0u); + let q = max(abs(n) - vec3<f32>(blend), vec3<f32>(0.0)); + let q2 = q * q; + var w = q2 * q2; + let sum = w.x + w.y + w.z; + if sum > 0.0 && finite_f32(sum) { + w = w / sum; + } else { + let an = abs(n); + var d = 2u; + if an.x > an.y { + if an.x > an.z { + d = 0u; + } + } else if an.y > an.z { + d = 1u; + } + w = vec3<f32>(select(0.0, 1.0, d == 0u), select(0.0, 1.0, d == 1u), select(0.0, 1.0, d == 2u)); + } + let wrap = flags & 3u; + let mode = (flags >> 2u) & 3u; + var out = vec4<f32>(0.0); + for (var axis = 0u; axis < 3u; axis += 1u) { + if w[axis] <= 0.0 { + continue; + } + var plane = vec2<f32>(a.x, a.y); + if axis == 0u { + plane = vec2<f32>(a.z, a.y); + } else if axis == 1u { + plane = vec2<f32>(a.x, a.z); + } + let uv = xform2(vec4<f32>(plane, a.w, 0.0), sx, sy, cs, sn, ox, oy); + out += tex_sample(t, uv.xy, uv.z, wrap, mode, fallback) * w[axis]; + } + return out; +} + +fn label_coords(pv: ProgramView, flags: u32, a: vec4<f32>, k: u32, nobj: vec4<f32>) -> vec4<f32> { + let origin = vec3<f32>(pk(pv, k), pk(pv, k + 1u), pk(pv, k + 2u)); + let right = vec3<f32>(pk(pv, k + 3u), pk(pv, k + 4u), pk(pv, k + 5u)); + let up = vec3<f32>(pk(pv, k + 6u), pk(pv, k + 7u), pk(pv, k + 8u)); + let nrm = vec3<f32>(pk(pv, k + 9u), pk(pv, k + 10u), pk(pv, k + 11u)); + let d = a.xyz - origin; + let u = dot3(d, right) + 0.5; + let v = dot3(d, up) + 0.5; + let w = dot3(d, nrm); + let fu = a.w * maxf(length3(right), length3(up)); + var inside = u >= 0.0 && u <= 1.0 && v >= 0.0 && v <= 1.0 && w >= -1.0 && w <= 1.0; + if (flags & 1u) != 0u { + inside = inside && dot3(nobj.xyz, normalize_or(nrm, vec3<f32>(0.0))) > 0.0; + } + return vec4<f32>(u, v, fu, select(0.0, 1.0, inside)); +} + +fn run_proc(pv: ProgramView, r: ptr<function, array<vec4<f32>, 32>>, kind: u32, output: u32, at: u32) -> vec4<f32> { + var args: array<vec4<f32>, 12>; + let n = min(u32(maxf(pk(pv, at), 0.0)), 12u); + for (var j = 0u; j < n; j += 1u) { + args[j] = reg(r, u32(pk(pv, at + 1u + j))); + } + return procedural(kind, output, &args, n); +} + +fn fold_op(op: u32, flags: u32, a: vec4<f32>, b: vec4<f32>, c: vec4<f32>) -> vec4<f32> { + switch op { + case OP_SWIZZLE: { + return vec4<f32>(a[flags & 3u], a[(flags >> 2u) & 3u], a[(flags >> 4u) & 3u], a[(flags >> 6u) & 3u]); + } + case OP_COMBINE: { + return vec4<f32>(a.x, b.x, c.x, 0.0); + } + case OP_ADD: { + return a + b; + } + case OP_SUB: { + return a - b; + } + case OP_MUL: { + return a * b; + } + case OP_DIV: { + return vec4<f32>( + select(a.x / b.x, 0.0, b.x == 0.0), + select(a.y / b.y, 0.0, b.y == 0.0), + select(a.z / b.z, 0.0, b.z == 0.0), + select(a.w / b.w, 0.0, b.w == 0.0), + ); + } + case OP_MIN: { + return vec4<f32>(minf(a.x, b.x), minf(a.y, b.y), minf(a.z, b.z), minf(a.w, b.w)); + } + case OP_MAX: { + return vec4<f32>(maxf(a.x, b.x), maxf(a.y, b.y), maxf(a.z, b.z), maxf(a.w, b.w)); + } + case OP_POW: { + return vec4<f32>( + pow_rs(maxf(a.x, 0.0), b.x), + pow_rs(maxf(a.y, 0.0), b.y), + pow_rs(maxf(a.z, 0.0), b.z), + pow_rs(maxf(a.w, 0.0), b.w), + ); + } + case OP_LERP: { + return a + (b - a) * c.x; + } + case OP_CLAMP: { + return vec4<f32>(clampf(a.x, b.x, c.x), clampf(a.y, b.y, c.y), clampf(a.z, b.z, c.z), clampf(a.w, b.w, c.w)); + } + case OP_INVERT: { + return vec4<f32>(1.0) - a; + } + case OP_LUMINANCE: { + return vec4<f32>(luminance(a.xyz)); + } + case OP_PROJECT: { + return project(a, flags); + } + default: { + return vec4<f32>(0.0); + } + } +} + +fn unit_in(v: f32, d: f32) -> f32 { + return select(d, clampf(v, 0.0, 1.0), finite_f32(v)); +} + +fn ior_in(v: f32, d: f32) -> f32 { + return select(d, clampf(v, 1.0, 4.0), finite_f32(v) && v > 0.0); +} + +fn col_in(c: vec3<f32>, d: vec3<f32>) -> vec3<f32> { + if finite_v3(c) { + return vec3<f32>(clampf(c.x, 0.0, 1.0), clampf(c.y, 0.0, 1.0), clampf(c.z, 0.0, 1.0)); + } + return d; +} + +fn sanitize_inputs(m: ptr<function, BsdfInputs>) { + (*m).base_weight = unit_in((*m).base_weight, 1.0); + (*m).base_color = col_in((*m).base_color, vec3<f32>(0.8)); + (*m).base_metalness = unit_in((*m).base_metalness, 0.0); + (*m).base_diffuse_roughness = unit_in((*m).base_diffuse_roughness, 0.0); + (*m).specular_weight = unit_in((*m).specular_weight, 1.0); + (*m).specular_color = col_in((*m).specular_color, vec3<f32>(1.0)); + (*m).specular_roughness = unit_in((*m).specular_roughness, 0.3); + (*m).specular_ior = ior_in((*m).specular_ior, 1.5); + (*m).specular_anisotropy = unit_in((*m).specular_anisotropy, 0.0); + (*m).transmission_weight = unit_in((*m).transmission_weight, 0.0); + (*m).transmission_color = col_in((*m).transmission_color, vec3<f32>(1.0)); + (*m).coat_weight = unit_in((*m).coat_weight, 0.0); + (*m).coat_color = col_in((*m).coat_color, vec3<f32>(1.0)); + (*m).coat_roughness = unit_in((*m).coat_roughness, 0.0); + (*m).coat_ior = ior_in((*m).coat_ior, 1.6); + (*m).fuzz_weight = unit_in((*m).fuzz_weight, 0.0); + (*m).fuzz_color = col_in((*m).fuzz_color, vec3<f32>(1.0)); + (*m).fuzz_roughness = unit_in((*m).fuzz_roughness, 0.5); + let e = (*m).emission; + (*m).emission = select(vec3<f32>(0.0), max(e, vec3<f32>(0.0)), finite_v3(e)); + (*m).opacity = unit_in((*m).opacity, 1.0); + (*m).eta = (*m).specular_ior; +} + +fn set_field(m: ptr<function, BsdfInputs>, field: u32, v: vec4<f32>) { + switch field { + case 0u: { + (*m).base_weight = v.x; + } + case 1u: { + (*m).base_color = v.xyz; + } + case 2u: { + (*m).base_metalness = v.x; + } + case 3u: { + (*m).base_diffuse_roughness = v.x; + } + case 4u: { + (*m).specular_weight = v.x; + } + case 5u: { + (*m).specular_color = v.xyz; + } + case 6u: { + (*m).specular_roughness = v.x; + } + case 7u: { + (*m).specular_ior = v.x; + } + case 8u: { + (*m).specular_anisotropy = v.x; + } + case 9u: { + (*m).transmission_weight = v.x; + } + case 10u: { + (*m).transmission_color = v.xyz; + } + case 11u: { + (*m).coat_weight = v.x; + } + case 12u: { + (*m).coat_color = v.xyz; + } + case 13u: { + (*m).coat_roughness = v.x; + } + case 14u: { + (*m).coat_ior = v.x; + } + case 15u: { + (*m).fuzz_weight = v.x; + } + case 16u: { + (*m).fuzz_color = v.xyz; + } + case 17u: { + (*m).fuzz_roughness = v.x; + } + case 18u: { + (*m).emission = v.xyz; + } + case 19u: { + (*m).opacity = v.x; + } + default: {} + } +} + +fn run_program(offset: u32, ctx: HitCtx, m: ptr<function, BsdfInputs>, ns: ptr<function, vec3<f32>>) { + let pv = program_view(offset); + var r: array<vec4<f32>, 32>; + for (var pc = 0u; pc < pv.count; pc += 1u) { + let at = pv.code + 4u * pc; + let w0 = u32(tables[at]); + let op = w0 & 255u; + let dst = (w0 >> 8u) & 255u; + let flags = (w0 >> 16u) & 255u; + let ia = u32(tables[at + 1u]); + let ib = u32(tables[at + 2u]); + let ic = u32(tables[at + 3u]); + let a = reg(&r, ia); + var v = vec4<f32>(0.0); + switch op { + case OP_CONST: { + v = pk4(pv, ia); + } + case OP_INPUT: { + v = read_input(ctx, flags & 15u, flags >> 4u, ia); + } + case OP_RAMP: { + v = ramp(pv, a.x, ib, flags); + } + case OP_XFORM2: { + v = xform2(a, pk(pv, ib), pk(pv, ib + 1u), pk(pv, ib + 2u), pk(pv, ib + 3u), pk(pv, ib + 4u), pk(pv, ib + 5u)); + } + case OP_TEX: { + v = tex_sample(ib, a.xy, a.z, flags & 3u, (flags >> 2u) & 3u, pk4(pv, ic)); + } + case OP_TEXBOX: { + if ic + 11u <= pv.nconsts { + v = tex_box(pv, ctx, flags, ib, a, ic); + } + } + case OP_NORMALMAP: { + v = normal_map(ctx, a, reg(&r, ib).x, (flags & 1u) != 0u); + } + case OP_BUMP: { + v = bump_normal(ctx, a, reg(&r, ib)); + } + case OP_PROC: { + v = run_proc(pv, &r, flags, ib, ia); + } + case OP_LABEL: { + v = label_coords(pv, flags, a, ib, reg(&r, ic)); + } + default: { + v = fold_op(op, flags, a, reg(&r, ib), reg(&r, ic)); + } + } + if dst < PROGRAM_REGISTERS { + r[dst] = v; + } + } + for (var j = 0u; j < pv.noutputs; j += 1u) { + let w = u32(tables[pv.outputs + j]); + let field = w & 255u; + let v = reg(&r, (w >> 8u) & 255u); + if field == FIELD_NORMAL { + let n = try_normalize(v.xyz); + if n.ok && finite_v3(n.v) { + *ns = n.v; + } + } else if field != FIELD_DISPLACEMENT { + set_field(m, field, v); + } + } + sanitize_inputs(m); +} diff --git a/native/crates/fsh-render-gpu/src/shaders/surface.wgsl b/native/crates/fsh-render-gpu/src/shaders/surface.wgsl index f0dc90c3..feb0a938 100644 --- a/native/crates/fsh-render-gpu/src/shaders/surface.wgsl +++ b/native/crates/fsh-render-gpu/src/shaders/surface.wgsl @@ -1,6 +1,7 @@ #include "bindings.wgsl" #include "math.wgsl" #include "bsdf.wgsl" +#include "program.wgsl" #include "trace.wgsl" #include "features.wgsl" @@ -49,13 +50,14 @@ fn hit_point(inst: u32, slot: u32, u: f32, v: f32) -> vec3<f32> { fn shading_normal(inst: u32, slot: u32, b1: f32, b2: f32) -> Normalized { let rec = instances[inst]; - if !USE_NORMALS || rec.vertex_base == NONE { + if !USE_NORMALS || (rec.flags & INST_NORMALS) == 0u { return Normalized(vec3<f32>(0.0), false); } let t = tris[slot]; - let na = verts[rec.vertex_base + t.i0].normal; - let nb = verts[rec.vertex_base + t.i1].normal; - let nc = verts[rec.vertex_base + t.i2].normal; + let stride = vertex_stride(rec.flags); + let na = verts[rec.vertex_base + t.i0 * stride].v.xyz; + let nb = verts[rec.vertex_base + t.i1 * stride].v.xyz; + let nc = verts[rec.vertex_base + t.i2 * stride].v.xyz; let r = try_normalize(instance_normal(rec.inv, na * (1.0 - b1 - b2) + nb * b1 + nc * b2)); return Normalized(r.v, r.ok && finite_v3(r.v)); } @@ -69,6 +71,95 @@ fn instance_inputs(inst: u32) -> BsdfInputs { return m; } +fn vertex_slot(rec: Instance, corner: u32, slot: u32) -> vec4<f32> { + return verts[rec.vertex_base + corner * vertex_stride(rec.flags) + slot].v; +} + +fn hit_ctx(inst: u32, slot: u32, b1: f32, b2: f32, p: vec3<f32>, ng: vec3<f32>, ns: vec3<f32>, footprint: f32) -> HitCtx { + let rec = instances[inst]; + let t = tris[slot]; + let b0 = 1.0 - b1 - b2; + var c: HitCtx; + c.p = p; + c.footprint = footprint; + c.p_object = t.c0 * b0 + t.c1 * b1 + t.c2 * b2; + c.ng = ng; + c.ns = ns; + var n_object = unit_or(cross3(t.c1 - t.c0, t.c2 - t.c0), vec3<f32>(0.0, 0.0, 1.0)); + if (rec.flags & INST_NORMALS) != 0u { + let n = vertex_slot(rec, t.i0, 0u).xyz * b0 + vertex_slot(rec, t.i1, 0u).xyz * b1 + vertex_slot(rec, t.i2, 0u).xyz * b2; + n_object = unit_or(n, n_object); + } + c.n_object = n_object; + c.tangent_sign = 1.0; + let sets = vertex_uv_sets(rec.flags); + let first = select(0u, 1u, (rec.flags & INST_NORMALS) != 0u); + c.uv_count = sets; + var ok = false; + if sets > 0u { + let a0 = vertex_slot(rec, t.i0, first); + let a1 = vertex_slot(rec, t.i1, first); + let a2 = vertex_slot(rec, t.i2, first); + c.uv01 = a0 * b0 + a1 * b1 + a2 * b2; + if sets > 2u { + c.uv23 = vertex_slot(rec, t.i0, first + 1u) * b0 + vertex_slot(rec, t.i1, first + 1u) * b1 + vertex_slot(rec, t.i2, first + 1u) * b2; + } + let d1 = a1.xy - a0.xy; + let d2 = a2.xy - a0.xy; + let det = d1.x * d2.y - d1.y * d2.x; + let p1 = t.c1 - t.c0; + let p2 = t.c2 - t.c0; + if finite_f32(det) && abs(det) >= 1e-12 { + let inv = 1.0 / det; + let du = (p1 * d2.y - p2 * d1.y) * inv; + let dv = (p2 * d1.x - p1 * d2.x) * inv; + if finite_v3(du) && finite_v3(dv) { + c.dpdu_object = du; + c.dpdv_object = dv; + c.dpdu = instance_vector(rec.world, du); + c.dpdv = instance_vector(rec.world, dv); + ok = true; + } + } + } + if !ok { + let fw = orthonormal_basis(ns); + let fo = orthonormal_basis(c.n_object); + c.dpdu = fw.t; + c.dpdv = fw.b; + c.dpdu_object = fo.t; + c.dpdv_object = fo.b; + } + if (rec.flags & INST_TANGENTS) != 0u { + let last = vertex_stride(rec.flags) - 1u; + let tg = vertex_slot(rec, t.i0, last) * b0 + vertex_slot(rec, t.i1, last) * b1 + vertex_slot(rec, t.i2, last) * b2; + let tw = instance_vector(rec.world, tg.xyz); + let tu = try_normalize(tw - ns * dot3(ns, tw)); + if tu.ok && finite_v3(tu.v) { + c.tangent = tu.v; + let flip = select(1.0, -1.0, (rec.flags & INST_FLIP) != 0u); + c.tangent_sign = select(flip, -flip, tg.w < 0.0); + } + } + return c; +} + +fn shade_inputs(inst: u32, slot: u32, b1: f32, b2: f32, p: vec3<f32>, ng: vec3<f32>, ns: ptr<function, vec3<f32>>, footprint: f32) -> BsdfInputs { + let rec = instances[inst]; + var m = bsdf_inputs(rec.material); + if USE_PROGRAMS { + let mat = materials[rec.material]; + if (mat.flags & MAT_PROGRAM) != 0u && mat.program != NONE { + let ctx = hit_ctx(inst, slot, b1, b2, p, ng, *ns, footprint); + run_program(mat.program, ctx, &m, ns); + } + } + if (rec.flags & INST_TINT) != 0u { + m.base_color = rec.tint; + } + return m; +} + fn instance_eta(inst: u32) -> f32 { return materials[instances[inst].material].eta; } diff --git a/native/crates/fsh-render-gpu/src/shaders/texture.wgsl b/native/crates/fsh-render-gpu/src/shaders/texture.wgsl new file mode 100644 index 00000000..365c841f --- /dev/null +++ b/native/crates/fsh-render-gpu/src/shaders/texture.wgsl @@ -0,0 +1,161 @@ +#include "bindings.wgsl" +#include "math.wgsl" + +const TEX_SPACE_SRGB: u32 = 0u; +const TEX_SPACE_LINEAR: u32 = 1u; +const TEX_STORAGE_RGBA8: u32 = 0u; +const TEX_STORAGE_RGB8: u32 = 2u; +const TEX_WRAP_CLAMP: u32 = 1u; +const TEX_WRAP_MIRROR: u32 = 2u; +const TEX_FILTER_NEAREST: u32 = 0u; +const TEX_FILTER_BILINEAR: u32 = 1u; + +struct TexImage { + levels: u32, + space: u32, + storage: u32, + level0: u32, +} + +struct TexLevel { + width: u32, + height: u32, + base: u32, +} + +fn tex_word(i: u32) -> u32 { + return u32(tables[i]); +} + +fn tex_image(t: u32) -> TexImage { + if frame.textures == NONE || t >= tex_word(frame.textures) { + return TexImage(0u, 0u, 0u, 0u); + } + let r = frame.textures + 4u + 4u * t; + return TexImage(tex_word(r), tex_word(r + 1u), tex_word(r + 2u), frame.textures + tex_word(r + 3u)); +} + +fn tex_level(img: TexImage, l: u32) -> TexLevel { + let r = img.level0 + 4u * l; + return TexLevel(tex_word(r), tex_word(r + 1u), frame.textures + tex_word(r + 2u) * 65536u + tex_word(r + 3u)); +} + +fn tex_texel(img: TexImage, lv: TexLevel, x: u32, y: u32) -> vec4<f32> { + let i = y * lv.width + x; + if img.storage == TEX_STORAGE_RGB8 { + let w = tex_word(lv.base + i); + let c = vec3<u32>(w & 255u, (w >> 8u) & 255u, w >> 16u); + if img.space == TEX_SPACE_SRGB { + let lut = frame.textures + tex_word(frame.textures + 1u); + return vec4<f32>(tables[lut + c.x], tables[lut + c.y], tables[lut + c.z], 1.0); + } + return vec4<f32>(f32(c.x) / 255.0, f32(c.y) / 255.0, f32(c.z) / 255.0, 1.0); + } + if img.storage == TEX_STORAGE_RGBA8 { + let o = lv.base + 2u * i; + let rg = tex_word(o); + let ba = tex_word(o + 1u); + let c = vec4<u32>(rg & 255u, rg >> 8u, ba & 255u, ba >> 8u); + if img.space == TEX_SPACE_SRGB { + let lut = frame.textures + tex_word(frame.textures + 1u); + return vec4<f32>(tables[lut + c.x], tables[lut + c.y], tables[lut + c.z], f32(c.w) / 255.0); + } + return vec4<f32>(f32(c.x) / 255.0, f32(c.y) / 255.0, f32(c.z) / 255.0, f32(c.w) / 255.0); + } + let o = lv.base + 4u * i; + return vec4<f32>(tables[o], tables[o + 1u], tables[o + 2u], tables[o + 3u]); +} + +fn tex_wrap(i: i32, n: i32, mode: u32) -> u32 { + if mode == TEX_WRAP_CLAMP { + return u32(clamp(i, 0, n - 1)); + } + if mode == TEX_WRAP_MIRROR { + let p = 2 * n; + var m = i % p; + if m < 0 { + m += p; + } + if m >= n { + m = p - 1 - m; + } + return u32(m); + } + var m = i % n; + if m < 0 { + m += n; + } + return u32(m); +} + +fn tex_coord(x: f32) -> i32 { + return i32(clamp(x, -1073741824.0, 1073741824.0)); +} + +fn tex_nearest(img: TexImage, uv: vec2<f32>, wrap: u32) -> vec4<f32> { + let lv = tex_level(img, 0u); + let w = i32(lv.width); + let h = i32(lv.height); + let x = tex_wrap(tex_coord(floor(uv.x * f32(w))), w, wrap); + let y = tex_wrap(tex_coord(floor((1.0 - uv.y) * f32(h))), h, wrap); + return tex_texel(img, lv, x, y); +} + +fn tex_bilinear(img: TexImage, l: u32, uv: vec2<f32>, wrap: u32) -> vec4<f32> { + let lv = tex_level(img, l); + let w = i32(lv.width); + let h = i32(lv.height); + let x = uv.x * f32(w) - 0.5; + let y = (1.0 - uv.y) * f32(h) - 0.5; + let fx = floor(x); + let fy = floor(y); + let tx = x - fx; + let ty = y - fy; + let ix = tex_coord(fx); + let iy = tex_coord(fy); + let x0 = tex_wrap(ix, w, wrap); + let x1 = tex_wrap(ix + 1, w, wrap); + let y0 = tex_wrap(iy, h, wrap); + let y1 = tex_wrap(iy + 1, h, wrap); + let top = tex_texel(img, lv, x0, y0) * (1.0 - tx) + tex_texel(img, lv, x1, y0) * tx; + let bottom = tex_texel(img, lv, x0, y1) * (1.0 - tx) + tex_texel(img, lv, x1, y1) * tx; + return top * (1.0 - ty) + bottom * ty; +} + +fn tex_to_shading(space: u32, v: vec4<f32>) -> vec4<f32> { + if space == TEX_SPACE_SRGB || space == TEX_SPACE_LINEAR { + return vec4<f32>( + 0.6130974 * v.x + 0.33952315 * v.y + 0.04737945 * v.z, + 0.07019372 * v.x + 0.9163539 * v.y + 0.0134524 * v.z, + 0.020615593 * v.x + 0.10956977 * v.y + 0.8698146 * v.z, + v.w, + ); + } + return v; +} + +fn tex_sample(t: u32, uv: vec2<f32>, footprint: f32, wrap: u32, mode: u32, fallback: vec4<f32>) -> vec4<f32> { + let img = tex_image(t); + if img.levels == 0u || !finite_f32(uv.x) || !finite_f32(uv.y) { + return fallback; + } + var v: vec4<f32>; + if mode == TEX_FILTER_NEAREST { + v = tex_nearest(img, uv, wrap); + } else if mode == TEX_FILTER_BILINEAR { + v = tex_bilinear(img, 0u, uv, wrap); + } else { + let lv = tex_level(img, 0u); + let fp = select(0.0, maxf(footprint, 0.0), finite_f32(footprint)); + let size = maxf(maxf(fp * f32(lv.width), fp * f32(lv.height)), 1e-8); + let lod = clampf(log2(size), 0.0, f32(img.levels - 1u)); + let l0 = floor(lod); + let f = lod - l0; + let i0 = u32(l0); + v = tex_bilinear(img, i0, uv, wrap); + if f > 0.0 && i0 + 1u < img.levels { + v = v + (tex_bilinear(img, i0 + 1u, uv, wrap) - v) * f; + } + } + return tex_to_shading(img.space, v); +} diff --git a/native/crates/fsh-render-gpu/src/texpack.rs b/native/crates/fsh-render-gpu/src/texpack.rs new file mode 100644 index 00000000..4e7f3b1b --- /dev/null +++ b/native/crates/fsh-render-gpu/src/texpack.rs @@ -0,0 +1,123 @@ +use fsh_materials::{srgb8_table, Texels, TextureImage, TextureLevel, TextureSet}; + +use crate::layout::NONE; + +/// Floats of the directory header: image count, LUT offset, two zero words. +pub const TEXTURE_HEADER: usize = 4; +/// Floats per image record: levels, colour space, storage, first level record offset. +pub const TEXTURE_RECORD: usize = 4; +/// Floats per level record: width, height, texel offset high 16 bits, low 16 bits. +pub const LEVEL_RECORD: usize = 4; +/// Floats of the sRGB decode table. +pub const SRGB_LUT: usize = 256; +/// `storage` word: four 8-bit channels in two floats per texel (`r + 256 g`, `b + 256 a`). +pub const STORAGE_RGBA8: u32 = 0; +/// `storage` word: four floats per texel. +pub const STORAGE_RGBAF32: u32 = 1; +/// `storage` word: three 8-bit channels in one float per texel (`r + 256 g + 65536 b`, exact below 2^24) and alpha 1, +/// for 8-bit images whose every alpha byte is 255 (half the memory of `STORAGE_RGBA8`). +pub const STORAGE_RGB8: u32 = 2; + +fn storage(levels: &[TextureLevel]) -> u32 { + let opaque = |l: &TextureLevel| matches!(&l.texels, Texels::Rgba8(v) if v.as_chunks::<4>().0.iter().all(|t| t[3] == 255)); + match levels.first().map(|l| &l.texels) { + Some(Texels::RgbaF32(_)) => STORAGE_RGBAF32, + _ if levels.iter().all(opaque) => STORAGE_RGB8, + _ => STORAGE_RGBA8, + } +} + +fn floats_per_texel(storage: u32) -> usize { + match storage { + STORAGE_RGB8 => 1, + STORAGE_RGBA8 => 2, + _ => 4, + } +} + +fn level_ok(w: u32, h: u32, texels: &Texels) -> bool { + let n = w as usize * h as usize * 4; + w > 0 + && h > 0 + && match texels { + Texels::Rgba8(v) => v.len() == n, + Texels::RgbaF32(v) => v.len() == n, + } +} + +/// The levels the CPU sampler uses: the leading run of well-formed levels with the storage of level 0. +fn usable(img: &TextureImage) -> &[TextureLevel] { + let Some(first) = img.levels.first() else { return &[] }; + let rgba8 = matches!(first.texels, Texels::Rgba8(_)); + let n = img.levels.iter().take_while(|l| level_ok(l.width, l.height, &l.texels) && matches!(l.texels, Texels::Rgba8(_)) == rgba8).count(); + &img.levels[..n] +} + +/// Floats the texture block of `set` takes in `tables` (0 when there is nothing to pack). +pub fn block_len(set: Option<&TextureSet>) -> usize { + let Some(set) = set.filter(|s| !s.images.is_empty()) else { return 0 }; + let mut n = TEXTURE_HEADER + TEXTURE_RECORD * set.images.len() + SRGB_LUT; + for levels in set.images.iter().flatten().map(|i| usable(i)) { + n += LEVEL_RECORD * levels.len(); + let per = floats_per_texel(storage(levels)); + for l in levels { + n += per * l.width as usize * l.height as usize; + } + } + n +} + +/// Appends the texture block of `set` to `tables` and returns the float offset of its directory (`NONE` when there is +/// nothing to pack). Every offset inside the block is relative to the directory, so the words stay exact floats +/// however far into `tables` the block starts. An image that is missing or whose level 0 is malformed gets zero levels +/// and samples its fallback; levels after a malformed one are left out, as the CPU sampler ignores them. +pub fn append(set: Option<&TextureSet>, tables: &mut Vec<f32>) -> u32 { + let Some(set) = set.filter(|s| !s.images.is_empty()) else { return NONE }; + let dir = tables.len(); + tables.reserve(block_len(Some(set))); + let count = set.images.len(); + let images: Vec<Option<(&TextureImage, &[TextureLevel], u32)>> = set + .images + .iter() + .map(|i| i.as_deref().map(|i| (i, usable(i))).filter(|(_, l)| !l.is_empty()).map(|(i, l)| (i, l, storage(l)))) + .collect(); + let level_records: usize = images.iter().flatten().map(|(_, l, _)| l.len()).sum(); + let lut = TEXTURE_HEADER + TEXTURE_RECORD * count + LEVEL_RECORD * level_records; + tables.extend_from_slice(&[count as f32, lut as f32, 0.0, 0.0]); + let mut level_at = TEXTURE_HEADER + TEXTURE_RECORD * count; + for img in &images { + match img { + Some((i, levels, storage)) => { + tables.extend_from_slice(&[levels.len() as f32, i.colour_space.code() as f32, *storage as f32, level_at as f32]); + level_at += LEVEL_RECORD * levels.len(); + } + None => tables.extend_from_slice(&[0.0; TEXTURE_RECORD]), + } + } + let mut texel_at = lut + SRGB_LUT; + for (_, levels, storage) in images.iter().flatten() { + for l in levels.iter() { + let at = texel_at as u64; + tables.extend_from_slice(&[l.width as f32, l.height as f32, (at >> 16) as f32, (at & 0xffff) as f32]); + texel_at += floats_per_texel(*storage) * l.width as usize * l.height as usize; + } + } + tables.extend_from_slice(srgb8_table()); + for (_, levels, storage) in images.iter().flatten() { + for l in levels.iter() { + match &l.texels { + Texels::Rgba8(v) if *storage == STORAGE_RGB8 => { + tables.extend(v.as_chunks::<4>().0.iter().map(|t| t[0] as f32 + 256.0 * t[1] as f32 + 65536.0 * t[2] as f32)); + } + Texels::Rgba8(v) => { + for t in v.as_chunks::<4>().0 { + tables.push(t[0] as f32 + 256.0 * t[1] as f32); + tables.push(t[2] as f32 + 256.0 * t[3] as f32); + } + } + Texels::RgbaF32(v) => tables.extend_from_slice(v), + } + } + } + dir as u32 +} diff --git a/native/crates/fsh-render-gpu/src/validate.rs b/native/crates/fsh-render-gpu/src/validate.rs index 8c904cb6..c419c961 100644 --- a/native/crates/fsh-render-gpu/src/validate.rs +++ b/native/crates/fsh-render-gpu/src/validate.rs @@ -2,7 +2,10 @@ use std::mem::{offset_of, size_of}; use naga::valid::{Capabilities, ValidationFlags, Validator}; +use fsh_materials::Op; + use crate::layout::{AccumPixel, Band, BvhNode, Frame, Instance, Light, Material, Sobol, Triangle, Vertex}; +use crate::refusals::{GPU_OPCODES, OP_LABEL}; use crate::shaders::{assemble, assemble_variant, SOURCES}; /// Result of validating one assembled WGSL file. @@ -50,6 +53,46 @@ pub fn validate_all() -> Vec<ShaderReport> { out } +/// Checks program.wgsl against the refusal list: every opcode `GPU_OPCODES` admits (opcode 0, `Nop`, writes zero +/// without a constant, as on the CPU) must have an `OP_<NAME>` constant of the contract's value; opcodes outside the +/// mask are reported as refused (`material_program`). Returns one line per finding. +pub fn program_report() -> (bool, Vec<String>) { + let module = match assemble("program.wgsl").map_err(|e| e.to_string()).and_then(|t| parse(&t)) { + Ok(m) => m, + Err(e) => return (false, vec![e]), + }; + let value = |name: &str| -> Option<u32> { + let (_, c) = module.constants.iter().find(|(_, c)| c.name.as_deref() == Some(name))?; + match module.global_expressions[c.init] { + naga::Expression::Literal(naga::Literal::U32(v)) => Some(v), + _ => None, + } + }; + let mut names: Vec<(u32, String)> = + Op::ALL.iter().filter(|o| **o != Op::Nop).map(|o| (*o as u32, format!("OP_{}", o.name().to_uppercase()))).collect(); + if !names.iter().any(|(n, _)| *n == OP_LABEL) { + names.push((OP_LABEL, "OP_LABEL".into())); + } + let mut ok = true; + let mut lines = Vec::new(); + for (n, name) in names { + match (GPU_OPCODES & (1 << n) != 0, value(&name)) { + (true, Some(v)) if v == n => {} + (true, Some(v)) => { + ok = false; + lines.push(format!("{name} is {v} in program.wgsl, the contract says {n}")); + } + (true, None) => { + ok = false; + lines.push(format!("{name} ({n}) is admitted by GPU_OPCODES but program.wgsl has no such constant")); + } + (false, _) => lines.push(format!("{name} ({n}) is refused as material_program")), + } + } + lines.insert(0, format!("program.wgsl: {} opcodes admitted, constants {}", GPU_OPCODES.count_ones(), if ok { "match" } else { "MISMATCH" })); + (ok, lines) +} + macro_rules! fields { ($t:ty, $($f:ident),+) => { (stringify!($t), size_of::<$t>(), vec![$((stringify!($f), offset_of!($t, $f))),+]) @@ -66,16 +109,17 @@ fn host_layouts() -> Vec<HostLayout> { ground_reflection, background_colour, ground_material, env_w, env_h, env_total, env_scale, env_cos_r, env_sin_r, env_black, env_pixels, env_func, env_cond, env_marg, light_count, env_prob, lamp_total, instance_count, material_count, top_count, node_count, triangle_count, stack_bound, bsdf_cond, bsdf_cond_avg, bsdf_diel, - bsdf_sheen, flags, revision, samples, pass_index, region_x0, region_y0, region_x1, region_y1), + bsdf_sheen, flags, revision, samples, pass_index, region_x0, region_y0, region_x1, region_y1, textures, pad0, + pad1, pad2), fields!(Sobol, v), fields!(BvhNode, min, data, max, info), fields!(Triangle, c0, i0, c1, i1, c2, i2), - fields!(Vertex, normal, pad), + fields!(Vertex, v), fields!(Instance, world, inv, tint, material, root, vertex_base, mask, flags), fields!(Material, base_color, base_weight, specular_color, base_metalness, transmission_color, base_diffuse_roughness, coat_color, specular_weight, fuzz_color, specular_roughness, emission, specular_ior, specular_anisotropy, transmission_weight, coat_weight, coat_roughness, coat_ior, fuzz_weight, fuzz_roughness, - opacity, thin_walled, eta, program, flags), + opacity, thin_walled, eta, program, flags, film_weight, film_thickness, film_ior, dispersion), fields!(Light, kind, flags, prob, cdf, emission, area, p, radius, u, cos_inner, v, cos_outer, n, importance), fields!(Band, y0, rows, width, first_pixel, row_step, row_phase, adapt_warmup, adapt_on, adapt_threshold, adapt_revive, adapt_floor, pad), diff --git a/native/crates/fsh-scene/Cargo.toml b/native/crates/fsh-scene/Cargo.toml index ce6cd4b1..7e1c9833 100644 --- a/native/crates/fsh-scene/Cargo.toml +++ b/native/crates/fsh-scene/Cargo.toml @@ -1,11 +1,12 @@ [package] name = "fsh-scene" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false [dependencies] fsh-core = { path = "../fsh-core" } +fsh-materials = { path = "../fsh-materials" } serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" diff --git a/native/crates/fsh-scene/src/catalogue.rs b/native/crates/fsh-scene/src/catalogue.rs index ff3fd685..f836f368 100644 --- a/native/crates/fsh-scene/src/catalogue.rs +++ b/native/crates/fsh-scene/src/catalogue.rs @@ -1,5 +1,6 @@ use crate::command::{ChangeLevel, TABLE}; use crate::material::{SurfaceParams, TextureRef}; +use crate::slots::MaterialInput; use crate::node::{Light, RayVisibility}; use crate::settings::{Camera, DocumentInfo, Environment, Ground, ImageStyle, RenderSettings}; use serde::Serialize; @@ -26,6 +27,9 @@ const MERGEABLE: &[&str] = &[ "scene.set_cutaway", "scene.set_pivot", "material.set_params", + "material.set_slot", + "material.set_graph", + "material.label_set", "camera.set", "environment.set", "ground.set", @@ -266,13 +270,121 @@ fn mesh_schema() -> Value { ) } +fn type_ids() -> Vec<&'static str> { + crate::types::material_types().iter().map(|t| t.id).collect() +} + +fn input_names(slottable: bool) -> Vec<&'static str> { + MaterialInput::ALL.iter().filter(|i| !slottable || i.slottable()).map(|i| i.name()).collect() +} + +fn projection_schema() -> Value { + json!({"oneOf": [ + {"type": "object", "properties": {"kind": {"const": "uv"}, "set": {"type": "integer", "minimum": 0, "maximum": 3, "default": 0}}, "required": ["kind"]}, + {"type": "object", "properties": {"kind": {"const": "box"}, "blend": {"type": "number", "minimum": 0, "maximum": 1, "default": 0.5}}, "required": ["kind"]}, + {"type": "object", "properties": {"kind": {"const": "planar"}}, "required": ["kind"]}, + {"type": "object", "properties": {"kind": {"const": "cylindrical"}}, "required": ["kind"]}, + {"type": "object", "properties": {"kind": {"const": "spherical"}}, "required": ["kind"]} + ], "description": "Coordinate source: a uv set, or a projection of the object-space position in metres"}) +} + +fn uv_transform_schema() -> Value { + let pair = |d: &str, v: f32| json!({"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2, "default": [v, v], "description": d}); + obj( + vec![ + ("offset", pair("Added after rotation", 0.0)), + ("scale", pair("Repeats per uv unit, or per metre for projections", 1.0)), + ("rotation", json!({"type": "number", "default": 0.0, "description": "Radians, counter-clockwise"})), + ("space", str_enum(&["object", "world"], "Space projections read positions in")), + ], + &[], + ) +} + +fn colour_space_schema() -> Value { + opt(str_enum(&["srgb", "linear", "acescg", "data"], "Colour space; by default sRGB for colour inputs and data otherwise")) +} + +fn slot_schema() -> Value { + obj( + vec![ + ("texture", key("Document texture")), + ("projection", projection_schema()), + ("transform", uv_transform_schema()), + ("wrap", str_enum(&["repeat", "clamp", "mirror"], "Wrapping outside 0..1")), + ("filter", str_enum(&["nearest", "bilinear", "trilinear"], "Filtering")), + ("colour_space", colour_space_schema()), + ("channel", str_enum(&["rgb", "r", "g", "b", "a", "luminance"], "Channel a number input reads (rgb reads the luminance)")), + ("range", json!({"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2, "default": [0.0, 1.0], "description": "Number inputs: value = range[0] + t * (range[1] - range[0])"})), + ("invert", boolean("t = 1 - t before the range")), + ("multiply", boolean("Multiply by the input's constant value")), + ("strength", json!({"type": "number", "description": "Normal: tangent xy scale; bump: metres of height per unit; displacement: metres per unit"})), + ("flip_y", boolean("Normal map green points down (DirectX)")), + ("fallback", opt(json!({"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4, "description": "RGBA used when the image is missing; the input's constant when null"}))), + ], + &[], + ) +} + +fn graph_schema() -> Value { + let sock = json!({"type": "array", "prefixItems": [{"type": "integer", "minimum": 1}, {"type": "string"}], "minItems": 2, "maxItems": 2, "description": "[node id, socket name]"}); + let kinds: Vec<&str> = crate::graph::graph_kinds().iter().map(|k| k.id).collect(); + obj( + vec![ + ( + "nodes", + json!({"type": "object", "description": "Nodes by id (decimal string); settings sit beside kind (see material.node_kinds)", + "additionalProperties": {"type": "object", "properties": { + "kind": {"type": "string", "enum": kinds}, + "inputs": {"type": "object", "description": "Values of unlinked inputs: a number or [r, g, b]"}, + "position": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, + "label": {"type": "string"} + }, "required": ["kind"]}}), + ), + ("links", json!({"type": "array", "items": {"type": "object", "properties": {"from": sock, "to": sock}, "required": ["from", "to"]}})), + ( + "outputs", + json!({"type": "object", "description": "Material input driven by an output socket", "propertyNames": {"enum": input_names(false)}, "additionalProperties": sock}), + ), + ], + &[], + ) +} + +fn label_schema() -> Value { + let unit = |d: &str| json!({"anyOf": [{"type": "number", "minimum": 0, "maximum": 1}, {"type": "null"}], "description": d}); + obj( + vec![ + ("id", json!({"type": "integer", "minimum": 0, "description": "Id unique within the material; allocated when 0 or absent"})), + ("name", string("Display name")), + ("texture", opt(key("Image texture; the label draws nothing without one"))), + ("colour_space", colour_space_schema()), + ("origin", triple("Centre on the surface, object space of the part (metres)")), + ("normal", triple("Direction the label faces, object space")), + ("up", triple("Direction of the image's top before rotation, object space; not parallel to normal")), + ("size", json!({"type": "array", "items": {"type": "number", "exclusiveMinimum": 0}, "minItems": 2, "maxItems": 2, "description": "Width and height in metres"})), + ("rotation", json!({"type": "number", "description": "Radians about the normal, counter-clockwise seen from the front"})), + ("depth", json!({"type": "number", "exclusiveMinimum": 0, "description": "Thickness of the projection volume in metres, centred on the origin"})), + ("opacity", json!({"type": "number", "minimum": 0, "maximum": 1})), + ("two_sided", boolean("Also print on surfaces facing away from the normal")), + ("visible", boolean("Draw the label")), + ("roughness", unit("Specular roughness under the label; null keeps the surface's")), + ("metalness", unit("Metalness under the label; null keeps the surface's")), + ], + &[], + ) +} + fn material_schema() -> Value { obj( vec![ ("name", string("Display name")), - ("type_id", string("Catalogue type: generic, plastic, metal, glass, paint, ...")), + ("type_id", string("Material type id (material.types): generic, plastic, metal, glass, paint, ...")), ("params", describe(block::<SurfaceParams>(), "Surface parameters")), ("textures", keys("Texture keys")), + ("slots", json!({"type": "object", "description": "Texture slots by input", "propertyNames": {"enum": input_names(true)}, "additionalProperties": slot_schema()})), + ("graph", opt(describe(graph_schema(), "Node graph"))), + ("labels", json!({"type": "array", "items": label_schema(), "description": "Images projected onto the parts, printed in order"})), ], &[], ) @@ -342,6 +454,14 @@ fn schema(name: &str) -> Value { &["id", "key"], ), "scene.set_pivot" => obj(vec![("id", key("Node")), ("pivot", opt(triple("Local pivot, null clears")))], &["id"]), + "scene.set_part_mesh" => obj( + vec![ + ("id", key("Part")), + ("mesh", key("Existing mesh the part shows from now on (add it first with mesh.add)")), + ("remove_unused", json!({"type": "boolean", "default": true, "description": "Remove the old mesh when no other part uses it"})), + ], + &["id", "mesh"], + ), "scene.set_light" => patch_node(light_schema()), "scene.set_cutaway" => patch_node(cutaway_schema()), "scene.reparent" => obj( @@ -377,12 +497,78 @@ fn schema(name: &str) -> Value { ), "mesh.add" => obj(vec![("key", key("Key; allocated when absent")), ("mesh", mesh_schema())], &["mesh"]), "mesh.remove" => obj(vec![("key", key("Mesh"))], &["key"]), - "material.create" => obj(vec![("key", key("Key; allocated when absent")), ("material", material_schema())], &[]), + "material.create" => obj( + vec![ + ("key", key("Key; allocated when absent")), + ("material", material_schema()), + ("type", str_enum(&type_ids(), "Start from this material type's preset (ignores material)")), + ("name", string("Name; the type's name when absent")), + ], + &[], + ), + "material.set_slot" => obj( + vec![ + ("key", key("Material (alias: material)")), + ("input", str_enum(&input_names(true), "Input the texture drives")), + ("slot", describe(slot_schema(), "Only the slot fields to change; a new slot starts from the defaults")), + ("path", string("Image file to add as a new texture in the same step (instead of slot.texture)")), + ("colour_space", string("Colour-space hint for the new texture")), + ], + &["key", "input"], + ), + "material.clear_slot" => obj( + vec![("key", key("Material (alias: material)")), ("input", str_enum(&input_names(true), "Input"))], + &["key", "input"], + ), + "material.set_graph" => obj( + vec![ + ("key", key("Material (alias: material)")), + ("graph", opt(describe(graph_schema(), "The whole graph; null removes it"))), + ("merge", json!({"type": "boolean", "default": false, "description": "Merge into the previous merging set_graph of this material until history.barrier, so a value drag is one undo step"})), + ], + &["key", "graph"], + ), + "material.label_add" => obj( + vec![ + ("key", key("Material (alias: material)")), + ("label", describe(label_schema(), "Label fields over the defaults (0.1 m square facing +Z, 10 mm deep)")), + ("index", index("Position in the list; last when absent")), + ("path", string("Image file to add as the label's texture in the same step")), + ("colour_space", string("Colour-space hint for the new texture")), + ], + &["key"], + ), + "material.label_set" => obj( + vec![ + ("key", key("Material (alias: material)")), + ("id", key("Label id")), + ("label", describe(label_schema(), "Only the label fields to change")), + ("path", string("Image file to add as the label's new texture in the same step")), + ("colour_space", string("Colour-space hint for the new texture")), + ], + &["key", "id"], + ), + "material.label_remove" => obj(vec![("key", key("Material (alias: material)")), ("id", key("Label id"))], &["key", "id"]), + "material.label_move" => obj( + vec![ + ("key", key("Material (alias: material)")), + ("id", key("Label id")), + ("index", index("New position; later labels print over earlier ones")), + ], + &["key", "id", "index"], + ), "material.set_params" => obj( vec![("key", key("Material")), ("values", describe(block::<SurfaceParams>(), "Only the parameters to change"))], &["key", "values"], ), - "material.set_type" => obj(vec![("key", key("Material")), ("type_id", string("Catalogue type id"))], &["key", "type_id"]), + "material.set_type" => obj( + vec![ + ("key", key("Material (alias: material)")), + ("type_id", string("Material type id (alias: type); see material.types")), + ("keep", json!({"type": "boolean", "default": true, "description": "Keep parameters and graph; false resets them to the type's preset"})), + ], + &["key", "type_id"], + ), "material.assign" => obj( vec![("ids", keys("Nodes; every part beneath is assigned")), ("material", opt(key("Material; null for default")))], &["ids"], diff --git a/native/crates/fsh-scene/src/command.rs b/native/crates/fsh-scene/src/command.rs index ba588eb1..f50e25e9 100644 --- a/native/crates/fsh-scene/src/command.rs +++ b/native/crates/fsh-scene/src/command.rs @@ -1,6 +1,11 @@ +use crate::compile::{compile_material, TextureTable}; use crate::document::Document; use crate::error::{non_negative, Result, SceneError}; -use crate::material::{Material, SurfaceParams, TextureRef}; +use crate::graph::MaterialGraph; +use crate::labels::{check_label_fields, Label, MaterialLabelAdd, MaterialLabelMove, MaterialLabelRef, MaterialLabelSet}; +use crate::material::{Material, SurfaceParams, TextureRef, TextureRole}; +use crate::slots::{MapProjection, MaterialInput, TextureSlot}; +use crate::types::material_type; use crate::mesh::Mesh; use crate::node::{Cutaway, Light, Node, NodeKind, RayVisibility, Trs}; use crate::primitives::Primitive; @@ -276,6 +281,21 @@ pub struct SetPivot { pub pivot: Option<Vec3>, } +/// `scene.set_part_mesh` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SetPartMesh { + /// Part. + #[serde(with = "ser::key")] + pub id: NodeId, + /// Mesh the part shows from now on. + #[serde(with = "ser::key")] + pub mesh: MeshKey, + /// Remove the part's previous mesh when no other part uses it any more. + #[serde(default = "yes")] + pub remove_unused: bool, +} + /// Arguments that patch one node's block (light or cutaway). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -412,7 +432,62 @@ pub struct MaterialCreate { pub key: Option<MaterialKey>, /// Material. #[serde(default)] - pub material: Material, + pub material: Box<Material>, + /// Start from this material type's preset instead of `material` (dropped once resolved). + #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")] + pub type_id: Option<String>, + /// Name for the new material (dropped once resolved). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option<String>, +} + +/// `material.set_slot` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MaterialSetSlot { + /// Material. + #[serde(alias = "material", with = "ser::key")] + pub key: MaterialKey, + /// Input the slot drives. + pub input: MaterialInput, + /// Partial `TextureSlot` merged onto the current slot (stored in history as the full slot). + #[serde(default)] + pub slot: Value, + /// Image file to add as a new texture in the same step. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option<String>, + /// Colour-space hint for the new texture. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub colour_space: Option<String>, + /// Key of the new texture; allocated when `path` is given. + #[serde(default, with = "ser::key_opt", skip_serializing_if = "Option::is_none")] + pub texture_key: Option<TextureKey>, +} + +/// `material.clear_slot` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MaterialClearSlot { + /// Material. + #[serde(alias = "material", with = "ser::key")] + pub key: MaterialKey, + /// Input whose slot goes. + pub input: MaterialInput, +} + +/// `material.set_graph` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MaterialSetGraph { + /// Material. + #[serde(alias = "material", with = "ser::key")] + pub key: MaterialKey, + /// The whole graph, or null to remove it. + #[serde(default)] + pub graph: Option<Box<MaterialGraph>>, + /// Merge into the previous `material.set_graph` of this material until a barrier (value drags). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub merge: bool, } /// `material.set_params` arguments. @@ -431,10 +506,17 @@ pub struct MaterialSetParams { #[serde(deny_unknown_fields)] pub struct MaterialSetType { /// Material. - #[serde(with = "ser::key")] + #[serde(alias = "material", with = "ser::key")] pub key: MaterialKey, /// Catalogue type id. + #[serde(alias = "type")] pub type_id: String, + /// Keep parameters and graph (true) or reset them to the type's preset (false). + #[serde(default = "yes")] + pub keep: bool, + /// The material after a reset, filled when resolved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preset: Option<Box<Material>>, } /// `material.assign` arguments. @@ -592,6 +674,7 @@ commands! { SetPartColour(SetPartColour) = "scene.set_part_colour", Region, "Set or clear the per-part colour that materials may read."; SetMetadata(SetMetadata) = "scene.set_metadata", None, "Set or delete one metadata field on a node."; SetPivot(SetPivot) = "scene.set_pivot", None, "Set or clear a node's gizmo pivot (local space)."; + SetPartMesh(SetPartMesh) = "scene.set_part_mesh", Full, "Make a part show another existing mesh in place, keeping its id, name, material, transform and metadata; its old mesh is removed when nothing else uses it."; SetLight(PatchNode) = "scene.set_light", Region, "Change a light node's settings; give only the fields to change."; SetCutaway(PatchNode) = "scene.set_cutaway", Full, "Change a cutaway node's settings; give only the fields to change."; Reparent(Reparent) = "scene.reparent", Full, "Move nodes under another parent (or to the root), keeping their world placement by default."; @@ -599,9 +682,16 @@ commands! { Import(Import) = "scene.import", Full, "Add imported meshes, materials, textures and nodes as one step."; MeshAdd(MeshAdd) = "mesh.add", None, "Add a mesh to the shared mesh store."; MeshRemove(MeshRef) = "mesh.remove", None, "Remove a mesh no part uses."; - MaterialCreate(MaterialCreate) = "material.create", None, "Create a material."; + MaterialCreate(MaterialCreate) = "material.create", None, "Create a material, from a material type's preset when type is given."; MaterialSetParams(MaterialSetParams) = "material.set_params", Region, "Change a material's surface parameters; give only the fields to change."; - MaterialSetType(MaterialSetType) = "material.set_type", None, "Change a material's catalogue type id."; + MaterialSetType(MaterialSetType) = "material.set_type", Region, "Change a material's type; keep false resets parameters and graph to the type's preset."; + MaterialSetSlot(MaterialSetSlot) = "material.set_slot", Region, "Drive a material input with an image texture (an existing texture or a new path); give only the slot fields to change."; + MaterialClearSlot(MaterialClearSlot) = "material.clear_slot", Region, "Remove the texture slot of a material input; the constant applies again."; + MaterialSetGraph(MaterialSetGraph) = "material.set_graph", Region, "Replace a material's node graph, or remove it with null."; + MaterialLabelAdd(MaterialLabelAdd) = "material.label_add", Region, "Add a label (an image projected onto the parts wearing the material), optionally adding its image file in the same step; answers the new label id."; + MaterialLabelSet(MaterialLabelSet) = "material.label_set", Region, "Change a label; give only the fields to change (path replaces its image with a new texture)."; + MaterialLabelRemove(MaterialLabelRef) = "material.label_remove", Region, "Remove a label from a material."; + MaterialLabelMove(MaterialLabelMove) = "material.label_move", Region, "Move a label within its material's list; later labels print over earlier ones."; MaterialAssign(MaterialAssign) = "material.assign", Region, "Assign a material to every part in the given nodes' subtrees."; MaterialRename(MaterialRename) = "material.rename", None, "Rename a material."; MaterialRemove(MaterialRef) = "material.remove", Region, "Remove a material; parts wearing it fall back to the default material."; @@ -704,6 +794,27 @@ fn default_name(name: &str, fallback: &str) -> String { } } +fn material_level(doc: &Document, key: MaterialKey) -> ChangeLevel { + if doc.parts_using_material(key).is_empty() { + ChangeLevel::None + } else { + ChangeLevel::Region + } +} + +fn role_of(input: MaterialInput) -> TextureRole { + match input { + MaterialInput::BaseColor => TextureRole::BaseColour, + MaterialInput::SpecularRoughness => TextureRole::Roughness, + MaterialInput::BaseMetalness => TextureRole::Metalness, + MaterialInput::Normal => TextureRole::Normal, + MaterialInput::Bump => TextureRole::Bump, + MaterialInput::GeometryOpacity => TextureRole::Opacity, + MaterialInput::EmissionColor => TextureRole::Emission, + _ => TextureRole::Other, + } +} + fn check_part_refs(doc: &Document, kind: &NodeKind) -> Result<()> { if let NodeKind::Part { mesh, material } = kind { if !doc.meshes().contains_key(mesh) { @@ -805,6 +916,9 @@ impl Command { Command::SetLight(a) | Command::SetCutaway(a) => k(a.id.raw()), Command::SetPivot(a) => k(a.id.raw()), Command::MaterialSetParams(a) => k(a.key.raw()), + Command::MaterialSetSlot(a) if a.path.is_none() => k(a.key.raw() << 5 | a.input as u64), + Command::MaterialLabelSet(a) if a.path.is_none() => k(a.key.raw() << 24 | (a.id as u64 & 0xff_ffff)), + Command::MaterialSetGraph(a) if a.merge => k(a.key.raw()), Command::CameraSet(a) => k(a.index as u64), Command::EnvironmentSet(_) | Command::GroundSet(_) | Command::ImageSetStyle(_) | Command::RenderSetSettings(_) => k(0), _ => None, @@ -826,7 +940,48 @@ impl Command { Arc::make_mut(&mut a.mesh).validate()?; a.key = Some(fresh(doc, a.key)?); } - Command::MaterialCreate(a) => a.key = Some(fresh(doc, a.key)?), + Command::MaterialCreate(a) => { + if let Some(id) = a.type_id.take() { + let t = material_type(&id).ok_or_else(|| SceneError::value("type", format!("unknown material type \"{id}\"")))?; + *a.material = t.material(a.name.as_deref()); + } else if let Some(n) = a.name.as_ref().filter(|n| !n.trim().is_empty()) { + a.material.name = n.clone(); + } + a.name = None; + a.key = Some(fresh(doc, a.key)?); + } + Command::MaterialSetType(a) => { + a.preset = None; + if !a.keep { + let t = material_type(&a.type_id) + .ok_or_else(|| SceneError::value("type", format!("unknown material type \"{}\"", a.type_id)))?; + let cur = doc.material(a.key).ok_or(SceneError::UnknownMaterial(a.key))?; + let mut m = t.material(Some(&cur.name)); + m.textures = cur.textures.clone(); + m.slots = cur.slots.clone(); + m.labels = cur.labels.clone(); + a.preset = Some(Box::new(m)); + } + } + Command::MaterialSetSlot(a) => { + let m = doc.material(a.key).ok_or(SceneError::UnknownMaterial(a.key))?; + let mut cur = m.slots.get(&a.input).cloned().unwrap_or_else(|| TextureSlot::for_input(a.input, TextureKey::NONE)); + if a.path.is_some() { + let key = fresh(doc, a.texture_key)?; + a.texture_key = Some(key); + cur.texture = key; + } else { + a.texture_key = None; + } + let texture = cur.texture; + let mut slot: TextureSlot = if a.slot.is_null() { cur } else { patched(&cur, &a.slot)? }; + if a.path.is_some() { + slot.texture = texture; + } + a.slot = full_value(&slot)?; + } + Command::MaterialLabelAdd(a) => resolve_label_add(doc, a)?, + Command::MaterialLabelSet(a) => resolve_label_set(doc, a)?, Command::TextureAdd(a) => a.key = Some(fresh(doc, a.key)?), Command::Duplicate(a) => { let tops = top_level(doc, &a.ids)?; @@ -988,6 +1143,23 @@ impl Command { tx.node_mut(a.id)?.pivot = a.pivot; Ok(Applied::at(ChangeLevel::None)) } + Command::SetPartMesh(a) => { + editable(tx.doc, a.id)?; + let NodeKind::Part { mesh: old, material } = tx.doc.get_node(a.id)?.kind else { + return Err(SceneError::WrongKind { node: a.id, expected: "part" }); + }; + if tx.doc.mesh(a.mesh).is_none() { + return Err(SceneError::UnknownMesh(a.mesh)); + } + if old == a.mesh { + return Ok(Applied::at(ChangeLevel::None)); + } + tx.node_mut(a.id)?.kind = NodeKind::Part { mesh: a.mesh, material }; + if a.remove_unused && tx.doc.mesh(old).is_some() && tx.doc.parts_using_mesh(old).is_empty() { + tx.set_mesh(old, None); + } + Ok(Applied::at(ChangeLevel::Full)) + } Command::SetLight(a) => { editable(tx.doc, a.id)?; let n = tx.doc.get_node(a.id)?; @@ -1041,11 +1213,9 @@ impl Command { return Err(SceneError::KeyNotFresh(key.raw())); } a.material.validate()?; - if let Some(t) = a.material.textures.iter().find(|t| !tx.doc.textures().contains_key(t)) { - return Err(SceneError::UnknownTexture(*t)); - } + a.material.validate_refs(tx.doc.textures())?; tx.doc.observe(key.raw()); - tx.set_material(key, Some(a.material.clone())); + tx.set_material(key, Some((*a.material).clone())); Ok(Applied { level: ChangeLevel::None, created: vec![key.raw()] }) } Command::MaterialSetParams(a) => { @@ -1060,9 +1230,68 @@ impl Command { if a.type_id.trim().is_empty() { return Err(SceneError::value("type_id", "must not be empty")); } - tx.material_mut(a.key)?.type_id = a.type_id.clone(); - Ok(Applied::at(ChangeLevel::None)) + let Some(preset) = &a.preset else { + tx.material_mut(a.key)?.type_id = a.type_id.clone(); + return Ok(Applied::at(ChangeLevel::None)); + }; + preset.validate()?; + preset.validate_refs(tx.doc.textures())?; + *tx.material_mut(a.key)? = (**preset).clone(); + Ok(Applied::at(material_level(tx.doc, a.key))) + } + Command::MaterialSetSlot(a) => { + let slot: TextureSlot = serde_json::from_value(a.slot.clone()).map_err(|e| SceneError::InvalidArguments(e.to_string()))?; + if tx.doc.material(a.key).is_none() { + return Err(SceneError::UnknownMaterial(a.key)); + } + if let Some(path) = &a.path { + let key = a.texture_key.ok_or_else(unresolved)?; + if !key.is_some() || tx.doc.textures().contains_key(&key) { + return Err(SceneError::KeyNotFresh(key.raw())); + } + let uv_set = match slot.projection { + MapProjection::Uv { set } => set, + _ => 0, + }; + let texture = TextureRef { path: path.clone(), role: role_of(a.input), uv_set, colour_space: a.colour_space.clone() }; + texture.validate()?; + tx.doc.observe(key.raw()); + tx.set_texture(key, Some(texture)); + tx.material_mut(a.key)?.textures.push(key); + } + slot.validate(a.input)?; + if !tx.doc.textures().contains_key(&slot.texture) { + return Err(SceneError::UnknownTexture(slot.texture)); + } + tx.material_mut(a.key)?.slots.insert(a.input, slot); + let mut created = Vec::new(); + if a.path.is_some() { + created.extend(a.texture_key.map(|k| k.raw())); + } + Ok(Applied { level: material_level(tx.doc, a.key), created }) } + Command::MaterialClearSlot(a) => { + let m = tx.material_mut(a.key)?; + if m.slots.remove(&a.input).is_none() { + return Err(SceneError::value("input", format!("{} has no texture slot", a.input.name()))); + } + Ok(Applied::at(material_level(tx.doc, a.key))) + } + Command::MaterialSetGraph(a) => { + let mut m = tx.doc.material(a.key).ok_or(SceneError::UnknownMaterial(a.key))?.clone(); + m.graph = a.graph.clone().map(|mut g| { + g.normalize(); + g + }); + m.validate_refs(tx.doc.textures())?; + compile_material(&m, &mut TextureTable::new(tx.doc.textures()))?; + tx.material_mut(a.key)?.graph = m.graph; + Ok(Applied::at(material_level(tx.doc, a.key))) + } + Command::MaterialLabelAdd(a) => apply_label_add(tx, a), + Command::MaterialLabelSet(a) => apply_label_set(tx, a), + Command::MaterialLabelRemove(a) => apply_label_remove(tx, a), + Command::MaterialLabelMove(a) => apply_label_move(tx, a), Command::MaterialAssign(a) => { if let Some(m) = a.material { if tx.doc.material(m).is_none() { @@ -1123,9 +1352,10 @@ impl Command { return Err(SceneError::UnknownTexture(a.key)); } let users: Vec<MaterialKey> = - tx.doc.materials().iter().filter(|(_, m)| m.textures.contains(&a.key)).map(|(k, _)| *k).collect(); + tx.doc.materials().iter().filter(|(_, m)| m.texture_keys().contains(&a.key)).map(|(k, _)| *k).collect(); + let gone = a.key; for m in users { - tx.material_mut(m)?.textures.retain(|t| *t != a.key); + tx.material_mut(m)?.map_textures(|t| (t != gone).then_some(t)); } tx.set_texture(a.key, None); Ok(Applied::at(ChangeLevel::Region)) @@ -1285,6 +1515,120 @@ fn apply_duplicate(tx: &mut Tx, a: &Duplicate) -> Result<Applied> { Ok(Applied { level: ChangeLevel::Full, created }) } +fn no_label(id: u32) -> SceneError { + SceneError::value("id", format!("the material has no label {id}")) +} + +fn label_of(v: &Value) -> Result<Label> { + serde_json::from_value(v.clone()).map_err(|e| SceneError::InvalidArguments(format!("label: {e}"))) +} + +fn resolve_label_texture(doc: &mut Document, path: &Option<String>, key: &mut Option<TextureKey>, label: &mut Label) -> Result<()> { + *key = match path { + Some(_) => Some(fresh(doc, *key)?), + None => None, + }; + if let Some(k) = *key { + label.texture = Some(k); + } + Ok(()) +} + +fn resolve_label_add(doc: &mut Document, a: &mut MaterialLabelAdd) -> Result<()> { + let m = doc.material(a.key).ok_or(SceneError::UnknownMaterial(a.key))?; + let next = m.labels.iter().map(|l| l.id).max().unwrap_or(0) + 1; + check_label_fields(&a.label)?; + let mut label: Label = if a.label.is_null() { Label::default() } else { patched(&Label::default(), &a.label)? }; + if label.id == 0 { + label.id = next; + } + resolve_label_texture(doc, &a.path, &mut a.texture_key, &mut label)?; + a.label = full_value(&label)?; + Ok(()) +} + +fn resolve_label_set(doc: &mut Document, a: &mut MaterialLabelSet) -> Result<()> { + let m = doc.material(a.key).ok_or(SceneError::UnknownMaterial(a.key))?; + let cur = m.labels.iter().find(|l| l.id == a.id).cloned().ok_or_else(|| no_label(a.id))?; + check_label_fields(&a.label)?; + let mut label: Label = if a.label.is_null() { cur } else { patched(&cur, &a.label)? }; + label.id = a.id; + resolve_label_texture(doc, &a.path, &mut a.texture_key, &mut label)?; + a.label = full_value(&label)?; + Ok(()) +} + +fn add_label_texture(tx: &mut Tx, material: MaterialKey, path: &Option<String>, key: Option<TextureKey>, colour_space: &Option<String>) -> Result<Vec<u64>> { + let Some(path) = path else { return Ok(Vec::new()) }; + let key = key.ok_or_else(unresolved)?; + if !key.is_some() || tx.doc.textures().contains_key(&key) { + return Err(SceneError::KeyNotFresh(key.raw())); + } + let texture = TextureRef { path: path.clone(), role: TextureRole::BaseColour, uv_set: 0, colour_space: colour_space.clone() }; + texture.validate()?; + tx.doc.observe(key.raw()); + tx.set_texture(key, Some(texture)); + tx.material_mut(material)?.textures.push(key); + Ok(vec![key.raw()]) +} + +fn check_label(doc: &Document, label: &Label) -> Result<()> { + label.validate()?; + match label.texture { + Some(t) if !doc.textures().contains_key(&t) => Err(SceneError::UnknownTexture(t)), + _ => Ok(()), + } +} + +fn label_index(doc: &Document, key: MaterialKey, id: u32) -> Result<usize> { + let m = doc.material(key).ok_or(SceneError::UnknownMaterial(key))?; + m.labels.iter().position(|l| l.id == id).ok_or_else(|| no_label(id)) +} + +fn apply_label_add(tx: &mut Tx, a: &MaterialLabelAdd) -> Result<Applied> { + let label = label_of(&a.label)?; + let m = tx.doc.material(a.key).ok_or(SceneError::UnknownMaterial(a.key))?; + if label.id == 0 || m.labels.iter().any(|l| l.id == label.id) { + return Err(SceneError::value("label.id", format!("{} is zero or already used in this material", label.id))); + } + let made = add_label_texture(tx, a.key, &a.path, a.texture_key, &a.colour_space)?; + check_label(tx.doc, &label)?; + let id = label.id; + let labels = &mut tx.material_mut(a.key)?.labels; + let at = a.index.unwrap_or(labels.len()).min(labels.len()); + labels.insert(at, label); + let mut created = vec![id as u64]; + created.extend(made); + Ok(Applied { level: material_level(tx.doc, a.key), created }) +} + +fn apply_label_set(tx: &mut Tx, a: &MaterialLabelSet) -> Result<Applied> { + let label = label_of(&a.label)?; + if label.id != a.id { + return Err(SceneError::value("label.id", "cannot change a label's id")); + } + let i = label_index(tx.doc, a.key, a.id)?; + let created = add_label_texture(tx, a.key, &a.path, a.texture_key, &a.colour_space)?; + check_label(tx.doc, &label)?; + tx.material_mut(a.key)?.labels[i] = label; + Ok(Applied { level: material_level(tx.doc, a.key), created }) +} + +fn apply_label_remove(tx: &mut Tx, a: &MaterialLabelRef) -> Result<Applied> { + let i = label_index(tx.doc, a.key, a.id)?; + tx.material_mut(a.key)?.labels.remove(i); + Ok(Applied::at(material_level(tx.doc, a.key))) +} + +fn apply_label_move(tx: &mut Tx, a: &MaterialLabelMove) -> Result<Applied> { + let i = label_index(tx.doc, a.key, a.id)?; + let labels = &mut tx.material_mut(a.key)?.labels; + let label = labels.remove(i); + let at = a.index.min(labels.len()); + labels.insert(at, label); + Ok(Applied::at(material_level(tx.doc, a.key))) +} + fn resolve_import(doc: &mut Document, p: &mut ImportPayload) -> Result<()> { let mut meshes = BTreeMap::new(); let mut materials = BTreeMap::new(); @@ -1312,9 +1656,7 @@ fn resolve_import(doc: &mut Document, p: &mut ImportPayload) -> Result<()> { return Err(SceneError::InvalidArguments(format!("material key {} appears twice in the payload", m.key))); } m.key = k; - for t in &mut m.material.textures { - *t = textures.get(t).copied().unwrap_or(*t); - } + m.material.map_textures(|t| Some(textures.get(&t).copied().unwrap_or(t))); } for n in &mut p.nodes { let k: NodeId = doc.alloc_key(); @@ -1374,9 +1716,7 @@ fn apply_import(tx: &mut Tx, a: &Import) -> Result<Applied> { return Err(SceneError::KeyNotFresh(m.key.raw())); } m.material.validate()?; - if let Some(t) = m.material.textures.iter().find(|t| !tx.doc.textures().contains_key(t)) { - return Err(SceneError::UnknownTexture(*t)); - } + m.material.validate_refs(tx.doc.textures())?; tx.doc.observe(m.key.raw()); tx.set_material(m.key, Some(m.material.clone())); } diff --git a/native/crates/fsh-scene/src/compile.rs b/native/crates/fsh-scene/src/compile.rs new file mode 100644 index 00000000..c48c862a --- /dev/null +++ b/native/crates/fsh-scene/src/compile.rs @@ -0,0 +1,713 @@ +use crate::error::{Result, SceneError}; +use crate::graph::{GraphNode, GraphOp, MaterialGraph, MathOp, RampInterpolation, SocketType}; +use crate::labels::Label; +use crate::material::{Material, SurfaceParams, TextureRef}; +use crate::slots::{Channel, CoordSpace, MapProjection, MaterialInput, TextureSlot, UvTransform}; +use crate::snapshot::{RenderTexture, SCENE_UNITS_PER_NIT}; +use fsh_core::TextureKey; +use fsh_materials::program::{input, LABEL_ONE_SIDED, NEED_BUMP, NEED_NORMAL, NEED_PROCEDURAL, NEED_TANGENT, NEED_TEXTURES, NEED_UV0}; +use fsh_materials::{fold, ColourSpace, Field, Filter, Instr, Op, Output, Program, SurfaceInputs, Wrap, REGISTERS}; +use std::collections::BTreeMap; + +/// Snapshot textures collected while compiling, deduplicated by (path, colour space). +#[derive(Clone, Debug)] +pub struct TextureTable<'d> { + doc: &'d BTreeMap<TextureKey, TextureRef>, + /// Textures in index order. + pub list: Vec<RenderTexture>, +} + +impl<'d> TextureTable<'d> { + /// Empty table over a document's texture references. + pub fn new(doc: &'d BTreeMap<TextureKey, TextureRef>) -> Self { + Self { doc, list: Vec::new() } + } + + fn hint(&self, key: TextureKey) -> Option<&'d str> { + self.doc.get(&key).and_then(|t| t.colour_space.as_deref()) + } + + fn index(&mut self, key: TextureKey, colour_space: ColourSpace, filter: Filter) -> Option<u32> { + let t = self.doc.get(&key)?; + let mips = filter == Filter::Trilinear; + if let Some(i) = self.list.iter().position(|r| r.path == t.path && r.colour_space == colour_space) { + self.list[i].mipmaps |= mips; + return Some(i as u32); + } + self.list.push(RenderTexture { key, path: t.path.clone(), colour_space, mipmaps: mips }); + Some(self.list.len() as u32 - 1) + } +} + +/// Constant surface inputs of a parameter block (emission in scene units), sanitised; the same values the CPU +/// renderer derives for an untextured material. +pub fn base_inputs(p: &SurfaceParams) -> SurfaceInputs { + SurfaceInputs { + base_weight: p.base_weight, + base_color: p.base_color, + base_metalness: p.base_metalness, + base_diffuse_roughness: p.base_diffuse_roughness, + specular_weight: p.specular_weight, + specular_color: p.specular_color, + specular_roughness: p.specular_roughness, + specular_ior: p.specular_ior, + specular_anisotropy: p.specular_roughness_anisotropy, + transmission_weight: p.transmission_weight, + transmission_color: p.transmission_color, + coat_weight: p.coat_weight, + coat_color: p.coat_color, + coat_roughness: p.coat_roughness, + coat_ior: p.coat_ior, + fuzz_weight: p.fuzz_weight, + fuzz_color: p.fuzz_color, + fuzz_roughness: p.fuzz_roughness, + emission: p.emission_color * (p.emission_luminance * SCENE_UNITS_PER_NIT), + opacity: p.geometry_opacity, + thin_walled: p.geometry_thin_walled, + } + .sanitized() +} + +type V4 = [f32; 4]; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Val { + K(V4), + R(u32), +} + +#[derive(Clone, Debug)] +struct VInstr { + op: Op, + dst: u32, + flags: u8, + a: u32, + b: u32, + c: u32, + args: Vec<u32>, +} + +fn reg_operands(op: Op) -> [bool; 3] { + match op { + Op::Nop | Op::Const | Op::Input | Op::Proc => [false; 3], + Op::Swizzle | Op::Invert | Op::Luminance | Op::Project | Op::Ramp | Op::Xform2 | Op::Tex | Op::TexBox => { + [true, false, false] + } + Op::Combine | Op::Lerp | Op::Clamp => [true; 3], + Op::Label => [true, false, true], + Op::Add | Op::Sub | Op::Mul | Op::Div | Op::Min | Op::Max | Op::Pow | Op::NormalMap | Op::Bump => { + [true, true, false] + } + } +} + +const SPLAT_X: u8 = 0; +const SPLAT_Y: u8 = 0b01_01_01_01; +const SPLAT_Z: u8 = 0b10_10_10_10; +const SPLAT_W: u8 = 0b11_11_11_11; + +struct Emitter<'t, 'd> { + code: Vec<VInstr>, + consts: Vec<f32>, + next: u32, + kregs: BTreeMap<[u32; 4], u32>, + needs: u32, + table: &'t mut TextureTable<'d>, + memo: BTreeMap<(u32, String, u8), (Val, SocketType)>, +} + +fn splat(v: f32) -> V4 { + [v; 4] +} + +impl<'t, 'd> Emitter<'t, 'd> { + fn pool(&mut self, vals: &[f32]) -> u32 { + let at = self.consts.len() as u32; + self.consts.extend_from_slice(vals); + at + } + + fn push(&mut self, op: Op, flags: u8, a: u32, b: u32, c: u32, args: Vec<u32>) -> Val { + let dst = self.next; + self.next += 1; + self.code.push(VInstr { op, dst, flags, a, b, c, args }); + Val::R(dst) + } + + fn reg(&mut self, v: Val) -> u32 { + match v { + Val::R(r) => r, + Val::K(k) => { + let bits = k.map(f32::to_bits); + if let Some(r) = self.kregs.get(&bits) { + return *r; + } + let at = self.pool(&k); + let Val::R(r) = self.push(Op::Const, 0, at, 0, 0, Vec::new()) else { unreachable!() }; + self.kregs.insert(bits, r); + r + } + } + } + + fn pure(&mut self, op: Op, flags: u8, a: Val, b: Val, c: Val, imm_b: Option<u32>) -> Val { + if let (Val::K(x), Val::K(y), Val::K(z)) = (a, if imm_b.is_some() { Val::K([0.0; 4]) } else { b }, c) { + let i = Instr::new(op, 0, flags, 0, imm_b.unwrap_or(0), 0); + if let Some(v) = fold(&i, x, y, z, &self.consts) { + return Val::K(v); + } + } + let [ra, rb, rc] = reg_operands(op); + let a = if ra { self.reg(a) } else { 0 }; + let b = match imm_b { + Some(k) => k, + None if rb => self.reg(b), + None => 0, + }; + let c = if rc { self.reg(c) } else { 0 }; + self.push(op, flags, a, b, c, Vec::new()) + } + + fn bin(&mut self, op: Op, a: Val, b: Val) -> Val { + self.pure(op, 0, a, b, Val::K([0.0; 4]), None) + } + + fn un(&mut self, op: Op, a: Val) -> Val { + self.pure(op, 0, a, Val::K([0.0; 4]), Val::K([0.0; 4]), None) + } + + fn tri(&mut self, op: Op, a: Val, b: Val, c: Val) -> Val { + self.pure(op, 0, a, b, c, None) + } + + fn swizzle(&mut self, a: Val, sel: u8) -> Val { + self.pure(Op::Swizzle, sel, a, Val::K([0.0; 4]), Val::K([0.0; 4]), None) + } + + fn input(&mut self, which: u8, offset: u8, set: u32) -> Val { + match which { + input::UV => self.needs |= NEED_UV0 << set.min(3), + input::TANGENT => self.needs |= NEED_TANGENT, + _ => {} + } + let offset = if matches!(which, input::POSITION | input::POSITION_OBJECT | input::UV) { offset } else { 0 }; + self.push(Op::Input, which | offset << 4, set, 0, 0, Vec::new()) + } + + fn convert(&mut self, v: Val, from: SocketType, to: SocketType) -> Val { + match (from, to) { + (SocketType::Colour | SocketType::Vector, SocketType::Float) => self.un(Op::Luminance, v), + _ => v, + } + } + + fn xform(&mut self, coord: Val, t: &UvTransform) -> Val { + if t.is_identity() { + return coord; + } + let k = self.pool(&t.consts()); + self.pure(Op::Xform2, 0, coord, Val::K([0.0; 4]), Val::K([0.0; 4]), Some(k)) + } + + fn position(&mut self, space: CoordSpace, offset: u8) -> Val { + let which = if space == CoordSpace::World { input::POSITION } else { input::POSITION_OBJECT }; + self.input(which, offset, 0) + } + + fn coordinate(&mut self, projection: &MapProjection, t: &UvTransform, offset: u8) -> Val { + let raw = match *projection { + MapProjection::Uv { set } => self.input(input::UV, offset, set), + MapProjection::Box { .. } => return self.position(t.space, offset), + MapProjection::Planar => { + let p = self.position(t.space, offset); + self.pure(Op::Project, 0, p, Val::K([0.0; 4]), Val::K([0.0; 4]), None) + } + MapProjection::Cylindrical => { + let p = self.position(t.space, offset); + self.pure(Op::Project, 1, p, Val::K([0.0; 4]), Val::K([0.0; 4]), None) + } + MapProjection::Spherical => { + let p = self.position(t.space, offset); + self.pure(Op::Project, 2, p, Val::K([0.0; 4]), Val::K([0.0; 4]), None) + } + }; + self.xform(raw, t) + } + + #[allow(clippy::too_many_arguments)] + fn sample( + &mut self, + texture: Option<u32>, + coord: Option<Val>, + projection: &MapProjection, + t: &UvTransform, + wrap: Wrap, + filter: Filter, + fallback: V4, + offset: u8, + ) -> Val { + let Some(index) = texture else { return Val::K(fallback) }; + self.needs |= NEED_TEXTURES; + let flags = wrap.code() | filter.code() << 2; + if let (MapProjection::Box { blend }, None) = (projection, coord) { + let p = self.position(t.space, offset); + let p = self.reg(p); + let x = t.consts(); + let k = self.pool(&[fallback[0], fallback[1], fallback[2], fallback[3], x[0], x[1], x[2], x[3], x[4], x[5], *blend]); + let world = if t.space == CoordSpace::World { 16 } else { 0 }; + return self.push(Op::TexBox, flags | world, p, index, k, Vec::new()); + } + let coord = match coord { + Some(c) => self.xform(c, t), + None => self.coordinate(projection, t, offset), + }; + let coord = self.reg(coord); + let k = self.pool(&fallback); + self.push(Op::Tex, flags, coord, index, k, Vec::new()) + } + + fn node_out(&mut self, g: &MaterialGraph, id: u32, socket: &str, offset: u8, depth: u32) -> Result<(Val, SocketType)> { + let key = (id, socket.to_string(), offset); + if let Some(v) = self.memo.get(&key) { + return Ok(*v); + } + if depth > 512 { + return Err(SceneError::value("graph", "is nested too deeply")); + } + let node = g.nodes.get(&id).ok_or_else(|| SceneError::value("graph", format!("names missing node {id}")))?; + let ty = node.op.output_type(socket).ok_or_else(|| SceneError::value("graph", format!("node {id} has no output {socket}")))?; + let v = self.eval_node(g, id, node, socket, offset, depth)?; + self.memo.insert(key, (v, ty)); + Ok((v, ty)) + } + + fn node_in(&mut self, g: &MaterialGraph, id: u32, node: &GraphNode, socket: &str, offset: u8, depth: u32) -> Result<Val> { + let want = node.op.input(socket).map(|s| s.ty).unwrap_or(SocketType::Float); + if let Some(from) = g.link_into(id, socket) { + let (v, ty) = self.node_out(g, from.0, &from.1, offset, depth + 1)?; + return Ok(self.convert(v, ty, want)); + } + Ok(match want { + SocketType::Normal => self.input(input::NORMAL, 0, 0), + SocketType::Float => Val::K(splat(node.input_value(socket)[0])), + _ => Val::K(node.input_value(socket)), + }) + } + + fn eval_node(&mut self, g: &MaterialGraph, id: u32, node: &GraphNode, socket: &str, offset: u8, depth: u32) -> Result<Val> { + let inp = |e: &mut Self, s: &str| e.node_in(g, id, node, s, offset, depth); + Ok(match &node.op { + GraphOp::Constant { value } => Val::K(value.vec4()), + GraphOp::Texture { texture, projection, transform, wrap, filter, colour_space, fallback } => { + let cs = colour_space.or_else(|| texture.and_then(|t| self.table.hint(t)).and_then(ColourSpace::parse)); + let index = texture.and_then(|t| self.table.index(t, cs.unwrap_or(ColourSpace::Srgb), *filter)); + let coord = match g.link_into(id, "vector") { + Some(from) => Some(self.node_out(g, from.0, &from.1, offset, depth + 1)?.0), + None => None, + }; + let v = self.sample(index, coord, projection, transform, *wrap, *filter, *fallback, offset); + if socket == "alpha" { + self.swizzle(v, SPLAT_W) + } else { + v + } + } + GraphOp::Mapping { projection, transform } => self.coordinate(projection, transform, offset), + GraphOp::Mix {} => { + let (a, b, f) = (inp(self, "a")?, inp(self, "b")?, inp(self, "factor")?); + self.tri(Op::Lerp, a, b, f) + } + GraphOp::Math { op } => { + let (a, b, c) = (inp(self, "a")?, inp(self, "b")?, inp(self, "c")?); + match op { + MathOp::Add => self.bin(Op::Add, a, b), + MathOp::Subtract => self.bin(Op::Sub, a, b), + MathOp::Multiply => self.bin(Op::Mul, a, b), + MathOp::Divide => self.bin(Op::Div, a, b), + MathOp::Minimum => self.bin(Op::Min, a, b), + MathOp::Maximum => self.bin(Op::Max, a, b), + MathOp::Power => self.bin(Op::Pow, a, b), + MathOp::Lerp => self.tri(Op::Lerp, a, b, c), + MathOp::Clamp => self.tri(Op::Clamp, a, b, c), + MathOp::Invert => self.un(Op::Invert, a), + } + } + GraphOp::ColourRamp { stops, interpolation } => { + let f = inp(self, "factor")?; + let mut k = vec![stops.len() as f32]; + for s in stops { + k.extend_from_slice(&[s.position, s.colour[0], s.colour[1], s.colour[2], s.colour[3]]); + } + let at = self.pool(&k); + let mode = match interpolation { + RampInterpolation::Linear => 0, + RampInterpolation::Constant => 1, + RampInterpolation::Smooth => 2, + }; + let v = self.pure(Op::Ramp, mode, f, Val::K([0.0; 4]), Val::K([0.0; 4]), Some(at)); + if socket == "alpha" { + self.swizzle(v, SPLAT_W) + } else { + v + } + } + GraphOp::NormalMap { flip_y } => { + let (c, s) = (inp(self, "colour")?, inp(self, "strength")?); + self.normal_map(c, s, *flip_y) + } + GraphOp::Bump {} => { + let n = inp(self, "normal")?; + let s = inp(self, "strength")?; + let mut h = [Val::K([0.0; 4]); 3]; + for (o, slot) in h.iter_mut().enumerate() { + *slot = self.node_in(g, id, node, "height", o as u8, depth)?; + } + self.bump(n, h, s) + } + op => { + let kind = op.kind(); + let Some(proc_kind) = kind.procedural else { return Ok(Val::K([0.0; 4])) }; + self.needs |= NEED_PROCEDURAL; + let mut args = Vec::with_capacity(kind.inputs.len() + 1); + for spec in kind.inputs { + let v = if spec.name == "vector" && g.link_into(id, "vector").is_none() { + self.position(CoordSpace::Object, offset) + } else { + inp(self, spec.name)? + }; + args.push(self.reg(v)); + } + let settings = self.reg(Val::K(op.procedural_settings())); + args.push(settings); + let output = kind.outputs.iter().position(|o| o.name == socket).unwrap_or(0); + let v = self.push(Op::Proc, proc_kind as u8, 0, output as u32, 0, args); + if kind.outputs.get(output).is_some_and(|o| o.ty == SocketType::Normal) { + let half = Val::K(splat(0.5)); + let scaled = self.bin(Op::Mul, v, half); + let colour = self.bin(Op::Add, scaled, half); + self.normal_map(colour, Val::K(splat(1.0)), false) + } else { + v + } + } + }) + } + + fn normal_map(&mut self, colour: Val, strength: Val, flip_y: bool) -> Val { + self.needs |= NEED_TANGENT; + let (c, s) = (self.reg(colour), self.reg(strength)); + self.push(Op::NormalMap, flip_y as u8, c, s, 0, Vec::new()) + } + + fn bump(&mut self, normal: Val, heights: [Val; 3], strength: Val) -> Val { + if heights.iter().all(|h| matches!(h, Val::K(_))) { + return normal; + } + self.needs |= NEED_BUMP | NEED_TANGENT; + let scaled = heights.map(|h| self.bin(Op::Mul, h, strength)); + let packed = self.tri(Op::Combine, scaled[0], scaled[1], scaled[2]); + let (n, p) = (self.reg(normal), self.reg(packed)); + self.push(Op::Bump, 0, n, p, 0, Vec::new()) + } + + fn slot_texel(&mut self, input: MaterialInput, slot: &TextureSlot, constant: V4, offset: u8) -> Val { + let cs = slot.colour_space_for(input, self.table.hint(slot.texture)); + let index = self.table.index(slot.texture, cs, slot.filter); + let fallback = slot.fallback.unwrap_or_else(|| fallback_texel(input, slot, constant)); + self.sample(index, None, &slot.projection, &slot.transform, slot.wrap, slot.filter, fallback, offset) + } + + fn scalar(&mut self, v: Val, channel: Channel) -> Val { + match channel { + Channel::R => self.swizzle(v, SPLAT_X), + Channel::G => self.swizzle(v, SPLAT_Y), + Channel::B => self.swizzle(v, SPLAT_Z), + Channel::A => self.swizzle(v, SPLAT_W), + Channel::Rgb | Channel::Luminance => self.un(Op::Luminance, v), + } + } + + fn slot_value(&mut self, input: MaterialInput, slot: &TextureSlot, constant: V4) -> Val { + let t = self.slot_texel(input, slot, constant, 0); + if input.is_colour() { + let v = match slot.channel { + Channel::Rgb => t, + ch => self.scalar(t, ch), + }; + let v = if slot.invert { self.un(Op::Invert, v) } else { v }; + return if slot.multiply { self.bin(Op::Mul, v, Val::K(constant)) } else { v }; + } + let v = self.scalar(t, slot.channel); + let v = self.remap(v, slot); + if slot.multiply { + self.bin(Op::Mul, v, Val::K(splat(constant[0]))) + } else { + v + } + } + + fn remap(&mut self, v: Val, slot: &TextureSlot) -> Val { + let v = if slot.invert { self.un(Op::Invert, v) } else { v }; + if slot.range == [0.0, 1.0] { + return v; + } + self.tri(Op::Lerp, Val::K(splat(slot.range[0])), Val::K(splat(slot.range[1])), v) + } + + fn slot_height(&mut self, slot: &TextureSlot, input: MaterialInput, offset: u8) -> Val { + let t = self.slot_texel(input, slot, [0.0, 0.0, 0.0, 1.0], offset); + let v = self.scalar(t, slot.channel); + self.remap(v, slot) + } +} + +fn fallback_texel(input: MaterialInput, slot: &TextureSlot, constant: V4) -> V4 { + match input { + MaterialInput::Normal => return [0.5, 0.5, 1.0, 1.0], + MaterialInput::Bump | MaterialInput::Displacement => return [0.0, 0.0, 0.0, 0.0], + _ => {} + } + if input.is_colour() { + return if slot.multiply { [1.0; 4] } else { constant }; + } + let target = if slot.multiply { 1.0 } else { constant[0] }; + let span = slot.range[1] - slot.range[0]; + let t = if span != 0.0 { (target - slot.range[0]) / span } else { 0.0 }; + let t = if slot.invert { 1.0 - t } else { t }; + splat(t) +} + +fn set_base(m: &mut SurfaceInputs, f: Field, v: V4) { + let c = fsh_core::Rgb::new(v[0], v[1], v[2]); + match f { + Field::BaseWeight => m.base_weight = v[0], + Field::BaseColor => m.base_color = c, + Field::BaseMetalness => m.base_metalness = v[0], + Field::BaseDiffuseRoughness => m.base_diffuse_roughness = v[0], + Field::SpecularWeight => m.specular_weight = v[0], + Field::SpecularColor => m.specular_color = c, + Field::SpecularRoughness => m.specular_roughness = v[0], + Field::SpecularIor => m.specular_ior = v[0], + Field::SpecularAnisotropy => m.specular_anisotropy = v[0], + Field::TransmissionWeight => m.transmission_weight = v[0], + Field::TransmissionColor => m.transmission_color = c, + Field::CoatWeight => m.coat_weight = v[0], + Field::CoatColor => m.coat_color = c, + Field::CoatRoughness => m.coat_roughness = v[0], + Field::CoatIor => m.coat_ior = v[0], + Field::FuzzWeight => m.fuzz_weight = v[0], + Field::FuzzColor => m.fuzz_color = c, + Field::FuzzRoughness => m.fuzz_roughness = v[0], + Field::Emission => m.emission = c, + Field::Opacity => m.opacity = v[0], + Field::Normal | Field::Displacement => {} + } +} + +fn allocate(code: Vec<VInstr>, outputs: &[(Field, u32)], consts: &mut Vec<f32>) -> Result<(Vec<Instr>, Vec<Output>, u32)> { + let mut live = vec![false; code.len()]; + let mut needed: std::collections::BTreeSet<u32> = outputs.iter().map(|o| o.1).collect(); + for (i, ins) in code.iter().enumerate().rev() { + if !needed.contains(&ins.dst) { + continue; + } + live[i] = true; + let [ra, rb, rc] = reg_operands(ins.op); + for (on, r) in [(ra, ins.a), (rb, ins.b), (rc, ins.c)] { + if on { + needed.insert(r); + } + } + needed.extend(ins.args.iter().copied()); + } + let code: Vec<VInstr> = code.into_iter().zip(live).filter(|(_, l)| *l).map(|(c, _)| c).collect(); + let mut last: BTreeMap<u32, usize> = BTreeMap::new(); + for (i, ins) in code.iter().enumerate() { + let [ra, rb, rc] = reg_operands(ins.op); + for (on, r) in [(ra, ins.a), (rb, ins.b), (rc, ins.c)] { + if on { + last.insert(r, i); + } + } + for r in &ins.args { + last.insert(*r, i); + } + } + for (_, r) in outputs { + last.insert(*r, usize::MAX); + } + let mut phys: BTreeMap<u32, u8> = BTreeMap::new(); + let mut free: Vec<u8> = (0..REGISTERS as u8).rev().collect(); + let mut used = 0u32; + let mut out = Vec::with_capacity(code.len()); + for (i, ins) in code.iter().enumerate() { + let map = |phys: &BTreeMap<u32, u8>, r: u32| phys.get(&r).copied().unwrap_or(0) as u32; + let [ra, rb, rc] = reg_operands(ins.op); + let a = if ra { map(&phys, ins.a) } else { ins.a }; + let b = if rb { map(&phys, ins.b) } else { ins.b }; + let c = if rc { map(&phys, ins.c) } else { ins.c }; + let a = if ins.op == Op::Proc { + let mut list = vec![ins.args.len() as f32]; + list.extend(ins.args.iter().map(|r| map(&phys, *r) as f32)); + let at = consts.len() as u32; + consts.extend(list); + at + } else { + a + }; + let mut operands: Vec<u32> = Vec::new(); + for (on, r) in [(ra, ins.a), (rb, ins.b), (rc, ins.c)] { + if on { + operands.push(r); + } + } + operands.extend(ins.args.iter().copied()); + operands.sort_unstable(); + operands.dedup(); + for r in operands { + if last.get(&r) == Some(&i) { + if let Some(p) = phys.remove(&r) { + free.push(p); + } + } + } + let dst = free.pop().ok_or_else(|| { + SceneError::value("graph", format!("needs more than {REGISTERS} registers; simplify the graph")) + })?; + used = used.max(dst as u32 + 1); + if last.contains_key(&ins.dst) { + phys.insert(ins.dst, dst); + } else { + free.push(dst); + } + out.push(Instr::new(ins.op, dst, ins.flags, a, b, c)); + } + let outs = outputs.iter().map(|(f, r)| Output { field: *f, reg: phys.get(r).copied().unwrap_or(0) }).collect(); + Ok((out, outs, used)) +} + +fn label_layers(e: &mut Emitter, m: &Material, results: &mut Vec<(MaterialInput, Val)>) { + let mut hit: Option<(u32, u32)> = None; + for l in m.labels.iter().filter(|l| l.active()) { + let Some(key) = l.texture else { continue }; + let cs = l.colour_space.or_else(|| e.table.hint(key).and_then(ColourSpace::parse)).unwrap_or(ColourSpace::Srgb); + let Some(index) = e.table.index(key, cs, Filter::Trilinear) else { continue }; + e.needs |= NEED_TEXTURES; + let (p, n) = match hit { + Some(h) => h, + None => { + let (p, n) = (e.input(input::POSITION_OBJECT, 0, 0), e.input(input::NORMAL_OBJECT, 0, 0)); + let h = (e.reg(p), e.reg(n)); + hit = Some(h); + h + } + }; + let k = e.pool(&l.consts()); + let flags = if l.two_sided { 0 } else { LABEL_ONE_SIDED }; + let uvm = e.push(Op::Label, flags, p, k, n, Vec::new()); + let at = e.reg(uvm); + let fallback = e.pool(&[0.0; 4]); + let texel = e.push(Op::Tex, Wrap::Clamp.code() | Filter::Trilinear.code() << 2, at, index, fallback, Vec::new()); + let alpha = e.swizzle(texel, SPLAT_W); + let mask = e.swizzle(uvm, SPLAT_W); + let mut a = e.bin(Op::Mul, alpha, mask); + if l.opacity < 1.0 { + a = e.bin(Op::Mul, a, Val::K(splat(l.opacity))); + } + let mut over = |input: MaterialInput, value: Val| { + let i = results.iter().position(|r| r.0 == input).unwrap_or_else(|| { + results.push((input, Val::K(input.constant(&m.params)))); + results.len() - 1 + }); + results[i].1 = e.tri(Op::Lerp, results[i].1, value, a); + }; + over(MaterialInput::BaseColor, texel); + if let Some(r) = l.roughness { + over(MaterialInput::SpecularRoughness, Val::K(splat(r))); + } + if let Some(v) = l.metalness { + over(MaterialInput::BaseMetalness, Val::K(splat(v))); + } + } +} + +/// Compiles a material (constants, slots, graph, then labels in order) to a program; textures are added to `table`. +pub fn compile_material(m: &Material, table: &mut TextureTable) -> Result<Program> { + let mut base = base_inputs(&m.params); + if m.slots.is_empty() && m.graph.is_none() && !m.labels.iter().any(Label::active) { + return Ok(Program::constant(base)); + } + let mut e = Emitter { code: Vec::new(), consts: Vec::new(), next: 0, kregs: BTreeMap::new(), needs: 0, table, memo: BTreeMap::new() }; + let g = m.graph.as_deref(); + let mut results: Vec<(MaterialInput, Val)> = Vec::new(); + for input in MaterialInput::ALL { + if matches!(input, MaterialInput::Normal | MaterialInput::Bump) { + continue; + } + let constant = input.constant(&m.params); + let from_graph = g.and_then(|g| g.outputs.get(&input).map(|r| (g, r))); + let v = if let Some((g, r)) = from_graph { + let (v, ty) = e.node_out(g, r.0, &r.1, 0, 0)?; + let want = if input.is_colour() { SocketType::Colour } else { SocketType::Float }; + e.convert(v, ty, want) + } else if let Some(slot) = m.slots.get(&input) { + if input == MaterialInput::Displacement { + let h = e.slot_height(slot, input, 0); + e.bin(Op::Mul, h, Val::K(splat(slot.strength))) + } else { + e.slot_value(input, slot, constant) + } + } else { + continue; + }; + results.push((input, v)); + } + label_layers(&mut e, m, &mut results); + let normal =match g.and_then(|g| g.outputs.get(&MaterialInput::Normal).map(|r| (g, r))) { + Some((g, r)) => Some(e.node_out(g, r.0, &r.1, 0, 0)?.0), + None => { + let mapped = m.slots.get(&MaterialInput::Normal).map(|slot| { + let t = e.slot_texel(MaterialInput::Normal, slot, [0.5, 0.5, 1.0, 1.0], 0); + e.normal_map(t, Val::K(splat(slot.strength)), slot.flip_y) + }); + match m.slots.get(&MaterialInput::Bump) { + Some(slot) => { + let n = mapped.unwrap_or_else(|| e.input(input::NORMAL, 0, 0)); + let h = [0u8, 1, 2].map(|o| e.slot_height(slot, MaterialInput::Bump, o)); + Some(e.bump(n, h, Val::K(splat(slot.strength)))) + } + None => mapped, + } + } + }; + let mut outputs: Vec<(Field, u32)> = Vec::new(); + for (input, v) in results { + let v = if input == MaterialInput::EmissionColor { + e.bin(Op::Mul, v, Val::K(splat(m.params.emission_luminance * SCENE_UNITS_PER_NIT))) + } else { + v + }; + match v { + Val::K(k) => set_base(&mut base, input.field(), k), + Val::R(r) => outputs.push((input.field(), r)), + } + } + if let Some(Val::R(r)) = normal { + e.needs |= NEED_NORMAL; + outputs.push((Field::Normal, r)); + } + let base = base.sanitized(); + let needs = e.needs; + let mut consts = std::mem::take(&mut e.consts); + let code = std::mem::take(&mut e.code); + if outputs.is_empty() { + return Ok(Program::constant(base)); + } + let (code, outs, registers) = allocate(code, &outputs, &mut consts)?; + let mut textures: Vec<u32> = code.iter().filter(|i| matches!(i.op, Op::Tex | Op::TexBox)).map(|i| i.b).collect(); + textures.sort_unstable(); + textures.dedup(); + let p = Program { base, code, consts, outputs: outs, registers, needs, textures }; + p.check().map_err(|err| SceneError::value("material", err.to_string()))?; + Ok(p) +} diff --git a/native/crates/fsh-scene/src/document.rs b/native/crates/fsh-scene/src/document.rs index 73b7792b..0faa1ad1 100644 --- a/native/crates/fsh-scene/src/document.rs +++ b/native/crates/fsh-scene/src/document.rs @@ -132,9 +132,7 @@ impl Document { nonzero(k.raw(), "material")?; keys.observe(k.raw()); m.validate()?; - if let Some(t) = m.textures.iter().find(|t| !d.textures.contains_key(t)) { - return Err(SceneError::UnknownTexture(*t)); - } + m.validate_refs(&d.textures)?; } for (id, n) in &d.nodes { nonzero(id.raw(), "node")?; diff --git a/native/crates/fsh-scene/src/graph.rs b/native/crates/fsh-scene/src/graph.rs new file mode 100644 index 00000000..3f48203f --- /dev/null +++ b/native/crates/fsh-scene/src/graph.rs @@ -0,0 +1,906 @@ +use crate::error::{Result, SceneError}; +use crate::material::TextureRef; +use crate::ser; +use crate::slots::{validate_projection, MapProjection, MaterialInput, UvTransform}; +use fsh_core::TextureKey; +use fsh_materials::{ColourSpace, Filter, ProcKind, Wrap}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Most nodes a graph may hold. +pub const MAX_GRAPH_NODES: usize = 256; +/// Most stops a colour ramp may hold. +pub const MAX_RAMP_STOPS: usize = 16; + +/// Value type of a socket. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SocketType { + /// One number. + Float, + /// ACEScg colour. + Colour, + /// Position or texture coordinate. + Vector, + /// Unit world normal. + Normal, +} + +impl SocketType { + /// True when a value of type `self` may feed an input of type `to` (Cycles-style implicit conversions). + pub fn converts_to(self, to: SocketType) -> bool { + use SocketType::*; + match (self, to) { + (a, b) if a == b => true, + (Normal, Vector) | (Vector, Normal) => true, + (Normal, _) | (_, Normal) => false, + _ => true, + } + } +} + +/// One socket of a node kind. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct SocketSpec { + /// Socket name. + pub name: &'static str, + /// Value type. + pub ty: SocketType, + /// Value when unlinked (floats use x). + pub default: [f32; 3], +} + +/// One setting of a node kind (not a socket). +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct SettingSpec { + /// Field name in the node JSON. + pub name: &'static str, + /// "enum", "u32", "bool", "texture", "projection", "transform", "colour_space", "wrap", "filter", "rgba", "stops", "value". + pub kind: &'static str, + /// Allowed values of an enum. + pub values: &'static [&'static str], +} + +/// A node kind: its sockets and settings. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct GraphKind { + /// Kind id (the node's `kind`). + pub id: &'static str, + /// English label. + pub label: &'static str, + /// Input sockets in order. + pub inputs: &'static [SocketSpec], + /// Output sockets in order. + pub outputs: &'static [SocketSpec], + /// Settings. + pub settings: &'static [SettingSpec], + /// Procedural evaluated by `fsh_materials::procedural`, if any. + #[serde(skip)] + pub procedural: Option<ProcKind>, +} + +const fn s(name: &'static str, ty: SocketType, d: f32) -> SocketSpec { + SocketSpec { name, ty, default: [d, d, d] } +} + +const fn c(name: &'static str, r: f32, g: f32, b: f32) -> SocketSpec { + SocketSpec { name, ty: SocketType::Colour, default: [r, g, b] } +} + +const fn e(name: &'static str, values: &'static [&'static str]) -> SettingSpec { + SettingSpec { name, kind: "enum", values } +} + +const fn k(name: &'static str, kind: &'static str) -> SettingSpec { + SettingSpec { name, kind, values: &[] } +} + +use SocketType::{Float as F, Normal as N, Vector as V}; + +const VEC: SocketSpec = s("vector", V, 0.0); +const SEED: SettingSpec = k("seed", "u32"); +const VALUE: SocketSpec = s("value", F, 0.0); +const COLOUR: SocketSpec = c("colour", 0.0, 0.0, 0.0); + +static KINDS: &[GraphKind] = &[ + GraphKind { id: "constant", label: "Constant", inputs: &[], outputs: &[s("value", F, 0.0)], settings: &[k("value", "value")], procedural: None }, + GraphKind { + id: "texture", + label: "Image texture", + inputs: &[VEC], + outputs: &[COLOUR, s("alpha", F, 1.0)], + settings: &[ + k("texture", "texture"), + k("projection", "projection"), + k("transform", "transform"), + e("wrap", &["repeat", "clamp", "mirror"]), + e("filter", &["nearest", "bilinear", "trilinear"]), + k("colour_space", "colour_space"), + k("fallback", "rgba"), + ], + procedural: None, + }, + GraphKind { + id: "mapping", + label: "Mapping", + inputs: &[], + outputs: &[VEC], + settings: &[k("projection", "projection"), k("transform", "transform")], + procedural: None, + }, + GraphKind { + id: "mix", + label: "Mix", + inputs: &[c("a", 0.0, 0.0, 0.0), c("b", 1.0, 1.0, 1.0), s("factor", F, 0.5)], + outputs: &[c("result", 0.0, 0.0, 0.0)], + settings: &[], + procedural: None, + }, + GraphKind { + id: "math", + label: "Math", + inputs: &[s("a", F, 0.0), s("b", F, 0.0), s("c", F, 0.0)], + outputs: &[VALUE], + settings: &[e("op", &["add", "subtract", "multiply", "divide", "minimum", "maximum", "lerp", "clamp", "power", "invert"])], + procedural: None, + }, + GraphKind { + id: "colour_ramp", + label: "Colour ramp", + inputs: &[s("factor", F, 0.5)], + outputs: &[COLOUR, s("alpha", F, 1.0)], + settings: &[k("stops", "stops"), e("interpolation", &["linear", "constant", "smooth"])], + procedural: None, + }, + GraphKind { + id: "normal_map", + label: "Normal map", + inputs: &[c("colour", 0.5, 0.5, 1.0), s("strength", F, 1.0)], + outputs: &[s("normal", N, 0.0)], + settings: &[k("flip_y", "bool")], + procedural: None, + }, + GraphKind { + id: "bump", + label: "Bump", + inputs: &[s("height", F, 0.0), s("strength", F, 0.001), s("normal", N, 0.0)], + outputs: &[s("normal", N, 0.0)], + settings: &[], + procedural: None, + }, + GraphKind { + id: "noise", + label: "Noise", + inputs: &[VEC, s("scale", F, 5.0), s("detail", F, 2.0), s("roughness", F, 0.5), s("distortion", F, 0.0)], + outputs: &[VALUE, COLOUR], + settings: &[SEED], + procedural: Some(ProcKind::Noise), + }, + GraphKind { + id: "fbm", + label: "Fractal noise", + inputs: &[VEC, s("scale", F, 5.0), s("octaves", F, 6.0), s("lacunarity", F, 2.0), s("gain", F, 0.5)], + outputs: &[VALUE, COLOUR], + settings: &[SEED], + procedural: Some(ProcKind::Fbm), + }, + GraphKind { + id: "voronoi", + label: "Voronoi", + inputs: &[VEC, s("scale", F, 5.0), s("randomness", F, 1.0)], + outputs: &[s("distance", F, 0.0), COLOUR, s("position", V, 0.0)], + settings: &[SEED, e("metric", &["euclidean", "manhattan", "chebyshev"]), e("feature", &["f1", "f2", "edge"])], + procedural: Some(ProcKind::Voronoi), + }, + GraphKind { + id: "checker", + label: "Checker", + inputs: &[VEC, s("scale", F, 5.0), c("colour1", 0.8, 0.8, 0.8), c("colour2", 0.2, 0.2, 0.2)], + outputs: &[COLOUR, VALUE], + settings: &[], + procedural: Some(ProcKind::Checker), + }, + GraphKind { + id: "gradient", + label: "Gradient", + inputs: &[VEC], + outputs: &[VALUE, COLOUR], + settings: &[e("gradient", &["linear", "quadratic", "radial", "spherical"])], + procedural: Some(ProcKind::Gradient), + }, + GraphKind { + id: "wave", + label: "Wave", + inputs: &[VEC, s("scale", F, 5.0), s("distortion", F, 0.0), s("detail", F, 2.0), s("phase", F, 0.0)], + outputs: &[VALUE, COLOUR], + settings: &[SEED, e("wave", &["bands", "rings"]), e("profile", &["sine", "saw", "triangle"])], + procedural: Some(ProcKind::Wave), + }, + GraphKind { + id: "brushed", + label: "Brushed", + inputs: &[VEC, s("scale", F, 200.0), s("length", F, 0.05), s("strength", F, 1.0)], + outputs: &[VALUE], + settings: &[SEED], + procedural: Some(ProcKind::Brushed), + }, + GraphKind { + id: "flakes", + label: "Flakes", + inputs: &[VEC, s("scale", F, 2000.0), s("density", F, 0.5), s("spread", F, 0.3)], + outputs: &[s("normal", N, 0.0), s("mask", F, 0.0), COLOUR], + settings: &[SEED], + procedural: Some(ProcKind::Flakes), + }, + GraphKind { + id: "wood", + label: "Wood", + inputs: &[VEC, s("scale", F, 1.0), s("rings", F, 20.0), s("distortion", F, 0.5), c("colour1", 0.45, 0.28, 0.14), c("colour2", 0.2, 0.1, 0.05)], + outputs: &[COLOUR, VALUE], + settings: &[SEED], + procedural: Some(ProcKind::Wood), + }, + GraphKind { + id: "marble", + label: "Marble", + inputs: &[VEC, s("scale", F, 1.0), s("veins", F, 4.0), s("distortion", F, 1.0), c("colour1", 0.85, 0.84, 0.82), c("colour2", 0.3, 0.3, 0.32)], + outputs: &[COLOUR, VALUE], + settings: &[SEED], + procedural: Some(ProcKind::Marble), + }, +]; + +/// Every node kind, in catalogue order. +pub fn graph_kinds() -> &'static [GraphKind] { + KINDS +} + +/// A node kind by id. +pub fn graph_kind(id: &str) -> Option<&'static GraphKind> { + KINDS.iter().find(|k| k.id == id) +} + +/// Every node kind as JSON for the material page. +pub fn graph_kinds_json() -> Value { + Value::Array( + KINDS + .iter() + .map(|k| { + let mut v = serde_json::to_value(k).unwrap_or(Value::Null); + v["procedural"] = json!(k.procedural.is_some()); + v + }) + .collect(), + ) +} + +/// An unlinked socket value: a number or an rgb triple. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SocketValue { + /// One number. + Float(f32), + /// Three numbers. + Colour([f32; 3]), +} + +impl SocketValue { + /// As a vec4 (floats splatted, w 1). + pub fn vec4(self) -> [f32; 4] { + match self { + SocketValue::Float(v) => [v, v, v, 1.0], + SocketValue::Colour(c) => [c[0], c[1], c[2], 1.0], + } + } + + fn finite(self) -> bool { + self.vec4().iter().all(|v| v.is_finite()) + } +} + +/// Arithmetic of a math node. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MathOp { + /// a + b. + #[default] + Add, + /// a - b. + Subtract, + /// a * b. + Multiply, + /// a / b (0 where b is 0). + Divide, + /// min(a, b). + Minimum, + /// max(a, b). + Maximum, + /// a + (b - a) * c. + Lerp, + /// min(max(a, b), c). + Clamp, + /// max(a, 0)^b. + Power, + /// 1 - a. + Invert, +} + +/// Interpolation between ramp stops. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RampInterpolation { + /// Straight lines. + #[default] + Linear, + /// Steps (the left stop's colour). + Constant, + /// Smoothstep between stops. + Smooth, +} + +/// One colour ramp stop. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct RampStop { + /// Position along the factor. + pub position: f32, + /// Colour and alpha. + pub colour: [f32; 4], +} + +/// Distance metric of a voronoi node. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum VoronoiMetric { + /// Straight-line distance. + #[default] + Euclidean, + /// Sum of axis distances. + Manhattan, + /// Largest axis distance. + Chebyshev, +} + +/// Feature of a voronoi node. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum VoronoiFeature { + /// Nearest point. + #[default] + F1, + /// Second nearest point. + F2, + /// Distance to the cell edge. + Edge, +} + +/// Shape of a gradient node. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GradientKind { + /// Along x. + #[default] + Linear, + /// Along x, squared. + Quadratic, + /// Angle around z. + Radial, + /// Distance from the origin. + Spherical, +} + +/// Shape of a wave node. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WaveKind { + /// Straight bands. + #[default] + Bands, + /// Concentric rings. + Rings, +} + +/// Profile of a wave node. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WaveProfile { + /// Sine. + #[default] + Sine, + /// Sawtooth. + Saw, + /// Triangle. + Triangle, +} + +fn grey_fallback() -> [f32; 4] { + [0.5, 0.5, 0.5, 1.0] +} + +fn default_stops() -> Vec<RampStop> { + vec![RampStop { position: 0.0, colour: [0.0, 0.0, 0.0, 1.0] }, RampStop { position: 1.0, colour: [1.0, 1.0, 1.0, 1.0] }] +} + +/// What a node does, with its settings; JSON tagged by `kind`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum GraphOp { + /// A fixed value. + Constant { + /// Number or rgb. + value: SocketValue, + }, + /// An image texture. + Texture { + /// Document texture; null samples the fallback. + #[serde(default, with = "ser::key_opt")] + texture: Option<TextureKey>, + /// Coordinate source when `vector` is unlinked. + #[serde(default)] + projection: MapProjection, + /// Coordinate transform. + #[serde(default)] + transform: UvTransform, + /// Wrapping. + #[serde(default)] + wrap: Wrap, + /// Filtering. + #[serde(default)] + filter: Filter, + /// Colour space; sRGB when absent. + #[serde(default)] + colour_space: Option<ColourSpace>, + /// Value without an image. + #[serde(default = "grey_fallback")] + fallback: [f32; 4], + }, + /// Texture coordinates from a projection and a transform. + Mapping { + /// Projection. + #[serde(default)] + projection: MapProjection, + /// Transform. + #[serde(default)] + transform: UvTransform, + }, + /// Linear blend of two colours. + Mix {}, + /// Arithmetic on floats. + Math { + /// Operation. + #[serde(default)] + op: MathOp, + }, + /// Colour ramp. + ColourRamp { + /// Stops, sorted by position. + #[serde(default = "default_stops")] + stops: Vec<RampStop>, + /// Interpolation. + #[serde(default)] + interpolation: RampInterpolation, + }, + /// Tangent-space normal map. + NormalMap { + /// Green points down (DirectX). + #[serde(default)] + flip_y: bool, + }, + /// Bump from a height. + Bump {}, + /// Gradient noise. + Noise { + /// Seed. + #[serde(default)] + seed: u32, + }, + /// Fractal noise. + Fbm { + /// Seed. + #[serde(default)] + seed: u32, + }, + /// Cellular pattern. + Voronoi { + /// Seed. + #[serde(default)] + seed: u32, + /// Metric. + #[serde(default)] + metric: VoronoiMetric, + /// Feature. + #[serde(default)] + feature: VoronoiFeature, + }, + /// Checker. + Checker {}, + /// Gradient. + Gradient { + /// Shape. + #[serde(default)] + gradient: GradientKind, + }, + /// Bands or rings. + Wave { + /// Seed. + #[serde(default)] + seed: u32, + /// Shape. + #[serde(default)] + wave: WaveKind, + /// Profile. + #[serde(default)] + profile: WaveProfile, + }, + /// Brushed streaks. + Brushed { + /// Seed. + #[serde(default)] + seed: u32, + }, + /// Metallic flakes. + Flakes { + /// Seed. + #[serde(default)] + seed: u32, + }, + /// Wood rings. + Wood { + /// Seed. + #[serde(default)] + seed: u32, + }, + /// Marble veins. + Marble { + /// Seed. + #[serde(default)] + seed: u32, + }, +} + +impl GraphOp { + /// Kind id. + pub fn kind_id(&self) -> &'static str { + match self { + GraphOp::Constant { .. } => "constant", + GraphOp::Texture { .. } => "texture", + GraphOp::Mapping { .. } => "mapping", + GraphOp::Mix {} => "mix", + GraphOp::Math { .. } => "math", + GraphOp::ColourRamp { .. } => "colour_ramp", + GraphOp::NormalMap { .. } => "normal_map", + GraphOp::Bump {} => "bump", + GraphOp::Noise { .. } => "noise", + GraphOp::Fbm { .. } => "fbm", + GraphOp::Voronoi { .. } => "voronoi", + GraphOp::Checker {} => "checker", + GraphOp::Gradient { .. } => "gradient", + GraphOp::Wave { .. } => "wave", + GraphOp::Brushed { .. } => "brushed", + GraphOp::Flakes { .. } => "flakes", + GraphOp::Wood { .. } => "wood", + GraphOp::Marble { .. } => "marble", + } + } + + /// The kind's catalogue entry. + pub fn kind(&self) -> &'static GraphKind { + graph_kind(self.kind_id()).unwrap_or(&KINDS[0]) + } + + /// Type of an output socket (a constant's type follows its value). + pub fn output_type(&self, socket: &str) -> Option<SocketType> { + if let GraphOp::Constant { value } = self { + return (socket == "value").then_some(match value { + SocketValue::Float(_) => SocketType::Float, + SocketValue::Colour(_) => SocketType::Colour, + }); + } + self.kind().outputs.iter().find(|s| s.name == socket).map(|s| s.ty) + } + + /// Spec of an input socket. + pub fn input(&self, socket: &str) -> Option<&'static SocketSpec> { + self.kind().inputs.iter().find(|s| s.name == socket) + } + + /// Settings vector of a procedural: (seed, mode 1, mode 2, 0). + pub fn procedural_settings(&self) -> [f32; 4] { + match *self { + GraphOp::Noise { seed } | GraphOp::Fbm { seed } | GraphOp::Brushed { seed } | GraphOp::Flakes { seed } => { + [seed as f32, 0.0, 0.0, 0.0] + } + GraphOp::Wood { seed } | GraphOp::Marble { seed } => [seed as f32, 0.0, 0.0, 0.0], + GraphOp::Voronoi { seed, metric, feature } => [seed as f32, metric as u8 as f32, feature as u8 as f32, 0.0], + GraphOp::Gradient { gradient } => [0.0, gradient as u8 as f32, 0.0, 0.0], + GraphOp::Wave { seed, wave, profile } => [seed as f32, wave as u8 as f32, profile as u8 as f32, 0.0], + _ => [0.0; 4], + } + } + + /// The texture a node samples. + pub fn texture(&self) -> Option<TextureKey> { + match self { + GraphOp::Texture { texture, .. } => *texture, + _ => None, + } + } + + fn validate(&self, field: &str, textures: &BTreeMap<TextureKey, TextureRef>) -> Result<()> { + match self { + GraphOp::Constant { value } if !value.finite() => Err(SceneError::value(field, "value must be finite")), + GraphOp::Texture { texture, projection, transform, fallback, .. } => { + if let Some(t) = texture { + if !textures.contains_key(t) { + return Err(SceneError::UnknownTexture(*t)); + } + } + validate_projection(projection, field)?; + transform.validate(field)?; + if !fallback.iter().all(|v| v.is_finite()) { + return Err(SceneError::value(field, "fallback must be finite")); + } + Ok(()) + } + GraphOp::Mapping { projection, transform } => { + validate_projection(projection, field)?; + transform.validate(field) + } + GraphOp::ColourRamp { stops, .. } => { + if stops.is_empty() || stops.len() > MAX_RAMP_STOPS { + return Err(SceneError::value(field, format!("a ramp needs 1 to {MAX_RAMP_STOPS} stops"))); + } + if stops.iter().any(|s| !s.position.is_finite() || !s.colour.iter().all(|v| v.is_finite())) { + return Err(SceneError::value(field, "ramp stops must be finite")); + } + if stops.windows(2).any(|w| w[1].position < w[0].position) { + return Err(SceneError::value(field, "ramp stops must be sorted by position")); + } + Ok(()) + } + _ => Ok(()), + } + } +} + +/// A graph node: what it does, its unlinked input values and its place on the canvas. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GraphNode { + /// Kind and settings. + #[serde(flatten)] + pub op: GraphOp, + /// Values of unlinked inputs (absent inputs use the kind's default). + #[serde(default)] + pub inputs: BTreeMap<String, SocketValue>, + /// Canvas position. + #[serde(default)] + pub position: [f32; 2], + /// Optional label. + #[serde(default)] + pub label: String, +} + +impl GraphNode { + /// Node with default inputs. + pub fn new(op: GraphOp) -> Self { + Self { op, inputs: BTreeMap::new(), position: [0.0, 0.0], label: String::new() } + } + + /// Sets an unlinked input value. + pub fn with(mut self, socket: &str, value: SocketValue) -> Self { + self.inputs.insert(socket.to_string(), value); + self + } + + /// Value of an unlinked input (vec4), the kind's default when unset. + pub fn input_value(&self, socket: &str) -> [f32; 4] { + if let Some(v) = self.inputs.get(socket) { + return v.vec4(); + } + self.op.input(socket).map(|s| [s.default[0], s.default[1], s.default[2], 1.0]).unwrap_or([0.0, 0.0, 0.0, 1.0]) + } +} + +mod node_map { + use super::GraphNode; + use serde::{Deserialize, Deserializer, Serializer}; + use std::collections::BTreeMap; + + pub fn serialize<S: Serializer>(m: &BTreeMap<u32, GraphNode>, s: S) -> Result<S::Ok, S::Error> { + s.collect_map(m.iter().map(|(k, v)| (k.to_string(), v))) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<BTreeMap<u32, GraphNode>, D::Error> { + let raw = BTreeMap::<String, GraphNode>::deserialize(d)?; + let mut out = BTreeMap::new(); + for (k, v) in raw { + let id = k.trim().parse::<u32>().map_err(|_| serde::de::Error::custom(format!("node id \"{k}\" is not a number")))?; + out.insert(id, v); + } + Ok(out) + } +} + +/// A node socket: `[node, "socket"]`. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct SocketRef(pub u32, pub String); + +impl SocketRef { + /// Socket of a node. + pub fn new(node: u32, socket: &str) -> Self { + Self(node, socket.to_string()) + } +} + +/// A connection from an output socket to an input socket. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Link { + /// Output socket. + pub from: SocketRef, + /// Input socket. + pub to: SocketRef, +} + +/// A material's node graph; its outputs drive material inputs. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct MaterialGraph { + /// Nodes by id. + #[serde(with = "node_map")] + pub nodes: BTreeMap<u32, GraphNode>, + /// Links, sorted by (to, from). + pub links: Vec<Link>, + /// Material input driven by each output socket. + pub outputs: BTreeMap<MaterialInput, SocketRef>, +} + +impl MaterialGraph { + /// Empty graph. + pub fn new() -> Self { + Self::default() + } + + /// Adds a node and returns its id (one past the largest id). + pub fn add(&mut self, node: GraphNode) -> u32 { + let id = self.nodes.keys().next_back().copied().unwrap_or(0) + 1; + self.nodes.insert(id, node); + id + } + + /// Links an output socket to an input socket. + pub fn link(&mut self, from: u32, from_socket: &str, to: u32, to_socket: &str) { + self.links.push(Link { from: SocketRef::new(from, from_socket), to: SocketRef::new(to, to_socket) }); + self.normalize(); + } + + /// Drives a material input from an output socket. + pub fn output(&mut self, input: MaterialInput, node: u32, socket: &str) { + self.outputs.insert(input, SocketRef::new(node, socket)); + } + + /// Sorts and deduplicates links so serialisation is stable. + pub fn normalize(&mut self) { + self.links.sort_by(|a, b| (&a.to, &a.from).cmp(&(&b.to, &b.from))); + self.links.dedup(); + } + + /// The link feeding an input socket. + pub fn link_into(&self, node: u32, socket: &str) -> Option<&SocketRef> { + self.links.iter().find(|l| l.to.0 == node && l.to.1 == socket).map(|l| &l.from) + } + + /// Texture keys the graph samples. + pub fn texture_keys(&self) -> Vec<TextureKey> { + let mut v: Vec<TextureKey> = self.nodes.values().filter_map(|n| n.op.texture()).collect(); + v.sort_unstable(); + v.dedup(); + v + } + + /// Rewrites texture keys through `f` (imports and texture removal). + pub fn map_textures(&mut self, f: impl Fn(TextureKey) -> Option<TextureKey>) { + for n in self.nodes.values_mut() { + if let GraphOp::Texture { texture, .. } = &mut n.op { + *texture = texture.and_then(&f); + } + } + } + + /// Checks structure, types, settings and texture references; graphs must have no cycles. + pub fn validate(&self, textures: &BTreeMap<TextureKey, TextureRef>) -> Result<()> { + let bad = |m: String| Err(SceneError::value("graph", m)); + if self.nodes.len() > MAX_GRAPH_NODES { + return bad(format!("has {} nodes; at most {MAX_GRAPH_NODES} are allowed", self.nodes.len())); + } + for (id, n) in &self.nodes { + if *id == 0 { + return bad("node id 0 is not allowed".into()); + } + let field = format!("graph.nodes.{id}"); + n.op.validate(&field, textures)?; + for (name, v) in &n.inputs { + let Some(spec) = n.op.input(name) else { + return bad(format!("node {id} ({}) has no input {name}", n.op.kind_id())); + }; + if !v.finite() { + return bad(format!("node {id} input {name} must be finite")); + } + if spec.ty == SocketType::Float && matches!(v, SocketValue::Colour(_)) { + return bad(format!("node {id} input {name} takes a number")); + } + } + } + let mut fed = BTreeSet::new(); + for l in &self.links { + let (Some(from), Some(to)) = (self.nodes.get(&l.from.0), self.nodes.get(&l.to.0)) else { + return bad(format!("link {} {} -> {} {} names a missing node", l.from.0, l.from.1, l.to.0, l.to.1)); + }; + let Some(ft) = from.op.output_type(&l.from.1) else { + return bad(format!("node {} ({}) has no output {}", l.from.0, from.op.kind_id(), l.from.1)); + }; + let Some(spec) = to.op.input(&l.to.1) else { + return bad(format!("node {} ({}) has no input {}", l.to.0, to.op.kind_id(), l.to.1)); + }; + if !ft.converts_to(spec.ty) { + return bad(format!("{:?} output {} {} cannot feed {:?} input {} {}", ft, l.from.0, l.from.1, spec.ty, l.to.0, l.to.1)); + } + if !fed.insert((l.to.0, l.to.1.clone())) { + return bad(format!("input {} {} has more than one link", l.to.0, l.to.1)); + } + } + for (input, r) in &self.outputs { + if *input == MaterialInput::Bump { + return bad("bump is not a graph output; link a bump node into normal".into()); + } + let Some(n) = self.nodes.get(&r.0) else { + return bad(format!("output {} names missing node {}", input.name(), r.0)); + }; + let Some(ty) = n.op.output_type(&r.1) else { + return bad(format!("node {} ({}) has no output {}", r.0, n.op.kind_id(), r.1)); + }; + let want = match input { + MaterialInput::Normal => SocketType::Normal, + i if i.is_colour() => SocketType::Colour, + _ => SocketType::Float, + }; + if !ty.converts_to(want) { + return bad(format!("{:?} output {} {} cannot drive {}", ty, r.0, r.1, input.name())); + } + } + self.order().map(|_| ()) + } + + /// Node ids in dependency order (inputs before users); fails on a cycle. + pub fn order(&self) -> Result<Vec<u32>> { + let mut state: BTreeMap<u32, u8> = BTreeMap::new(); + let mut out = Vec::with_capacity(self.nodes.len()); + for start in self.nodes.keys() { + if state.contains_key(start) { + continue; + } + let mut stack = vec![(*start, false)]; + while let Some((id, done)) = stack.pop() { + if done { + state.insert(id, 2); + out.push(id); + continue; + } + match state.get(&id) { + Some(2) => continue, + Some(1) => return Err(SceneError::value("graph", format!("has a cycle through node {id}"))), + _ => {} + } + state.insert(id, 1); + stack.push((id, true)); + for l in self.links.iter().filter(|l| l.to.0 == id) { + match state.get(&l.from.0) { + Some(1) => return Err(SceneError::value("graph", format!("has a cycle through node {}", l.from.0))), + Some(2) => {} + _ => stack.push((l.from.0, false)), + } + } + } + } + Ok(out) + } +} diff --git a/native/crates/fsh-scene/src/labels.rs b/native/crates/fsh-scene/src/labels.rs new file mode 100644 index 00000000..93fbe7e1 --- /dev/null +++ b/native/crates/fsh-scene/src/labels.rs @@ -0,0 +1,225 @@ +use crate::error::{Result, SceneError}; +use crate::ser; +use fsh_core::{MaterialKey, TextureKey, Vec3}; +use fsh_materials::ColourSpace; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// An image projected onto the parts wearing a material (a decal), placed in the object space of those parts. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Label { + /// Id, unique within the material; allocated when 0. + pub id: u32, + /// Display name. + pub name: String, + /// Image; a label without one is kept but draws nothing. + #[serde(with = "ser::key_opt")] + pub texture: Option<TextureKey>, + /// Colour space of the image; the texture's hint, else sRGB, when absent. + pub colour_space: Option<ColourSpace>, + /// Centre of the label on the surface, object space (metres). + pub origin: [f32; 3], + /// Direction the label faces (projection axis), object space. + pub normal: [f32; 3], + /// Direction of the image's top before rotation, object space; must not be parallel to the normal. + pub up: [f32; 3], + /// Width and height in metres. + pub size: [f32; 2], + /// Radians about the normal, counter-clockwise seen from the front. + pub rotation: f32, + /// Thickness of the projection volume in metres, centred on the origin. + pub depth: f32, + /// 0..1. + pub opacity: f32, + /// Also prints on surfaces facing away from the normal. + pub two_sided: bool, + /// Drawn at all. + pub visible: bool, + /// Specular roughness under the label (0..1); the surface's when absent. + pub roughness: Option<f32>, + /// Metalness under the label (0..1); the surface's when absent. + pub metalness: Option<f32>, +} + +impl Default for Label { + fn default() -> Self { + Self { + id: 0, + name: "Label".into(), + texture: None, + colour_space: None, + origin: [0.0, 0.0, 0.0], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [0.1, 0.1], + rotation: 0.0, + depth: 0.01, + opacity: 1.0, + two_sided: false, + visible: true, + roughness: None, + metalness: None, + } + } +} + +/// Every field a label's JSON holds. +pub const LABEL_FIELDS: [&str; 15] = [ + "id", "name", "texture", "colour_space", "origin", "normal", "up", "size", "rotation", "depth", "opacity", "two_sided", + "visible", "roughness", "metalness", +]; + +/// Refuses a partial label naming a field labels do not have (command arguments; files keep unknown fields). +pub fn check_label_fields(partial: &Value) -> Result<()> { + if let Some(k) = partial.as_object().and_then(|o| o.keys().find(|k| !LABEL_FIELDS.contains(&k.as_str()))) { + return Err(SceneError::value("label", format!("labels have no field \"{k}\""))); + } + Ok(()) +} + +fn v3(a: [f32; 3]) -> Vec3 { + Vec3::new(a[0], a[1], a[2]) +} + +impl Label { + /// True when the label draws: visible and with an image. + pub fn active(&self) -> bool { + self.visible && self.texture.is_some_and(|t| t.is_some()) && self.opacity > 0.0 + } + + /// Checks the values against their ranges. + pub fn validate(&self) -> Result<()> { + let f = |s: &str| format!("labels.{}.{s}", self.id); + let finite = |v: &[f32]| v.iter().all(|x| x.is_finite()); + if !finite(&self.origin) || !finite(&self.normal) || !finite(&self.up) || !self.rotation.is_finite() { + return Err(SceneError::value(f("origin"), "origin, normal, up and rotation must be finite")); + } + if !self.size.iter().all(|s| s.is_finite() && *s > 0.0) { + return Err(SceneError::value(f("size"), "width and height must be positive")); + } + if !(self.depth.is_finite() && self.depth > 0.0) { + return Err(SceneError::value(f("depth"), "must be positive")); + } + if !(self.opacity.is_finite() && (0.0..=1.0).contains(&self.opacity)) { + return Err(SceneError::value(f("opacity"), "must be within 0..1")); + } + for (name, v) in [("roughness", self.roughness), ("metalness", self.metalness)] { + if v.is_some_and(|v| !(v.is_finite() && (0.0..=1.0).contains(&v))) { + return Err(SceneError::value(f(name), "must be within 0..1")); + } + } + let (n, u) = (v3(self.normal), v3(self.up)); + if n.length() < 1.0e-6 || u.length() < 1.0e-6 { + return Err(SceneError::value(f("normal"), "normal and up must not be zero")); + } + if n.normalize().cross(u.normalize()).length() < 1.0e-4 { + return Err(SceneError::value(f("up"), "must not be parallel to the normal")); + } + if self.texture.is_some_and(|t| !t.is_some()) { + return Err(SceneError::value(f("texture"), "names the zero key")); + } + Ok(()) + } + + /// The unit frame (right, up, normal) after rotation; right = up x normal, so the image reads unmirrored from the + /// front. + pub fn frame(&self) -> (Vec3, Vec3, Vec3) { + let n = v3(self.normal).normalize(); + let u0 = (v3(self.up) - n * n.dot(v3(self.up))).normalize(); + let r0 = u0.cross(n); + let (s, c) = self.rotation.sin_cos(); + (r0 * c + u0 * s, u0 * c - r0 * s, n) + } + + /// The twelve constants of the `Label` opcode: origin, right / width, up / height, normal / (depth / 2). + pub fn consts(&self) -> [f32; 12] { + let (r, u, n) = self.frame(); + let (r, u, n) = (r / self.size[0], u / self.size[1], n / (0.5 * self.depth)); + let o = self.origin; + [o[0], o[1], o[2], r.x, r.y, r.z, u.x, u.y, u.z, n.x, n.y, n.z] + } +} + +/// `material.label_add` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MaterialLabelAdd { + /// Material. + #[serde(alias = "material", with = "ser::key")] + pub key: MaterialKey, + /// Partial label over the defaults (stored in history as the full label with its id). + #[serde(default)] + pub label: Value, + /// Position in the list; last when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub index: Option<usize>, + /// Image file to add as a new texture for the label in the same step. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option<String>, + /// Colour-space hint for the new texture. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub colour_space: Option<String>, + /// Key of the new texture; allocated when `path` is given. + #[serde(default, with = "ser::key_opt", skip_serializing_if = "Option::is_none")] + pub texture_key: Option<TextureKey>, +} + +/// `material.label_set` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MaterialLabelSet { + /// Material. + #[serde(alias = "material", with = "ser::key")] + pub key: MaterialKey, + /// Label id. + pub id: u32, + /// Partial label merged onto the current one (stored in history as the full label). + #[serde(default)] + pub label: Value, + /// Image file to add as a new texture and use for the label in the same step. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option<String>, + /// Colour-space hint for the new texture. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub colour_space: Option<String>, + /// Key of the new texture; allocated when `path` is given. + #[serde(default, with = "ser::key_opt", skip_serializing_if = "Option::is_none")] + pub texture_key: Option<TextureKey>, +} + +/// `material.label_remove` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MaterialLabelRef { + /// Material. + #[serde(alias = "material", with = "ser::key")] + pub key: MaterialKey, + /// Label id. + pub id: u32, +} + +/// `material.label_move` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MaterialLabelMove { + /// Material. + #[serde(alias = "material", with = "ser::key")] + pub key: MaterialKey, + /// Label id. + pub id: u32, + /// New position in the list (clamped to the end); later labels draw over earlier ones. + pub index: usize, +} + +/// Checks a material's label list: each label, and ids non-zero and unique. +pub fn validate_labels(labels: &[Label]) -> Result<()> { + let mut seen = std::collections::BTreeSet::new(); + for l in labels { + if l.id == 0 || !seen.insert(l.id) { + return Err(SceneError::value("labels", format!("label id {} is zero or appears twice", l.id))); + } + l.validate()?; + } + Ok(()) +} diff --git a/native/crates/fsh-scene/src/lib.rs b/native/crates/fsh-scene/src/lib.rs index 36557e52..057d404e 100644 --- a/native/crates/fsh-scene/src/lib.rs +++ b/native/crates/fsh-scene/src/lib.rs @@ -3,19 +3,25 @@ mod catalogue; mod command; +mod compile; mod document; mod editor; mod error; +mod graph; mod history; +mod labels; mod material; mod mesh; mod node; +mod preview; pub mod primitives; pub mod ser; mod selection; mod settings; +mod slots; mod snapshot; mod tx; +mod types; pub use catalogue::{catalogue, catalogue_json, CommandInfo}; pub use command::{ @@ -25,15 +31,25 @@ pub use command::{ NodeList, PatchBlock, PatchNode, Rename, Reparent, SetLocked, SetMetadata, SetPartColour, SetPivot, SetRays, SetTransform, SetVisible, TextureAdd, TextureRefArgs, UnitsSetDisplay, }; +pub use compile::{base_inputs, compile_material, TextureTable}; pub use document::{Document, DocumentData, FORMAT_VERSION}; pub use editor::{Editor, Outcome}; pub use error::{Result, SceneError}; +pub use graph::{ + graph_kind, graph_kinds, graph_kinds_json, GradientKind, GraphKind, GraphNode, GraphOp, Link, MaterialGraph, + MathOp, RampInterpolation, RampStop, SettingSpec, SocketRef, SocketSpec, SocketType, SocketValue, VoronoiFeature, + VoronoiMetric, WaveKind, WaveProfile, MAX_GRAPH_NODES, MAX_RAMP_STOPS, +}; pub use history::History; -pub use material::{Material, SurfaceParams, TextureRef, TextureRole}; +pub use labels::{validate_labels, Label, MaterialLabelAdd, MaterialLabelMove, MaterialLabelRef, MaterialLabelSet}; +pub use material::{Material, SurfaceParams, TextureRef, TextureRole, MATERIAL_FIELDS}; +pub use slots::{validate_projection, Channel, CoordSpace, MapProjection, MaterialInput, TextureSlot, UvTransform}; pub use mesh::Mesh; pub use node::{ CapMode, Cutaway, CutawayShape, Light, LightColour, LightShape, Node, NodeKind, PowerUnit, RayVisibility, Trs, }; +pub use fsh_materials; +pub use preview::{bake_preview, preview_hit, PreviewMaps, PREVIEW_MAX, PREVIEW_MIN}; pub use primitives::Primitive; pub use selection::{SelectMode, Selection, SelectionLevel}; pub use settings::{ @@ -42,6 +58,7 @@ pub use settings::{ }; pub use snapshot::{ flatten, Instance, RenderCamera, RenderCutaway, RenderLight, RenderLightShape, RenderMaterial, RenderSnapshot, - SCENE_UNITS_PER_NIT, + RenderTexture, SCENE_UNITS_PER_NIT, }; pub use tx::UndoRecord; +pub use types::{material_type, material_types, metal_colour, types_json, MaterialType, ParamKind, ParamSpec, METALS}; diff --git a/native/crates/fsh-scene/src/material.rs b/native/crates/fsh-scene/src/material.rs index 3f1c8d04..2a2f80f1 100644 --- a/native/crates/fsh-scene/src/material.rs +++ b/native/crates/fsh-scene/src/material.rs @@ -1,7 +1,11 @@ use crate::error::{non_negative, range, Result, SceneError}; +use crate::graph::MaterialGraph; +use crate::labels::{validate_labels, Label}; use crate::ser; +use crate::slots::{MaterialInput, TextureSlot}; use fsh_core::{Rgb, TextureKey}; use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; /// Parameters of one layered physically based surface (field names follow the OpenPBR Surface parameter names). #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] @@ -237,18 +241,81 @@ pub struct Material { /// Textures this material uses. #[serde(with = "ser::key_vec")] pub textures: Vec<TextureKey>, + /// Image textures driving inputs, by input (left out of the JSON when empty). + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub slots: BTreeMap<MaterialInput, TextureSlot>, + /// Node graph whose outputs drive inputs over slots and constants (left out of the JSON when absent). + #[serde(skip_serializing_if = "Option::is_none")] + pub graph: Option<Box<MaterialGraph>>, + /// Images projected onto the parts, drawn in order over slots and graph (left out of the JSON when empty). + #[serde(skip_serializing_if = "Vec::is_empty")] + pub labels: Vec<Label>, } +/// Every field a material's JSON may hold, including those left out when empty (for readers that keep unknown +/// fields apart). +pub const MATERIAL_FIELDS: [&str; 7] = ["name", "type_id", "params", "textures", "slots", "graph", "labels"]; + impl Default for Material { fn default() -> Self { - Self { name: "Material".into(), type_id: "generic".into(), params: SurfaceParams::default(), textures: Vec::new() } + Self { + name: "Material".into(), + type_id: "generic".into(), + params: SurfaceParams::default(), + textures: Vec::new(), + slots: BTreeMap::new(), + graph: None, + labels: Vec::new(), + } } } impl Material { /// Material with a name, type and parameters. pub fn new(name: impl Into<String>, type_id: impl Into<String>, params: SurfaceParams) -> Self { - Self { name: name.into(), type_id: type_id.into(), params, textures: Vec::new() } + Self { name: name.into(), type_id: type_id.into(), params, ..Default::default() } + } + + /// Every texture key the material refers to (list, slots and graph), sorted and unique. + pub fn texture_keys(&self) -> Vec<TextureKey> { + let mut v: Vec<TextureKey> = self.textures.clone(); + v.extend(self.slots.values().map(|s| s.texture)); + if let Some(g) = &self.graph { + v.extend(g.texture_keys()); + } + v.extend(self.labels.iter().filter_map(|l| l.texture)); + v.sort_unstable(); + v.dedup(); + v + } + + /// Checks slots and graph against the document's textures. + pub fn validate_refs(&self, textures: &BTreeMap<TextureKey, TextureRef>) -> Result<()> { + if let Some(t) = self.texture_keys().into_iter().find(|t| !textures.contains_key(t)) { + return Err(SceneError::UnknownTexture(t)); + } + if let Some(g) = &self.graph { + g.validate(textures)?; + } + Ok(()) + } + + /// Rewrites texture keys in the list, slots and graph; slots whose texture maps to `None` are dropped. + pub fn map_textures(&mut self, f: impl Fn(TextureKey) -> Option<TextureKey>) { + self.textures = self.textures.iter().filter_map(|t| f(*t)).collect(); + self.slots.retain(|_, s| match f(s.texture) { + Some(t) => { + s.texture = t; + true + } + None => false, + }); + if let Some(g) = &mut self.graph { + g.map_textures(&f); + } + for l in &mut self.labels { + l.texture = l.texture.and_then(&f); + } } /// Checks parameters and name. @@ -259,6 +326,10 @@ impl Material { if self.textures.iter().any(|t| !t.is_some()) { return Err(SceneError::value("material.textures", "contains the zero key")); } + for (input, slot) in &self.slots { + slot.validate(*input)?; + } + validate_labels(&self.labels)?; self.params.validate() } } diff --git a/native/crates/fsh-scene/src/preview.rs b/native/crates/fsh-scene/src/preview.rs new file mode 100644 index 00000000..0dfa517c --- /dev/null +++ b/native/crates/fsh-scene/src/preview.rs @@ -0,0 +1,93 @@ +use crate::compile::{compile_material, TextureTable}; +use crate::error::Result; +use crate::material::{Material, TextureRef}; +use crate::snapshot::RenderTexture; +use fsh_core::{TextureKey, Vec2, Vec3}; +use fsh_materials::{HitContext, Program, TextureSampler, MAX_UV_SETS}; +use std::collections::BTreeMap; + +/// Smallest preview map size. +pub const PREVIEW_MIN: u32 = 16; +/// Largest preview map size. +pub const PREVIEW_MAX: u32 = 512; + +/// Small maps baked in uv space for the window's raster material view; RGBA8, row 0 at v = 1. +#[derive(Clone, Debug, PartialEq)] +pub struct PreviewMaps { + /// Width and height in pixels. + pub size: u32, + /// The material has nothing varying; the maps are flat. + pub constant: bool, + /// The compiled program (its `base` holds the constant values). + pub program: Program, + /// Textures the program samples, by index (build the sampler for this list). + pub textures: Vec<RenderTexture>, + /// Base colour, sRGB encoded, opacity in alpha. + pub base_color: Vec<u8>, + /// Specular roughness, linear grey. + pub roughness: Vec<u8>, + /// Metalness, linear grey. + pub metalness: Vec<u8>, + /// Tangent-space normal, `0.5 + 0.5 n`. + pub normal: Vec<u8>, +} + +fn byte(v: f32) -> u8 { + (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 +} + +/// The hit used for preview pixel (x, y): a 1 m square in the object XY plane facing +Z, uv from the pixel centre. +pub fn preview_hit(x: u32, y: u32, size: u32) -> HitContext { + let s = size.max(1) as f32; + let u = (x as f32 + 0.5) / s; + let v = 1.0 - (y as f32 + 0.5) / s; + let p = Vec3::new(u - 0.5, v - 0.5, 0.0); + HitContext { + p, + p_object: p, + uv: [Vec2::new(u, v); MAX_UV_SETS], + uv_count: 1, + tangent: Vec3::X, + tangent_sign: 1.0, + footprint: 1.0 / s, + ..HitContext::default() + } +} + +/// Bakes base colour, roughness, metalness and normal maps of a material with the CPU interpreter. +pub fn bake_preview( + m: &Material, + doc_textures: &BTreeMap<TextureKey, TextureRef>, + size: u32, + sampler: &dyn TextureSampler, +) -> Result<PreviewMaps> { + let size = size.clamp(PREVIEW_MIN, PREVIEW_MAX); + let mut table = TextureTable::new(doc_textures); + let program = compile_material(m, &mut table)?; + let n = (size * size * 4) as usize; + let (mut base, mut rough, mut metal, mut normal) = (vec![0u8; n], vec![0u8; n], vec![0u8; n], vec![0u8; n]); + for y in 0..size { + for x in 0..size { + let s = program.evaluate(&preview_hit(x, y, size), sampler); + let i = ((y * size + x) * 4) as usize; + let c = s.inputs.base_color.to_srgb8(); + base[i..i + 4].copy_from_slice(&[c[0], c[1], c[2], byte(s.inputs.opacity)]); + let r = byte(s.inputs.specular_roughness); + rough[i..i + 4].copy_from_slice(&[r, r, r, 255]); + let mt = byte(s.inputs.base_metalness); + metal[i..i + 4].copy_from_slice(&[mt, mt, mt, 255]); + let nn = s.normal; + normal[i..i + 4].copy_from_slice(&[byte(0.5 + 0.5 * nn.x), byte(0.5 + 0.5 * nn.y), byte(0.5 + 0.5 * nn.z), 255]); + } + } + Ok(PreviewMaps { + size, + constant: program.is_constant(), + program, + textures: table.list, + base_color: base, + roughness: rough, + metalness: metal, + normal, + }) +} diff --git a/native/crates/fsh-scene/src/primitives.rs b/native/crates/fsh-scene/src/primitives.rs index d6dfeeac..91054044 100644 --- a/native/crates/fsh-scene/src/primitives.rs +++ b/native/crates/fsh-scene/src/primitives.rs @@ -234,7 +234,8 @@ pub fn cylinder(radius: f32, height: f32, segments: u32, capped: bool) -> Result for s in 0..=segments { let phi = s as f32 / segments as f32 * 2.0 * PI; let (sx, cz) = (phi.sin(), phi.cos()); - b.vert(Vec3::new(sx * radius, y, cz * radius), n, Vec2::new(0.5 + 0.5 * sx, 0.5 + 0.5 * cz)); + let v = if y > 0.0 { 0.5 - 0.5 * cz } else { 0.5 + 0.5 * cz }; + b.vert(Vec3::new(sx * radius, y, cz * radius), n, Vec2::new(0.5 + 0.5 * sx, v)); } for s in 0..segments { if y > 0.0 { diff --git a/native/crates/fsh-scene/src/slots.rs b/native/crates/fsh-scene/src/slots.rs new file mode 100644 index 00000000..90ffb08a --- /dev/null +++ b/native/crates/fsh-scene/src/slots.rs @@ -0,0 +1,429 @@ +use crate::error::{Result, SceneError}; +use crate::material::SurfaceParams; +use crate::ser; +use fsh_core::TextureKey; +use fsh_materials::{ColourSpace, Field, Filter, Wrap, MAX_UV_SETS}; +use serde::{Deserialize, Serialize}; + +/// A material input a texture slot or a graph output can drive (SurfaceParams field names plus geometry inputs). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MaterialInput { + /// `base_weight`. + BaseWeight, + /// `base_color`. + BaseColor, + /// `base_metalness`. + BaseMetalness, + /// `base_diffuse_roughness`. + BaseDiffuseRoughness, + /// `specular_weight`. + SpecularWeight, + /// `specular_color`. + SpecularColor, + /// `specular_roughness`. + SpecularRoughness, + /// `specular_ior`. + SpecularIor, + /// `specular_roughness_anisotropy`. + SpecularRoughnessAnisotropy, + /// `transmission_weight`. + TransmissionWeight, + /// `transmission_color`. + TransmissionColor, + /// `coat_weight`. + CoatWeight, + /// `coat_color`. + CoatColor, + /// `coat_roughness`. + CoatRoughness, + /// `coat_ior`. + CoatIor, + /// `fuzz_weight`. + FuzzWeight, + /// `fuzz_color`. + FuzzColor, + /// `fuzz_roughness`. + FuzzRoughness, + /// `emission_color` (scaled by `emission_luminance`). + EmissionColor, + /// `geometry_opacity`. + GeometryOpacity, + /// Shading normal (tangent-space normal map, or a graph normal). + Normal, + /// Bump height (slots only; graphs use a bump node). + Bump, + /// Displacement height (stored; not applied per hit). + Displacement, +} + +impl MaterialInput { + /// Every input in order. + pub const ALL: [MaterialInput; 23] = [ + MaterialInput::BaseWeight, + MaterialInput::BaseColor, + MaterialInput::BaseMetalness, + MaterialInput::BaseDiffuseRoughness, + MaterialInput::SpecularWeight, + MaterialInput::SpecularColor, + MaterialInput::SpecularRoughness, + MaterialInput::SpecularIor, + MaterialInput::SpecularRoughnessAnisotropy, + MaterialInput::TransmissionWeight, + MaterialInput::TransmissionColor, + MaterialInput::CoatWeight, + MaterialInput::CoatColor, + MaterialInput::CoatRoughness, + MaterialInput::CoatIor, + MaterialInput::FuzzWeight, + MaterialInput::FuzzColor, + MaterialInput::FuzzRoughness, + MaterialInput::EmissionColor, + MaterialInput::GeometryOpacity, + MaterialInput::Normal, + MaterialInput::Bump, + MaterialInput::Displacement, + ]; + + /// Inputs that accept a texture slot. + pub const SLOTTABLE: [MaterialInput; 11] = [ + MaterialInput::BaseColor, + MaterialInput::SpecularRoughness, + MaterialInput::BaseMetalness, + MaterialInput::SpecularWeight, + MaterialInput::CoatWeight, + MaterialInput::CoatRoughness, + MaterialInput::EmissionColor, + MaterialInput::GeometryOpacity, + MaterialInput::Normal, + MaterialInput::Bump, + MaterialInput::Displacement, + ]; + + /// True when a texture slot may drive this input. + pub fn slottable(self) -> bool { + Self::SLOTTABLE.contains(&self) + } + + /// JSON name. + pub fn name(self) -> &'static str { + match self { + MaterialInput::BaseWeight => "base_weight", + MaterialInput::BaseColor => "base_color", + MaterialInput::BaseMetalness => "base_metalness", + MaterialInput::BaseDiffuseRoughness => "base_diffuse_roughness", + MaterialInput::SpecularWeight => "specular_weight", + MaterialInput::SpecularColor => "specular_color", + MaterialInput::SpecularRoughness => "specular_roughness", + MaterialInput::SpecularIor => "specular_ior", + MaterialInput::SpecularRoughnessAnisotropy => "specular_roughness_anisotropy", + MaterialInput::TransmissionWeight => "transmission_weight", + MaterialInput::TransmissionColor => "transmission_color", + MaterialInput::CoatWeight => "coat_weight", + MaterialInput::CoatColor => "coat_color", + MaterialInput::CoatRoughness => "coat_roughness", + MaterialInput::CoatIor => "coat_ior", + MaterialInput::FuzzWeight => "fuzz_weight", + MaterialInput::FuzzColor => "fuzz_color", + MaterialInput::FuzzRoughness => "fuzz_roughness", + MaterialInput::EmissionColor => "emission_color", + MaterialInput::GeometryOpacity => "geometry_opacity", + MaterialInput::Normal => "normal", + MaterialInput::Bump => "bump", + MaterialInput::Displacement => "displacement", + } + } + + /// Input by JSON name. + pub fn parse(s: &str) -> Option<MaterialInput> { + Self::ALL.iter().copied().find(|i| i.name() == s) + } + + /// True for colour inputs. + pub fn is_colour(self) -> bool { + matches!( + self, + MaterialInput::BaseColor + | MaterialInput::SpecularColor + | MaterialInput::TransmissionColor + | MaterialInput::CoatColor + | MaterialInput::FuzzColor + | MaterialInput::EmissionColor + ) + } + + /// Program field written for this input (bump writes the normal). + pub fn field(self) -> Field { + match self { + MaterialInput::BaseWeight => Field::BaseWeight, + MaterialInput::BaseColor => Field::BaseColor, + MaterialInput::BaseMetalness => Field::BaseMetalness, + MaterialInput::BaseDiffuseRoughness => Field::BaseDiffuseRoughness, + MaterialInput::SpecularWeight => Field::SpecularWeight, + MaterialInput::SpecularColor => Field::SpecularColor, + MaterialInput::SpecularRoughness => Field::SpecularRoughness, + MaterialInput::SpecularIor => Field::SpecularIor, + MaterialInput::SpecularRoughnessAnisotropy => Field::SpecularAnisotropy, + MaterialInput::TransmissionWeight => Field::TransmissionWeight, + MaterialInput::TransmissionColor => Field::TransmissionColor, + MaterialInput::CoatWeight => Field::CoatWeight, + MaterialInput::CoatColor => Field::CoatColor, + MaterialInput::CoatRoughness => Field::CoatRoughness, + MaterialInput::CoatIor => Field::CoatIor, + MaterialInput::FuzzWeight => Field::FuzzWeight, + MaterialInput::FuzzColor => Field::FuzzColor, + MaterialInput::FuzzRoughness => Field::FuzzRoughness, + MaterialInput::EmissionColor => Field::Emission, + MaterialInput::GeometryOpacity => Field::Opacity, + MaterialInput::Normal | MaterialInput::Bump => Field::Normal, + MaterialInput::Displacement => Field::Displacement, + } + } + + /// The constant value of this input in a parameter block (rgb, alpha 1; scalars splatted; geometry inputs 0). + pub fn constant(self, p: &SurfaceParams) -> [f32; 4] { + let c = |c: fsh_core::Rgb| [c.r, c.g, c.b, 1.0]; + let s = |v: f32| [v, v, v, 1.0]; + match self { + MaterialInput::BaseWeight => s(p.base_weight), + MaterialInput::BaseColor => c(p.base_color), + MaterialInput::BaseMetalness => s(p.base_metalness), + MaterialInput::BaseDiffuseRoughness => s(p.base_diffuse_roughness), + MaterialInput::SpecularWeight => s(p.specular_weight), + MaterialInput::SpecularColor => c(p.specular_color), + MaterialInput::SpecularRoughness => s(p.specular_roughness), + MaterialInput::SpecularIor => s(p.specular_ior), + MaterialInput::SpecularRoughnessAnisotropy => s(p.specular_roughness_anisotropy), + MaterialInput::TransmissionWeight => s(p.transmission_weight), + MaterialInput::TransmissionColor => c(p.transmission_color), + MaterialInput::CoatWeight => s(p.coat_weight), + MaterialInput::CoatColor => c(p.coat_color), + MaterialInput::CoatRoughness => s(p.coat_roughness), + MaterialInput::CoatIor => s(p.coat_ior), + MaterialInput::FuzzWeight => s(p.fuzz_weight), + MaterialInput::FuzzColor => c(p.fuzz_color), + MaterialInput::FuzzRoughness => s(p.fuzz_roughness), + MaterialInput::EmissionColor => c(p.emission_color), + MaterialInput::GeometryOpacity => s(p.geometry_opacity), + MaterialInput::Normal => [0.5, 0.5, 1.0, 1.0], + MaterialInput::Bump | MaterialInput::Displacement => [0.0, 0.0, 0.0, 1.0], + } + } +} + +/// How a slot finds its texture coordinate. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum MapProjection { + /// A mesh uv set. + Uv { + /// Uv set index (0..4). + #[serde(default)] + set: u32, + }, + /// Three axis planes blended by the normal (triplanar). + Box { + /// Blend width, 0 (hard seams) to 1. + #[serde(default = "half")] + blend: f32, + }, + /// Along object Z onto the XY plane. + Planar, + /// Around object Y. + Cylindrical, + /// Around the object origin. + Spherical, +} + +fn half() -> f32 { + 0.5 +} + +impl Default for MapProjection { + fn default() -> Self { + MapProjection::Uv { set: 0 } + } +} + +/// Space a projection reads positions in. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CoordSpace { + /// Object space: the pattern moves with the part. + #[default] + Object, + /// World space. + World, +} + +/// Offset, scale and rotation applied to texture coordinates: `uv' = R(rotation) * (uv * scale) + offset`. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct UvTransform { + /// Added after rotation. + pub offset: [f32; 2], + /// Repeats per uv unit, or per metre for projections. + pub scale: [f32; 2], + /// Radians, counter-clockwise. + pub rotation: f32, + /// Space projections read positions in. + pub space: CoordSpace, +} + +impl Default for UvTransform { + fn default() -> Self { + Self { offset: [0.0, 0.0], scale: [1.0, 1.0], rotation: 0.0, space: CoordSpace::Object } + } +} + +impl UvTransform { + /// Checks the values are finite. + pub fn validate(&self, field: &str) -> Result<()> { + if !(self.offset.iter().chain(&self.scale).all(|v| v.is_finite()) && self.rotation.is_finite()) { + return Err(SceneError::value(field, "offset, scale and rotation must be finite")); + } + Ok(()) + } + + /// Program constants `(sx, sy, cos, sin, ox, oy)`. + pub fn consts(&self) -> [f32; 6] { + let (s, c) = self.rotation.sin_cos(); + [self.scale[0], self.scale[1], c, s, self.offset[0], self.offset[1]] + } + + /// True when the transform changes nothing. + pub fn is_identity(&self) -> bool { + self.offset == [0.0, 0.0] && self.scale == [1.0, 1.0] && self.rotation == 0.0 + } +} + +/// Which texel channel a scalar input reads. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Channel { + /// All three colour channels; number inputs read their ACEScg luminance (equal to the value on grey maps). + #[default] + Rgb, + /// Red. + R, + /// Green. + G, + /// Blue. + B, + /// Alpha. + A, + /// ACEScg luminance of rgb. + Luminance, +} + +/// An image texture driving one material input. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct TextureSlot { + /// Document texture. + #[serde(with = "ser::key")] + pub texture: TextureKey, + /// Coordinate source. + pub projection: MapProjection, + /// Coordinate transform. + pub transform: UvTransform, + /// Wrapping outside 0..1. + pub wrap: Wrap, + /// Filtering. + pub filter: Filter, + /// Colour space override; by default sRGB for colour inputs and data otherwise. + pub colour_space: Option<ColourSpace>, + /// Channel scalar inputs read. + pub channel: Channel, + /// Scalar inputs: value = range[0] + t * (range[1] - range[0]). + pub range: [f32; 2], + /// Scalar inputs: t = 1 - t before the range. + pub invert: bool, + /// Multiply by the input's constant value (glTF factor semantics). + pub multiply: bool, + /// Normal: tangent xy scale; bump: metres of height per unit; displacement: metres per unit. + pub strength: f32, + /// Normal: the green channel points down (DirectX convention). + pub flip_y: bool, + /// Value when the image is missing; the input's constant when absent. + pub fallback: Option<[f32; 4]>, +} + +impl Default for TextureSlot { + fn default() -> Self { + Self { + texture: TextureKey::NONE, + projection: MapProjection::default(), + transform: UvTransform::default(), + wrap: Wrap::Repeat, + filter: Filter::Trilinear, + colour_space: None, + channel: Channel::Rgb, + range: [0.0, 1.0], + invert: false, + multiply: false, + strength: 1.0, + flip_y: false, + fallback: None, + } + } +} + +impl TextureSlot { + /// Default slot for an input (bump strength 1 mm). + pub fn for_input(input: MaterialInput, texture: TextureKey) -> Self { + let strength = match input { + MaterialInput::Bump => 0.001, + MaterialInput::Displacement => 0.01, + _ => 1.0, + }; + Self { texture, strength, ..Default::default() } + } + + /// Checks values against their ranges. + pub fn validate(&self, input: MaterialInput) -> Result<()> { + let f = |s: &str| format!("slots.{}.{s}", input.name()); + if !input.slottable() { + return Err(SceneError::value(f("input"), "takes no texture slot")); + } + if !self.texture.is_some() { + return Err(SceneError::value(f("texture"), "must name a texture")); + } + validate_projection(&self.projection, &f("projection"))?; + self.transform.validate(&f("transform"))?; + if !self.range.iter().all(|v| v.is_finite()) { + return Err(SceneError::value(f("range"), "must be finite")); + } + if !self.strength.is_finite() || self.strength.abs() > 1.0e3 { + return Err(SceneError::value(f("strength"), "must be finite and at most 1000 in size")); + } + if self.fallback.is_some_and(|c| !c.iter().all(|v| v.is_finite())) { + return Err(SceneError::value(f("fallback"), "must be finite")); + } + Ok(()) + } + + /// Colour space used: the override, else sRGB for colour inputs and data otherwise. + pub fn colour_space_for(&self, input: MaterialInput, hint: Option<&str>) -> ColourSpace { + self.colour_space.or_else(|| if input.is_colour() { hint.and_then(ColourSpace::parse) } else { None }).unwrap_or( + if input.is_colour() { + ColourSpace::Srgb + } else { + ColourSpace::Data + }, + ) + } +} + +/// Checks a projection's numbers. +pub fn validate_projection(p: &MapProjection, field: &str) -> Result<()> { + match p { + MapProjection::Uv { set } if *set as usize >= MAX_UV_SETS => { + Err(SceneError::value(field, format!("uv set {set} is outside 0..{}", MAX_UV_SETS - 1))) + } + MapProjection::Box { blend } if !(blend.is_finite() && (0.0..=1.0).contains(blend)) => { + Err(SceneError::value(field, "blend must be within 0..1")) + } + _ => Ok(()), + } +} diff --git a/native/crates/fsh-scene/src/snapshot.rs b/native/crates/fsh-scene/src/snapshot.rs index b5f2aad1..611b0e1b 100644 --- a/native/crates/fsh-scene/src/snapshot.rs +++ b/native/crates/fsh-scene/src/snapshot.rs @@ -1,10 +1,12 @@ +use crate::compile::{base_inputs, compile_material, TextureTable}; use crate::document::Document; use crate::material::SurfaceParams; use crate::mesh::Mesh; use crate::node::{CapMode, CutawayShape, Light, LightShape, NodeKind, PowerUnit, RayVisibility}; use crate::settings::{Environment, Ground, ImageStyle, Projection, RenderSettings}; use fsh_core::math::PI; -use fsh_core::{Aabb, MaterialId, MaterialKey, MeshId, MeshKey, NodeId, Rgb, Transform, Vec3}; +use fsh_core::{Aabb, MaterialId, MaterialKey, MeshId, MeshKey, NodeId, Rgb, TextureKey, Transform, Vec3}; +use fsh_materials::{ColourSpace, Program}; use std::collections::BTreeMap; use std::sync::Arc; @@ -41,6 +43,21 @@ pub struct RenderMaterial { pub name: String, /// Surface parameters. pub params: SurfaceParams, + /// Compiled program; constant (`is_constant()`) for materials without slots or a varying graph. + pub program: Arc<Program>, +} + +/// An image a program samples; programs name it by its index in `RenderSnapshot::textures`. +#[derive(Clone, Debug, PartialEq)] +pub struct RenderTexture { + /// Document texture it came from (the first, when several share the image). + pub key: TextureKey, + /// File path, or `fshot:textures/...` for an image embedded in the project. + pub path: String, + /// How texel values are interpreted. + pub colour_space: ColourSpace, + /// Some user wants trilinear filtering, so build the mip pyramid. + pub mipmaps: bool, } /// A light's world-space geometry. @@ -140,6 +157,8 @@ pub struct RenderSnapshot { pub materials: Vec<RenderMaterial>, /// Index of the default material (parts without one). pub default_material: MaterialId, + /// Images the programs sample, deduplicated by (path, colour space). + pub textures: Vec<RenderTexture>, /// Lights that are on. pub lights: Vec<RenderLight>, /// Enabled, visible cutaways. @@ -287,12 +306,17 @@ type PartItem = (MeshKey, Option<MaterialKey>, Transform, u8, Option<Rgb>, NodeI pub fn flatten(doc: &Document) -> Arc<RenderSnapshot> { let mut materials: Vec<RenderMaterial> = Vec::with_capacity(doc.materials().len() + 1); let mut material_index: BTreeMap<MaterialKey, MaterialId> = BTreeMap::new(); + let mut table = TextureTable::new(doc.textures()); for (k, m) in doc.materials() { material_index.insert(*k, MaterialId::from_index(materials.len())); - materials.push(RenderMaterial { key: *k, name: m.name.clone(), params: m.params }); + let program = compile_material(m, &mut table).unwrap_or_else(|_| Program::constant(base_inputs(&m.params))); + materials.push(RenderMaterial { key: *k, name: m.name.clone(), params: m.params, program: Arc::new(program) }); } + let textures = table.list; let default_material = MaterialId::from_index(materials.len()); - materials.push(RenderMaterial { key: MaterialKey::NONE, name: "Default".into(), params: SurfaceParams::default() }); + let params = SurfaceParams::default(); + let program = Arc::new(Program::constant(base_inputs(¶ms))); + materials.push(RenderMaterial { key: MaterialKey::NONE, name: "Default".into(), params, program }); let mut parts: Vec<PartItem> = Vec::new(); let mut lights = Vec::new(); @@ -390,6 +414,7 @@ pub fn flatten(doc: &Document) -> Arc<RenderSnapshot> { instances, materials, default_material, + textures, lights, cutaways, environment: doc.environment().clone(), diff --git a/native/crates/fsh-scene/src/types.rs b/native/crates/fsh-scene/src/types.rs new file mode 100644 index 00000000..65058cab --- /dev/null +++ b/native/crates/fsh-scene/src/types.rs @@ -0,0 +1,459 @@ +use crate::graph::{GraphNode, GraphOp, MaterialGraph, MathOp, SocketValue}; +use crate::material::{Material, SurfaceParams}; +use crate::slots::MaterialInput; +use fsh_core::Rgb; +use serde::Serialize; +use serde_json::{json, Value}; +use std::sync::OnceLock; + +/// How a parameter is edited. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ParamKind { + /// A number between `min` and `max`. + Float, + /// An ACEScg colour. + Colour, + /// On or off. + Bool, +} + +/// One parameter a type's page shows. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct ParamSpec { + /// `SurfaceParams` field name. + pub field: &'static str, + /// Editor kind. + pub kind: ParamKind, + /// Lowest value. + pub min: f32, + /// Highest value (the slider's end; validation may allow more). + pub max: f32, + /// Unit: "", "nits", "m" or "um". + pub unit: &'static str, +} + +impl ParamSpec { + /// True when a texture slot may drive the parameter. + pub fn slot(&self) -> bool { + MaterialInput::parse(self.field).is_some_and(MaterialInput::slottable) + } +} + +/// A material type: a preset of the one surface model and the parameters its page shows. +#[derive(Clone, Debug, PartialEq)] +pub struct MaterialType { + /// Stable id. + pub id: &'static str, + /// English display name. + pub name: &'static str, + /// Library category. + pub category: &'static str, + /// Default parameters. + pub params: SurfaceParams, + /// Parameters the page shows, in order. + pub shown: &'static [ParamSpec], + /// The look needs a graph. + pub needs_graph: bool, + /// Graph a new material of this type starts with. + pub graph: Option<MaterialGraph>, + /// A graph the user may switch on (the brushed bump of brushed metal); a new material does not start with it. + pub optional_graph: Option<MaterialGraph>, +} + +impl MaterialType { + /// A new material of this type. + pub fn material(&self, name: Option<&str>) -> Material { + let mut m = Material::new(name.filter(|n| !n.trim().is_empty()).unwrap_or(self.name), self.id, self.params); + m.graph = self.graph.clone().map(Box::new); + m + } + + /// JSON entry for `material.types`. + pub fn json(&self) -> Value { + json!({ + "id": self.id, + "name": self.name, + "category": self.category, + "needs_graph": self.needs_graph, + "params": serde_json::to_value(self.params).unwrap_or(Value::Null), + "shown": self.shown.iter().map(|p| { + let mut v = serde_json::to_value(p).unwrap_or(Value::Null); + v["slot"] = json!(p.slot()); + v + }).collect::<Vec<_>>(), + "graph": self.graph.as_ref().and_then(|g| serde_json::to_value(g).ok()).unwrap_or(Value::Null), + "optional_graph": self.optional_graph.as_ref().and_then(|g| serde_json::to_value(g).ok()).unwrap_or(Value::Null), + }) + } +} + +const fn f(field: &'static str, min: f32, max: f32) -> ParamSpec { + ParamSpec { field, kind: ParamKind::Float, min, max, unit: "" } +} + +const fn u(field: &'static str, min: f32, max: f32, unit: &'static str) -> ParamSpec { + ParamSpec { field, kind: ParamKind::Float, min, max, unit } +} + +const fn c(field: &'static str) -> ParamSpec { + ParamSpec { field, kind: ParamKind::Colour, min: 0.0, max: 1.0, unit: "" } +} + +const fn b(field: &'static str) -> ParamSpec { + ParamSpec { field, kind: ParamKind::Bool, min: 0.0, max: 1.0, unit: "" } +} + +const BASE: ParamSpec = c("base_color"); +const ROUGH: ParamSpec = f("specular_roughness", 0.0, 1.0); +const IOR: ParamSpec = f("specular_ior", 1.0, 4.0); +const METAL: ParamSpec = f("base_metalness", 0.0, 1.0); +const SPEC: ParamSpec = f("specular_weight", 0.0, 1.0); +const ANISO: ParamSpec = f("specular_roughness_anisotropy", 0.0, 1.0); +const EDGE: ParamSpec = c("specular_color"); +const DIFF_ROUGH: ParamSpec = f("base_diffuse_roughness", 0.0, 1.0); +const TRANS: ParamSpec = f("transmission_weight", 0.0, 1.0); +const TRANS_COL: ParamSpec = c("transmission_color"); +const TRANS_DEPTH: ParamSpec = u("transmission_depth", 0.0, 1.0, "m"); +const ABBE: ParamSpec = f("transmission_dispersion_abbe_number", 1.0, 200.0); +const DISPERSION: ParamSpec = f("transmission_dispersion_scale", 0.0, 1.0); +const COAT: ParamSpec = f("coat_weight", 0.0, 1.0); +const COAT_ROUGH: ParamSpec = f("coat_roughness", 0.0, 1.0); +const COAT_COL: ParamSpec = c("coat_color"); +const COAT_IOR: ParamSpec = f("coat_ior", 1.0, 3.0); +const FUZZ: ParamSpec = f("fuzz_weight", 0.0, 1.0); +const FUZZ_COL: ParamSpec = c("fuzz_color"); +const FUZZ_ROUGH: ParamSpec = f("fuzz_roughness", 0.0, 1.0); +const LUM: ParamSpec = u("emission_luminance", 0.0, 10000.0, "nits"); +const EMIT_COL: ParamSpec = c("emission_color"); +const OPACITY: ParamSpec = f("geometry_opacity", 0.0, 1.0); +const THIN: ParamSpec = b("geometry_thin_walled"); +const SSS: ParamSpec = f("subsurface_weight", 0.0, 1.0); +const SSS_COL: ParamSpec = c("subsurface_color"); +const SSS_RADIUS: ParamSpec = u("subsurface_radius", 0.0, 0.1, "m"); +const FILM: ParamSpec = f("thin_film_weight", 0.0, 1.0); +const FILM_THICK: ParamSpec = u("thin_film_thickness", 0.0, 2.0, "um"); +const FILM_IOR: ParamSpec = f("thin_film_ior", 1.0, 3.0); + +static GENERIC: &[ParamSpec] = &[ + BASE, METAL, DIFF_ROUGH, SPEC, EDGE, ROUGH, IOR, ANISO, TRANS, TRANS_COL, TRANS_DEPTH, SSS, SSS_COL, SSS_RADIUS, COAT, + COAT_COL, COAT_ROUGH, COAT_IOR, FUZZ, FUZZ_COL, FUZZ_ROUGH, FILM, FILM_THICK, FILM_IOR, LUM, EMIT_COL, OPACITY, THIN, +]; +static PLASTIC: &[ParamSpec] = &[BASE, ROUGH, IOR, SPEC, COAT, COAT_ROUGH, OPACITY]; +static CLEAR: &[ParamSpec] = &[TRANS_COL, TRANS_DEPTH, ROUGH, IOR, BASE, THIN, OPACITY]; +static METAL_PAGE: &[ParamSpec] = &[BASE, EDGE, ROUGH, ANISO, COAT, COAT_ROUGH]; +static PAINT: &[ParamSpec] = &[BASE, ROUGH, COAT, COAT_COL, COAT_ROUGH, COAT_IOR]; +static PAINT_METAL: &[ParamSpec] = &[BASE, METAL, ROUGH, EDGE, COAT, COAT_COL, COAT_ROUGH, COAT_IOR]; +static GLASS: &[ParamSpec] = &[TRANS_COL, TRANS_DEPTH, ROUGH, IOR, DISPERSION, ABBE, THIN]; +static GEM: &[ParamSpec] = &[TRANS_COL, TRANS_DEPTH, ROUGH, IOR, DISPERSION, ABBE]; +static RUBBER: &[ParamSpec] = &[BASE, ROUGH, DIFF_ROUGH, SPEC, IOR]; +static FABRIC: &[ParamSpec] = &[BASE, DIFF_ROUGH, FUZZ, FUZZ_COL, FUZZ_ROUGH, SPEC, ROUGH]; +static CERAMIC: &[ParamSpec] = &[BASE, ROUGH, COAT, COAT_ROUGH, COAT_IOR]; +static DIFFUSE: &[ParamSpec] = &[BASE, DIFF_ROUGH]; +static EMISSIVE: &[ParamSpec] = &[EMIT_COL, LUM, BASE, OPACITY]; +static TEXTURED: &[ParamSpec] = &[BASE, ROUGH, DIFF_ROUGH, SPEC, COAT, COAT_ROUGH]; + +/// Measured metal colours: id, English name, normal-incidence reflectance in linear sRGB (Real-Time Rendering +/// 4th edition, table 9.2). +pub static METALS: &[(&str, &str, [f32; 3])] = &[ + ("iron", "Iron", [0.560, 0.570, 0.580]), + ("silver", "Silver", [0.972, 0.960, 0.915]), + ("aluminium", "Aluminium", [0.913, 0.921, 0.925]), + ("gold", "Gold", [1.000, 0.766, 0.336]), + ("copper", "Copper", [0.955, 0.637, 0.538]), + ("chromium", "Chromium", [0.550, 0.556, 0.554]), + ("nickel", "Nickel", [0.660, 0.609, 0.526]), + ("titanium", "Titanium", [0.542, 0.497, 0.449]), + ("cobalt", "Cobalt", [0.662, 0.655, 0.634]), + ("platinum", "Platinum", [0.672, 0.637, 0.585]), +]; + +/// A measured metal's base colour in ACEScg (clamped to 0..1). +pub fn metal_colour(id: &str) -> Option<Rgb> { + METALS.iter().find(|m| m.0 == id).map(|m| lin(m.2)) +} + +fn lin(c: [f32; 3]) -> Rgb { + Rgb::from_linear_srgb(c).clamp(0.0, 1.0) +} + +fn flakes_graph() -> MaterialGraph { + let mut g = MaterialGraph::new(); + let flakes = g.add( + GraphNode::new(GraphOp::Flakes { seed: 0 }) + .with("scale", SocketValue::Float(2000.0)) + .with("density", SocketValue::Float(0.5)) + .with("spread", SocketValue::Float(0.25)), + ); + let rough = g.add( + GraphNode::new(GraphOp::Math { op: MathOp::Lerp }) + .with("a", SocketValue::Float(0.35)) + .with("b", SocketValue::Float(0.12)), + ); + let metal = g.add( + GraphNode::new(GraphOp::Math { op: MathOp::Lerp }) + .with("a", SocketValue::Float(0.5)) + .with("b", SocketValue::Float(0.9)), + ); + g.link(flakes, "mask", rough, "c"); + g.link(flakes, "mask", metal, "c"); + g.output(MaterialInput::SpecularRoughness, rough, "value"); + g.output(MaterialInput::BaseMetalness, metal, "value"); + let tint = g.add(GraphNode::new(GraphOp::Mix {}).with("a", col([0.08, 0.15, 0.45])).with("b", col([0.16, 0.27, 0.62]))); + g.link(flakes, "mask", tint, "factor"); + g.output(MaterialInput::BaseColor, tint, "result"); + let bent = g.add(GraphNode::new(GraphOp::NormalMap { flip_y: false }).with("strength", SocketValue::Float(1.0))); + g.link(flakes, "colour", bent, "colour"); + g.output(MaterialInput::Normal, bent, "normal"); + g.nodes.entry(rough).and_modify(|n| n.position = [240.0, -60.0]); + g.nodes.entry(metal).and_modify(|n| n.position = [240.0, 60.0]); + g.nodes.entry(tint).and_modify(|n| n.position = [240.0, 180.0]); + g.nodes.entry(bent).and_modify(|n| n.position = [240.0, 300.0]); + g +} + +fn col(c: [f32; 3]) -> SocketValue { + let r = lin(c); + SocketValue::Colour([r.r, r.g, r.b]) +} + +fn pattern_graph(node: GraphNode) -> MaterialGraph { + let mut g = MaterialGraph::new(); + let n = g.add(node); + g.output(MaterialInput::BaseColor, n, "colour"); + g +} + +fn wood_graph() -> MaterialGraph { + pattern_graph( + GraphNode::new(GraphOp::Wood { seed: 0 }) + .with("scale", SocketValue::Float(1.0)) + .with("rings", SocketValue::Float(250.0)) + .with("distortion", SocketValue::Float(1.5)) + .with("colour1", col([0.48, 0.30, 0.15])) + .with("colour2", col([0.20, 0.10, 0.04])), + ) +} + +fn brushed_graph() -> MaterialGraph { + let mut g = MaterialGraph::new(); + let lines = g.add( + GraphNode::new(GraphOp::Brushed { seed: 0 }) + .with("scale", SocketValue::Float(1000.0)) + .with("length", SocketValue::Float(0.02)) + .with("strength", SocketValue::Float(1.0)), + ); + let bump = g.add(GraphNode::new(GraphOp::Bump {}).with("strength", SocketValue::Float(3.0e-5))); + g.link(lines, "value", bump, "height"); + g.output(MaterialInput::Normal, bump, "normal"); + g.nodes.entry(bump).and_modify(|n| n.position = [240.0, 0.0]); + g +} + +fn marble_graph() -> MaterialGraph { + pattern_graph( + GraphNode::new(GraphOp::Marble { seed: 0 }) + .with("scale", SocketValue::Float(1.0)) + .with("veins", SocketValue::Float(8.0)) + .with("distortion", SocketValue::Float(1.0)) + .with("colour1", col([0.80, 0.79, 0.76])) + .with("colour2", col([0.22, 0.22, 0.24])), + ) +} + +fn build() -> Vec<MaterialType> { + let d = SurfaceParams::default; + let metal = SurfaceParams { + base_metalness: 1.0, + base_color: lin(METALS[2].2), + specular_roughness: 0.2, + ..d() + }; + let glass = SurfaceParams { + base_color: Rgb::WHITE, + transmission_weight: 1.0, + specular_roughness: 0.0, + specular_ior: 1.52, + ..d() + }; + let t = |id, name, category, params, shown, graph: Option<MaterialGraph>| MaterialType { + id, + name, + category, + params, + shown, + needs_graph: graph.is_some(), + graph, + optional_graph: None, + }; + vec![ + t("generic", "Generic", "Generic", d(), GENERIC, None), + t( + "plastic", + "Plastic", + "Plastic", + SurfaceParams { base_color: lin([0.6, 0.6, 0.6]), specular_roughness: 0.3, specular_ior: 1.49, ..d() }, + PLASTIC, + None, + ), + t( + "plastic_clear", + "Clear plastic", + "Plastic", + SurfaceParams { specular_roughness: 0.02, specular_ior: 1.49, ..glass }, + CLEAR, + None, + ), + t("metal", "Metal", "Metal", metal, METAL_PAGE, None), + MaterialType { + optional_graph: Some(brushed_graph()), + ..t( + "metal_brushed", + "Brushed metal", + "Metal", + SurfaceParams { specular_roughness: 0.3, specular_roughness_anisotropy: 0.7, ..metal }, + METAL_PAGE, + None, + ) + }, + t( + "paint", + "Paint", + "Paint", + SurfaceParams { + base_color: lin([0.5, 0.03, 0.03]), + specular_roughness: 0.4, + coat_weight: 1.0, + coat_roughness: 0.03, + coat_ior: 1.5, + ..d() + }, + PAINT, + None, + ), + t( + "paint_metallic", + "Metallic paint", + "Paint", + SurfaceParams { + base_color: lin([0.08, 0.15, 0.45]), + base_metalness: 0.6, + specular_roughness: 0.35, + coat_weight: 1.0, + coat_roughness: 0.02, + coat_ior: 1.5, + ..d() + }, + PAINT_METAL, + Some(flakes_graph()), + ), + t("glass", "Glass", "Glass", glass, GLASS, None), + t("glass_thin", "Thin glass", "Glass", SurfaceParams { geometry_thin_walled: true, ..glass }, GLASS, None), + t("liquid", "Liquid", "Liquid", SurfaceParams { specular_ior: 1.333, ..glass }, GLASS, None), + t( + "gem", + "Gem", + "Gem", + SurfaceParams { + specular_ior: 2.417, + transmission_dispersion_scale: 1.0, + transmission_dispersion_abbe_number: 55.0, + ..glass + }, + GEM, + None, + ), + t( + "rubber", + "Rubber", + "Rubber", + SurfaceParams { + base_color: lin([0.04, 0.04, 0.04]), + specular_roughness: 0.6, + specular_ior: 1.52, + base_diffuse_roughness: 0.5, + ..d() + }, + RUBBER, + None, + ), + t( + "fabric", + "Fabric", + "Fabric", + SurfaceParams { + base_color: lin([0.3, 0.3, 0.35]), + specular_weight: 0.25, + specular_roughness: 0.8, + base_diffuse_roughness: 1.0, + fuzz_weight: 1.0, + fuzz_roughness: 0.5, + ..d() + }, + FABRIC, + None, + ), + t( + "ceramic", + "Ceramic", + "Ceramic", + SurfaceParams { + base_color: lin([0.8, 0.8, 0.8]), + specular_roughness: 0.4, + coat_weight: 1.0, + coat_roughness: 0.05, + coat_ior: 1.5, + ..d() + }, + CERAMIC, + None, + ), + t("diffuse", "Diffuse", "Generic", SurfaceParams { specular_weight: 0.0, base_diffuse_roughness: 0.5, ..d() }, DIFFUSE, None), + t( + "emissive", + "Emissive", + "Emissive", + SurfaceParams { base_color: Rgb::BLACK, emission_luminance: 500.0, emission_color: Rgb::WHITE, ..d() }, + EMISSIVE, + None, + ), + t( + "wood", + "Wood", + "Wood", + SurfaceParams { specular_roughness: 0.45, base_diffuse_roughness: 0.3, ..d() }, + TEXTURED, + Some(wood_graph()), + ), + t( + "stone", + "Stone", + "Stone", + SurfaceParams { specular_roughness: 0.5, base_diffuse_roughness: 0.5, ..d() }, + TEXTURED, + Some(marble_graph()), + ), + ] +} + +/// Every material type, in catalogue order. +pub fn material_types() -> &'static [MaterialType] { + static TYPES: OnceLock<Vec<MaterialType>> = OnceLock::new(); + TYPES.get_or_init(build) +} + +/// A material type by id. +pub fn material_type(id: &str) -> Option<&'static MaterialType> { + material_types().iter().find(|t| t.id == id) +} + +/// The registry as JSON: `{types, metals}`. +pub fn types_json() -> Value { + json!({ + "types": material_types().iter().map(MaterialType::json).collect::<Vec<_>>(), + "metals": METALS.iter().map(|(id, name, _)| { + let c = metal_colour(id).unwrap_or(Rgb::WHITE); + json!({"id": id, "name": name, "base_color": [c.r, c.g, c.b]}) + }).collect::<Vec<_>>(), + }) +} diff --git a/native/crates/fsh-wasm/Cargo.toml b/native/crates/fsh-wasm/Cargo.toml index 8567cbd8..e053eab3 100644 --- a/native/crates/fsh-wasm/Cargo.toml +++ b/native/crates/fsh-wasm/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fsh-wasm" -version = "0.4.0" +version = "0.6.0" edition = "2021" license = "Apache-2.0" publish = false diff --git a/native/crates/fsh-wasm/src/lib.rs b/native/crates/fsh-wasm/src/lib.rs index 077b822e..929403fb 100644 --- a/native/crates/fsh-wasm/src/lib.rs +++ b/native/crates/fsh-wasm/src/lib.rs @@ -5,12 +5,13 @@ mod mirror; #[cfg(target_arch = "wasm32")] mod present; mod session; +mod textures; #[cfg(target_arch = "wasm32")] mod tracer; #[cfg(target_arch = "wasm32")] mod viewport; -pub use session::{Scene, Session}; +pub use session::{decode_texture, Scene, Session}; #[cfg(target_arch = "wasm32")] pub use viewport::{create_viewport, scene_refusals, GpuViewport}; use wasm_bindgen::prelude::*; diff --git a/native/crates/fsh-wasm/src/session.rs b/native/crates/fsh-wasm/src/session.rs index 2679ca37..4533952d 100644 --- a/native/crates/fsh-wasm/src/session.rs +++ b/native/crates/fsh-wasm/src/session.rs @@ -1,11 +1,14 @@ +use std::collections::BTreeMap; use std::sync::Arc; +use fsh_commands::textures::{environment_image, EnvImage}; use fsh_commands::{Engine, EngineOptions}; -use fsh_scene::{Editor, RenderSnapshot}; +use fsh_scene::{Editor, EnvironmentSource, RenderSnapshot}; use serde_json::{json, Value}; use wasm_bindgen::prelude::*; use crate::mirror::Mirror; +use crate::textures::{self, Ident, SceneTextures, TextureStore, EMBED_SCHEME}; fn err(e: impl std::fmt::Display) -> JsError { JsError::new(&e.to_string()) @@ -23,6 +26,8 @@ fn parse(text: &str) -> Result<Value, JsError> { pub struct Scene { pub(crate) snapshot: Arc<RenderSnapshot>, pub(crate) revision: u64, + pub(crate) textures: SceneTextures, + pub(crate) environment: Option<(String, Arc<EnvImage>)>, } #[wasm_bindgen] @@ -37,9 +42,25 @@ impl Scene { vec![self.snapshot.render.width, self.snapshot.render.height] } - /// Instance and triangle counts as JSON. + /// Instance, triangle, material program and texture counts as JSON. pub fn counts(&self) -> String { - json!({"instances": self.snapshot.instances.len(), "meshes": self.snapshot.meshes.len(), "triangles": self.snapshot.triangle_count(), "lights": self.snapshot.lights.len()}).to_string() + let s = &self.snapshot; + let programs: Vec<&fsh_scene::RenderMaterial> = s.materials.iter().filter(|m| !m.program.is_constant()).collect(); + let words: usize = programs.iter().map(|m| m.program.encode().len()).sum(); + json!({ + "instances": s.instances.len(), + "meshes": s.meshes.len(), + "triangles": s.triangle_count(), + "lights": s.lights.len(), + "materials": s.materials.len(), + "programs": programs.len(), + "program_words": words, + "program_textures": programs.iter().map(|m| m.program.textures.len()).sum::<usize>(), + "textures": s.textures.len(), + "textures_ready": self.textures.set.images.iter().filter(|i| i.is_some()).count(), + "environment_image": self.environment.as_ref().map(|(p, i)| json!({"path": p, "width": i.width, "height": i.height})), + }) + .to_string() } } @@ -49,6 +70,43 @@ pub struct Session { engine: Engine, mirror: Mirror, revision: u64, + embedded: BTreeMap<String, Vec<u8>>, + store: TextureStore, + environment: Option<(String, Arc<EnvImage>)>, +} + +impl Session { + /// Decodes the environment image the loaded project embeds (`fshot:` HDRI path), keeping the decoded one while + /// the path stays the same; images outside the project are not read in the window. + fn keep_environment(&mut self) { + let path = match &self.engine.document().environment().source { + EnvironmentSource::Hdri { path } if path.starts_with(EMBED_SCHEME) => path.clone(), + _ => { + self.environment = None; + return; + } + }; + if self.environment.as_ref().is_some_and(|(p, _)| *p == path) { + return; + } + let member = &path[EMBED_SCHEME.len()..]; + self.environment = self.embedded.get(member).and_then(|b| environment_image(&path, b).ok()).map(|img| (path, Arc::new(img))); + } + + fn snapshot(&self) -> Arc<RenderSnapshot> { + Editor::new(self.engine.document()).snapshot() + } + + fn keep_pending_members(&mut self) { + let snap = self.snapshot(); + let pending: Vec<String> = snap + .textures + .iter() + .filter(|t| !self.store.settled(&Ident::of(t))) + .filter_map(|t| t.path.strip_prefix(EMBED_SCHEME).map(str::to_owned)) + .collect(); + self.embedded.retain(|m, _| pending.contains(m)); + } } #[wasm_bindgen] @@ -57,7 +115,14 @@ impl Session { #[wasm_bindgen(constructor)] pub fn new() -> Session { crate::install_clock(); - Session { engine: Engine::with_options(EngineOptions { threaded: false, threads: 1 }), mirror: Mirror::default(), revision: 1 } + Session { + engine: Engine::with_options(EngineOptions { threaded: false, threads: 1 }), + mirror: Mirror::default(), + revision: 1, + embedded: BTreeMap::new(), + store: TextureStore::default(), + environment: None, + } } /// Runs a catalogue command; returns the JSON reply or throws the engine's message. @@ -79,6 +144,9 @@ impl Session { let (project, report) = fsh_format::load_bytes(bytes).map_err(err)?; let title = project.document.info().name.clone(); self.engine.set_document(project.document, None); + self.embedded = project.textures; + self.keep_environment(); + self.keep_pending_members(); self.revision += 1; Ok(json!({"ok": true, "title": title, "format_version": report.version.to_string(), "warnings": report.warnings, "migrations": report.migrations}).to_string()) } @@ -96,6 +164,7 @@ impl Session { let mut ed = Editor::new(doc); ed.execute(cmd).map_err(err)?; self.engine.set_document(ed.into_document(), None); + self.embedded.clear(); let framed = self.engine.dispatch("view.frame", "{}").is_ok(); self.revision += 1; Ok(json!({"ok": true, "title": stem, "format": format.extension(), "framed": framed, "warnings": report.warnings}).to_string()) @@ -125,14 +194,76 @@ impl Session { self.mirror.forget_except(&keep); let (doc, notes) = self.mirror.build(&listing, &summary).map_err(err)?; self.engine.set_document(doc, None); + self.embedded.clear(); self.revision += 1; Ok(json!({"ok": true, "notes": notes}).to_string()) } - /// The current render view of the document. + /// The current render view of the document, with every texture decoded so far (missing ones sample their + /// fallback). pub fn scene(&self) -> Scene { - Scene { snapshot: Editor::new(self.engine.document()).snapshot(), revision: self.revision } + let snapshot = self.snapshot(); + let textures = self.store.scene_textures(&snapshot); + Scene { snapshot, revision: self.revision, textures, environment: self.environment.clone() } + } + + /// The textures the current document samples, each `{index, key, path, colour_space, mipmaps, embedded, held, + /// state: ready|failed|pending, reason, size}`, plus `bytes` of decoded texels held; releases decoded images the + /// document no longer names (`released`). + pub fn textures(&mut self) -> String { + let snap = self.snapshot(); + let released = self.store.retain_for(&snap); + let mut v = self.store.listing(&snap, &self.embedded); + v["released"] = json!(released); + v.to_string() } + + /// Takes the bytes of an embedded texture (`fshot:textures/...`) out of the loaded project, for decoding; the + /// session keeps no copy. + pub fn take_embedded(&mut self, path: &str) -> Result<Vec<u8>, JsError> { + let member = path.strip_prefix(EMBED_SCHEME).ok_or_else(|| err(format!("{path} is not an embedded texture")))?; + self.embedded.remove(member).ok_or_else(|| err(format!("the project holds no texture member {member}"))) + } + + /// Stores an image decoded elsewhere (the form `decode_texture` returns) for `(path, colour_space, mipmaps)`. + pub fn put_texture(&mut self, path: &str, colour_space: &str, mipmaps: bool, packed: &[u8]) -> Result<(), JsError> { + let id = Ident::new(path, colour_space, mipmaps).map_err(err)?; + let image = textures::unpack(packed, id.colour_space).map_err(err)?; + self.store.put(id, image); + Ok(()) + } + + /// Records that a texture could not be read or decoded; it samples its fallback until it is put again. + pub fn fail_texture(&mut self, path: &str, colour_space: &str, mipmaps: bool, reason: &str) -> Result<(), JsError> { + let id = Ident::new(path, colour_space, mipmaps).map_err(err)?; + self.store.fail(id, reason.to_string()); + Ok(()) + } + + /// Decodes an image file in this session (when no decoding worker is available); a failure is recorded like + /// `fail_texture` and returned as the reason, success returns null. + pub fn decode_texture(&mut self, path: &str, colour_space: &str, mipmaps: bool, bytes: &[u8]) -> Result<Option<String>, JsError> { + let id = Ident::new(path, colour_space, mipmaps).map_err(err)?; + match textures::decode(bytes, path, id.colour_space, mipmaps) { + Ok(image) => { + self.store.put(id, image); + Ok(None) + } + Err(reason) => { + self.store.fail(id, reason.clone()); + Ok(Some(reason)) + } + } + } +} + +/// Decodes an image file (PNG, Radiance HDR; JPEG and OpenEXR once the engine reads them) into the flat form +/// `Session.put_texture` takes, with the mip pyramid when `mipmaps`. Used by the decoding worker. +#[wasm_bindgen] +pub fn decode_texture(bytes: &[u8], path: &str, colour_space: &str, mipmaps: bool) -> Result<Vec<u8>, JsError> { + let id = Ident::new(path, colour_space, mipmaps).map_err(err)?; + let image = textures::decode(bytes, path, id.colour_space, mipmaps).map_err(err)?; + Ok(textures::pack(&image)) } impl Default for Session { diff --git a/native/crates/fsh-wasm/src/textures.rs b/native/crates/fsh-wasm/src/textures.rs new file mode 100644 index 00000000..30fcd58b --- /dev/null +++ b/native/crates/fsh-wasm/src/textures.rs @@ -0,0 +1,222 @@ +use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; + +use fsh_scene::fsh_materials::{ColourSpace, Texels, TextureImage, TextureLevel, TextureSet}; +use fsh_scene::{RenderSnapshot, RenderTexture}; +use serde_json::{json, Value}; + +pub const EMBED_SCHEME: &str = "fshot:"; +const PACK_MAGIC: u32 = 0x5854_5346; +const PACK_VERSION: u32 = 1; +const STORAGE_RGBA8: u32 = 0; +const STORAGE_F32: u32 = 1; +const MAX_SIDE: u32 = 16384; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Ident { + pub path: String, + pub colour_space: ColourSpace, + pub mipmaps: bool, +} + +impl Ident { + pub fn of(t: &RenderTexture) -> Self { + Self { path: t.path.clone(), colour_space: t.colour_space, mipmaps: t.mipmaps } + } + + pub fn new(path: &str, colour_space: &str, mipmaps: bool) -> Result<Self, String> { + let cs = ColourSpace::parse(colour_space).ok_or_else(|| format!("{colour_space:?} is not a colour space"))?; + Ok(Self { path: path.to_string(), colour_space: cs, mipmaps }) + } +} + +enum Entry { + Ready { image: Arc<TextureImage>, generation: u64 }, + Failed(String), +} + +/// Decoded images of the window session by (path, colour space, mipmaps), shared by `Arc` with the renderer. +#[derive(Default)] +pub struct TextureStore { + entries: HashMap<Ident, Entry>, + generation: u64, +} + +/// What a scene hands the viewport: the set in snapshot order and a tag that changes whenever any image does. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SceneTextures { + pub set: TextureSet, + pub tag: Vec<(Ident, u64)>, +} + +impl TextureStore { + pub fn put(&mut self, id: Ident, image: TextureImage) { + self.generation += 1; + self.entries.insert(id, Entry::Ready { image: Arc::new(image), generation: self.generation }); + } + + pub fn fail(&mut self, id: Ident, reason: String) { + self.entries.insert(id, Entry::Failed(reason)); + } + + pub fn settled(&self, id: &Ident) -> bool { + self.entries.contains_key(id) + } + + /// Releases every image the snapshot no longer names. + pub fn retain_for(&mut self, snap: &RenderSnapshot) -> usize { + let before = self.entries.len(); + let wanted: Vec<Ident> = snap.textures.iter().map(Ident::of).collect(); + self.entries.retain(|id, _| wanted.contains(id)); + before - self.entries.len() + } + + pub fn scene_textures(&self, snap: &RenderSnapshot) -> SceneTextures { + let mut out = SceneTextures::default(); + for t in &snap.textures { + let id = Ident::of(t); + match self.entries.get(&id) { + Some(Entry::Ready { image, generation }) => { + out.set.images.push(Some(image.clone())); + out.tag.push((id, *generation)); + } + _ => { + out.set.images.push(None); + out.tag.push((id, 0)); + } + } + } + out + } + + pub fn bytes(&self) -> usize { + self.entries + .values() + .map(|e| match e { + Entry::Ready { image, .. } => image.levels.iter().map(|l| texel_bytes(&l.texels)).sum(), + Entry::Failed(_) => 0, + }) + .sum() + } + + /// The snapshot's textures with their state: ready, failed (with the reason), or pending. + pub fn listing(&self, snap: &RenderSnapshot, embedded: &BTreeMap<String, Vec<u8>>) -> Value { + let list: Vec<Value> = snap + .textures + .iter() + .enumerate() + .map(|(i, t)| { + let id = Ident::of(t); + let (state, reason, size) = match self.entries.get(&id) { + Some(Entry::Ready { image, .. }) => ("ready", Value::Null, image.levels.first().map_or(json!(null), |l| json!([l.width, l.height]))), + Some(Entry::Failed(r)) => ("failed", json!(r), Value::Null), + None => ("pending", Value::Null, Value::Null), + }; + let member = t.path.strip_prefix(EMBED_SCHEME); + json!({ + "index": i, + "key": t.key.raw(), + "path": t.path, + "colour_space": t.colour_space, + "mipmaps": t.mipmaps, + "embedded": member.is_some(), + "held": member.is_some_and(|m| embedded.contains_key(m)), + "state": state, + "reason": reason, + "size": size, + }) + }) + .collect(); + json!({"textures": list, "bytes": self.bytes()}) + } +} + +fn texel_bytes(t: &Texels) -> usize { + match t { + Texels::Rgba8(v) => v.len(), + Texels::RgbaF32(v) => v.len() * 4, + } +} + +/// Decodes an image file into the renderer's texture form (level 0 and, when wanted, the mip pyramid). The one place +/// the window decodes pictures. +pub fn decode(bytes: &[u8], path: &str, cs: ColourSpace, mipmaps: bool) -> Result<TextureImage, String> { + let img = fsh_io::decode_image(path, bytes).map_err(|e| e.to_string())?; + let (w, h) = (img.width, img.height); + if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { + return Err(format!("the picture is {w} x {h} pixels; textures may be 1 to {MAX_SIDE} pixels a side")); + } + match img.pixels { + fsh_io::ImagePixels::Rgba8(v) => TextureImage::from_rgba8(w, h, v, cs, mipmaps), + fsh_io::ImagePixels::Rgba16(v) => TextureImage::from_rgba16(w, h, &v, cs, mipmaps), + fsh_io::ImagePixels::RgbaF32(v) => TextureImage::from_rgba_f32(w, h, v, cs, mipmaps), + } + .ok_or_else(|| format!("the picture is {w} x {h} pixels, which a texture cannot hold")) +} + +/// Flat little-endian form of a decoded image, for handing it from a decoding worker to the window session. +pub fn pack(image: &TextureImage) -> Vec<u8> { + let storage = match image.levels.first().map(|l| &l.texels) { + Some(Texels::RgbaF32(_)) => STORAGE_F32, + _ => STORAGE_RGBA8, + }; + let body: usize = image.levels.iter().map(|l| texel_bytes(&l.texels)).sum(); + let mut out = Vec::with_capacity(20 + image.levels.len() * 8 + body); + for w in [PACK_MAGIC, PACK_VERSION, image.colour_space.code(), storage, image.levels.len() as u32] { + out.extend_from_slice(&w.to_le_bytes()); + } + for l in &image.levels { + out.extend_from_slice(&l.width.to_le_bytes()); + out.extend_from_slice(&l.height.to_le_bytes()); + } + for l in &image.levels { + match &l.texels { + Texels::Rgba8(v) => out.extend_from_slice(v), + Texels::RgbaF32(v) => v.iter().for_each(|f| out.extend_from_slice(&f.to_le_bytes())), + } + } + out +} + +fn word(b: &[u8], i: usize) -> Option<u32> { + b.get(i * 4..i * 4 + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} + +/// Reads the form `pack` writes; checks every size against the bytes. +pub fn unpack(b: &[u8], cs: ColourSpace) -> Result<TextureImage, String> { + let bad = || "the decoded texture is damaged".to_string(); + if word(b, 0) != Some(PACK_MAGIC) || word(b, 1) != Some(PACK_VERSION) { + return Err(bad()); + } + if word(b, 2) != Some(cs.code()) { + return Err("the decoded texture has another colour space".into()); + } + let storage = word(b, 3).ok_or_else(bad)?; + let count = word(b, 4).ok_or_else(bad)? as usize; + if count == 0 || count > 32 || storage > STORAGE_F32 { + return Err(bad()); + } + let mut at = 20 + count * 8; + let mut levels = Vec::with_capacity(count); + for i in 0..count { + let (w, h) = (word(b, 5 + i * 2).ok_or_else(bad)?, word(b, 6 + i * 2).ok_or_else(bad)?); + if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { + return Err(bad()); + } + let n = (w * h * 4) as usize; + let texels = if storage == STORAGE_RGBA8 { + let s = b.get(at..at + n).ok_or_else(bad)?; + at += n; + Texels::Rgba8(s.to_vec()) + } else { + let s = b.get(at..at + n * 4).ok_or_else(bad)?; + at += n * 4; + Texels::RgbaF32(s.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()) + }; + levels.push(TextureLevel { width: w, height: h, texels }); + } + if at != b.len() { + return Err(bad()); + } + Ok(TextureImage { colour_space: cs, levels }) +} diff --git a/native/crates/fsh-wasm/src/tracer.rs b/native/crates/fsh-wasm/src/tracer.rs index f2ca6682..b042f7c1 100644 --- a/native/crates/fsh-wasm/src/tracer.rs +++ b/native/crates/fsh-wasm/src/tracer.rs @@ -2,12 +2,14 @@ use std::sync::atomic::AtomicBool; use std::sync::Arc; use fsh_render_gpu::{Accumulator, Changes, GpuContext, GpuRenderer, Refusals, RendererOptions, Result}; +use fsh_scene::fsh_materials::TextureSet; use fsh_scene::{RenderCamera, RenderSnapshot}; pub struct Tracer { r: GpuRenderer, width: u32, height: u32, + textures: Option<TextureSet>, } fn sized(snapshot: &RenderSnapshot, width: u32, height: u32) -> Arc<RenderSnapshot> { @@ -20,7 +22,21 @@ fn sized(snapshot: &RenderSnapshot, width: u32, height: u32) -> Arc<RenderSnapsh impl Tracer { pub async fn new(ctx: Arc<GpuContext>, snapshot: &RenderSnapshot, width: u32, height: u32) -> Result<Self> { let r = GpuRenderer::with_context(ctx, sized(snapshot, width, height), RendererOptions::default()).await?; - Ok(Self { r, width, height }) + Ok(Self { r, width, height, textures: None }) + } + + pub fn set_textures(&mut self, set: TextureSet) -> Result<bool> { + self.textures = Some(set.clone()); + let _ = self.r.set_textures(Some(set)); + Ok(true) + } + + pub fn set_environment_image(&mut self, image: Option<fsh_render_cpu::EnvImage>) { + let _ = self.r.set_environment_image(image); + } + + pub fn textures(&self) -> Option<&TextureSet> { + self.textures.as_ref() } pub fn set_scene(&mut self, snapshot: &RenderSnapshot) -> Result<Changes> { diff --git a/native/crates/fsh-wasm/src/viewport.rs b/native/crates/fsh-wasm/src/viewport.rs index 557fd758..0c5e327a 100644 --- a/native/crates/fsh-wasm/src/viewport.rs +++ b/native/crates/fsh-wasm/src/viewport.rs @@ -12,6 +12,7 @@ use web_sys::HtmlCanvasElement; use crate::present::Present; use crate::session::Scene; +use crate::textures::Ident; use crate::tracer::Tracer; const MOVING_SCALE: f32 = 0.5; @@ -51,6 +52,9 @@ pub struct GpuViewport { passes: u64, error: Option<String>, revision: u64, + texture_tag: Vec<(Ident, u64)>, + textures_wired: bool, + environment: Option<String>, } type MapResult = std::result::Result<(), String>; @@ -145,7 +149,13 @@ pub async fn create_viewport(canvas: HtmlCanvasElement, scene: Scene, max_side: surface.configure(ctx.device(), &config); let max_side = max_side.clamp(64, 8192); let (w, h) = render_size(cw, ch, max_side, 1.0); - let tracer = Tracer::new(ctx.clone(), &scene.snapshot, w, h).await.map_err(err)?; + let mut tracer = Tracer::new(ctx.clone(), &scene.snapshot, w, h).await.map_err(err)?; + let texture_tag = scene.textures.tag.clone(); + let textures_wired = if texture_tag.is_empty() { false } else { tracer.set_textures(scene.textures.set).map_err(err)? }; + let environment = scene.environment.as_ref().map(|(p, _)| p.clone()); + if let Some((_, img)) = &scene.environment { + tracer.set_environment_image(Some((**img).clone())); + } let present = Present::new(&ctx, tracer.accum(), format, premultiply); let target = scene.snapshot.render.samples.max(1); Ok(GpuViewport { @@ -170,6 +180,9 @@ pub async fn create_viewport(canvas: HtmlCanvasElement, scene: Scene, max_side: passes: 0, error: None, revision: scene.revision, + texture_tag, + textures_wired, + environment, }) } @@ -282,11 +295,21 @@ impl GpuViewport { /// Moves to a new render view of the document (partial uploads; accumulation restarts). pub fn set_scene(&mut self, scene: Scene) -> Result<String, JsError> { + let textures = scene.textures.tag != self.texture_tag; + if textures { + self.texture_tag = scene.textures.tag; + self.textures_wired = self.tracer.set_textures(scene.textures.set).map_err(|e| self.fail(e.to_string()))?; + } + let environment = scene.environment.as_ref().map(|(p, _)| p.clone()); + if environment != self.environment { + self.tracer.set_environment_image(scene.environment.as_ref().map(|(_, img)| (**img).clone())); + self.environment = environment; + } let c = self.tracer.set_scene(&scene.snapshot).map_err(|e| self.fail(e.to_string()))?; self.target = scene.snapshot.render.samples.max(1); self.revision = scene.revision; self.needs_present = true; - Ok(json!({"frame": c.frame, "geometry": c.geometry, "instances": c.instances, "materials": c.materials, "lights": c.lights, "environment": c.environment, "bytes": c.bytes}).to_string()) + Ok(json!({"frame": c.frame, "geometry": c.geometry, "instances": c.instances, "materials": c.materials, "lights": c.lights, "environment": c.environment, "textures": textures, "bytes": c.bytes}).to_string()) } /// Takes only the camera of a render view (one uniform write; accumulation restarts). @@ -419,6 +442,9 @@ impl GpuViewport { "kernel_hash": format!("{hash:016x}"), "kernel_lines": lines, "device_bytes": self.tracer.device_bytes(), + "textures": self.tracer.textures().map_or(0, |s| s.images.len()), + "textures_ready": self.tracer.textures().map_or(0, |s| s.images.iter().filter(|i| i.is_some()).count()), + "textures_wired": self.textures_wired, "format": format!("{:?}", self.config.format), "alpha_mode": format!("{:?}", self.config.alpha_mode), "stopped": self.stopped, diff --git a/setup/HASHOUT_LOG.md b/setup/HASHOUT_LOG.md index 4023b21b..90e4a3aa 100644 --- a/setup/HASHOUT_LOG.md +++ b/setup/HASHOUT_LOG.md @@ -1,13 +1,14 @@ # setup HASHOUT_LOG -Living log for the launcher, the setup suite and the root configuration, _v0.4.0. Entries are anchored by file and symbol, and removed code is quoted in full. +Living log for the launcher, the setup suite and the root configuration, _v0.6.0. Entries are anchored by file and symbol, and removed code is quoted in full. ## Org-navi-map ```text formshot, formshot.bat launcher: boot, install, install-desktop, backend, frontend, engine build|check|wasm, render, cli, build, serve, freeze, desktop dev|build, app, mcp, i18n, agents, notices, - doctor, clean, help (unknown command exits 2 with usage) + doctor, clean, help (unknown command exits 2 with usage), cad fetch|status +setup/cad_worker fetch or show FormCAD's kernel worker: runs backend/app/routers/cad.py's CLI with the venv formshot_oc_install, .bat one-step install, the same as ./formshot install build_app, build_app.bat start-to-finish desktop build with build_app.log setup/lib.sh shared helpers: os, python 3.12+, venv, target triple, rust env scrub, pinned toolchain, @@ -60,6 +61,12 @@ Boot scripts use `backend/boot_backend` and `frontend/boot_frontend` when presen - logged: v0.2.0 · 2026-12-02 No `test`, `bench` or `script` command (no tests by rule; no bench binary; Python scripting is planned for 0.13.0 to 0.14.0). No formfabric `version.py`, no `setup/licence_texts` yet (family data; populate when the Tauri crates need vendored texts), and no worker-fetch command (no family launcher has one; the app fetches workers). +### formshot, formshot.bat, setup/cad_worker · the cad command +- refers-to: formshot :: cad; formshot.bat :: :cad; setup/cad_worker; backend/app/routers/cad.py :: main +- kind: decision +- logged: v0.6.0 · 2026-12-02 +This supersedes the "no worker-fetch command" line above for one worker: STEP and IGES need FormCAD's kernel worker, the engine never downloads, and a developer without the window needs a way to fetch it. `./formshot cad fetch|status` runs `setup/cad_worker`, which runs `python -m app.routers.cad` from `backend/` with the backend venv, or with a system Python 3.12+ that has FastAPI (else it says to run `./formshot install`). It is the same code as the service's fetch route, prints progress, and exits 1 with the reason on refusal (no worker published for this triple, a hash that does not match the pinned record). `formshot.bat` gained the `cad` dispatch, a `:cad` label running the same module with the venv Python (CRLF kept), and its usage line; `formshot help` prints the cad line. Run: `./formshot cad fetch` installed occt-8.0.1 for x86_64 Linux (7061 files, 1002 MB unpacked) into a scratch cache; riscv64 exited 1; `./formshot help` showed the line. Not run: formshot.bat, macOS and Windows; there is no `setup/cad_worker.bat` (the .bat launcher calls the module directly). + ## Engine scripts ### setup/install_engine, engine_build, engine_check, engine_wasm, engine_cli @@ -112,7 +119,7 @@ Extract writes `frontend/src/i18n/strings.json`; check reads `locales/<code>.jso - refers-to: VERSION; rust-toolchain.toml; .editorconfig; .gitattributes; .gitignore; .mcp.json - kind: rationale - logged: v0.2.0 · 2026-12-02 -`VERSION` 0.4.0. rust-toolchain.toml pins 1.99.1 with clippy, rustfmt, wasm32-unknown-unknown, profile minimal. The family's .editorconfig (plus 4-space .rs), .gitattributes and .gitignore (plus frontend/src/engine/pkg/). `.mcp.json` names the project server `formshot` as `${CLAUDE_PROJECT_DIR:-.}/formshot mcp`. +`VERSION` 0.6.0. rust-toolchain.toml pins 1.99.1 with clippy, rustfmt, wasm32-unknown-unknown, profile minimal. The family's .editorconfig (plus 4-space .rs), .gitattributes and .gitignore (plus frontend/src/engine/pkg/). `.mcp.json` names the project server `formshot` as `${CLAUDE_PROJECT_DIR:-.}/formshot mcp`. ### .github/workflows/ci.yml · checks without tests - refers-to: .github/workflows/ci.yml :: frontend, engine, backend, desktop-shell, scripts diff --git a/setup/cad_worker b/setup/cad_worker new file mode 100755 index 00000000..5f89deb3 --- /dev/null +++ b/setup/cad_worker @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -e +source "$(dirname "$0")/lib.sh" +cd "$FSH_ROOT/backend" 2>/dev/null || fsh_die "backend/ is missing" +if fsh_has_venv; then + fsh_venv + py=python +else + py="$(fsh_python)" || fsh_die "Python 3.12 or newer is required" + "$py" -c 'import fastapi, starlette' 2>/dev/null || fsh_die "backend venv missing, run ./formshot install" +fi +exec "$py" -m app.routers.cad "$@" diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 3cb541c8..c5ec7c15 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1053,7 +1053,7 @@ dependencies = [ [[package]] name = "formshot" -version = "0.4.0" +version = "0.6.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 26d86663..40160535 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formshot" -version = "0.4.0" +version = "0.6.0" description = "FormShot desktop shell" authors = ["NodeAgentc, Inc."] license = "Apache-2.0" diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md index ea25273e..adc80634 100644 --- a/src-tauri/HASHOUT_LOG.md +++ b/src-tauri/HASHOUT_LOG.md @@ -1,12 +1,12 @@ # src-tauri HASHOUT_LOG -Living log for the desktop shell and its service start, _v0.4.0. Entries are anchored by file and symbol, and removed code is quoted in full. +Living log for the desktop shell and its service start, _v0.6.0. Entries are anchored by file and symbol, and removed code is quoted in full. ## Org-navi-map ```text src-tauri/ - Cargo.toml crate formshot 0.4.0: tauri 2 (macos-private-api), shell, dialog, updater, + Cargo.toml crate formshot 0.6.0: tauri 2 (macos-private-api), shell, dialog, updater, single-instance plugins, regex, serde, serde_json; windows-sys; objc2 build.rs the eight app commands for tauri-build's allow-<command> permissions tauri.conf.json FormShot, ai.nodemode.formshot, devUrl 5300, splash window, sidecar, .fshot, updater @@ -83,6 +83,18 @@ FormSurface's start-up check (native dialog) plus FormFabric's `check_for_update - logged: v0.2.0 · 2026-12-02 An original placeholder: a dark rounded square with a light lens ring and a six-blade aperture, drawn with Pillow by a script outside the repo. `icon.icns` and `icon.ico` are Pillow's output, checked only with `file`. +### tauri.conf.json · the material library as a bundle resource +- refers-to: tauri.conf.json :: bundle.resources; native/crates/fsh-commands/src/ext/library/locate.rs; backend/app/routers/library.py :: bundled_library +- kind: decision +- logged: v0.6.0 · 2026-12-02 +`"../assets/library/materials": "library/materials"` in `bundle.resources` ships the 249 presets and their index with the app. The engine looks for them where Tauri's `resource_dir` puts resources (`../Resources/library` on macOS, beside the program on Windows, `../lib/FormShot/library`, `$APPDIR/usr/lib/FormShot/library` or `/usr/lib/FormShot/library` on Linux). In the desktop app the engine runs inside the frozen service or unpacked by PyInstaller into a temporary folder, so the service sets `FORMSHOT_LIBRARY` from `sys.executable` when frozen; the shell now also passes `FORMSHOT_LIBRARY` to the sidecar (one region in `setup` in src/main.rs, polish pass): it sets `<resource_dir>/library` only when the person has not set the variable and `<resource_dir>/library/materials/index.json` exists; the service's frozen fallback stays. Checked by `cargo check --locked` and clippy only; no bundle was built or run. Not run: no desktop bundle was built; the places were checked with hand-made folder trees only. + +### src/main.rs · hand-offs and the opened-file list +- refers-to: src/main.rs :: OPENABLE_EXTS, open_paths, take_pending_opens +- kind: decision +- logged: v0.6.0 · 2026-12-02 +No file association or URL scheme was added for the family hand-offs: FormPortal and the family apps start an app with the file path as its argument, and FormShot already queues `.fshot .glb .gltf .obj .stl .ply` launch arguments as `formshot://open-paths`, while GoF folders and FormSurface exports are watched by the service and held for consent. The window now listens to `formshot://open-paths` and drains `take_pending_opens` (frontend/src/ui/import/desktop.ts), which nothing did before. `OPENABLE_EXTS` now lists `fshot glb gltf obj stl ply 3mf fbx step stp iges igs`, so every import format given by the system reaches the window; folders still do not (the filter keeps files with those extensions), so a GoF or FormSurface folder given at launch is not routed to `handoff.inspect`. + ## Verification ### (shell) · what ran diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 59a4bf57..d15e197a 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -16,7 +16,7 @@ mod traffic_lights; #[cfg(windows)] mod win_job; -const OPENABLE_EXTS: &[&str] = &["fshot", "glb", "gltf", "obj", "stl", "ply"]; +const OPENABLE_EXTS: &[&str] = &["fshot", "glb", "gltf", "obj", "stl", "ply", "3mf", "fbx", "step", "stp", "iges", "igs"]; const EXIT_EVENT: &str = "formshot://exit-requested"; const OPEN_EVENT: &str = "formshot://open-paths"; const ENGINE_GONE: &str = "The FormShot engine stopped while the app was running, so the window can no longer save, render or export. FormShot will close now; start it again to continue from the last saved project."; @@ -480,7 +480,18 @@ fn main() { app.manage(Service(Mutex::new(None))); let launch_args: Vec<String> = std::env::args().collect(); open_paths(&handle, paths_from_args(&launch_args, None)); + let library = std::env::var_os("FORMSHOT_LIBRARY") + .filter(|v| !v.is_empty()) + .is_none() + .then(|| app.path().resource_dir().ok()) + .flatten() + .map(|dir| dir.join("library")) + .filter(|dir| dir.join("materials").join("index.json").is_file()); let started = app.shell().sidecar(engine_start::SIDECAR).map_err(|_| engine_start::Failure::Missing).and_then(|engine| { + let engine = match library { + Some(dir) => engine.env("FORMSHOT_LIBRARY", dir), + None => engine, + }; engine .env(engine_start::PORT_ENV, engine_start::PORT) .env(engine_start::SHELL_ENV, std::process::id().to_string()) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index d9c0ce7d..1ace9772 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormShot", - "version": "0.4.0", + "version": "0.6.0", "identifier": "ai.nodemode.formshot", "build": { "devUrl": "http://localhost:5300", @@ -42,7 +42,8 @@ "resources": { "../LICENSE": "LICENSE", "../NOTICE.md": "NOTICE.md", - "../THIRD-PARTY-NOTICES.txt": "THIRD-PARTY-NOTICES.txt" + "../THIRD-PARTY-NOTICES.txt": "THIRD-PARTY-NOTICES.txt", + "../assets/library/materials": "library/materials" }, "icon": ["icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico"], "macOS": {