dymokomi/luced-3d
Source of release 0.11.5
## Editor-owned geometry DAG. IDs survive history restores; meshes are immutable.
from luce_geocore.geocore import Mesh
from luce_3d.graphics import Vector3, Matrix4
from geometry_data import GeometryData
from edit_operations import EditStep
import node_catalog
from node_evaluation import source_geometry, evaluate_verb, load_geometry, SourceCache
from geometry_nodes import evaluate_set_verb, is_placement, evaluate_placement, evaluate_attributes, points_deleted
from cache_node import reads_file, cook_cache, load_frozen
from usd_nodes import is_usd_path, load_usd, cook_export
from fbx_nodes import is_fbx_path, load_fbx, export_fbx
from ply_nodes import is_ply_path, export_ply
from spz_nodes import is_spz_path, export_spz
from luce_ui import ui
from edit_kinds import edit_kind
from scene_nodes import add_camera, add_light, check_render, add_material, assign_material
from shader_nodes import is_shader, graph_kind, math_operations
from take import Take
import shader_nodes
import cad_nodes
import code_cook
import script_cook
from script_hosts import ScriptHosts
from angles import radians
pub func kinds() -> list[str]:
return node_catalog.kinds()
pub class Node:
pub let id: int
pub let kind: str
pub var name: str
pub var enabled: bool = true
pub var parent: int = -1
## 0 = automatic terminal, 1 = explicitly exposed, -1 = explicitly off.
pub var output: int = 0
pub var visible: bool = true
pub var x: float
pub var y: float
pub var inputs: list[int]
## Which output of each input's node it takes (shader nodes have several).
pub var sources: list[int]
# Size, translate XYZ, rotate XYZ in degrees, scale XYZ.
pub var values: list[float]
pub var texts: list[str]
pub var edits: list[EditStep]
## Verb nodes made from a viewport selection: the connectivity hash of the
## input the Group was selected on (0: typed, unguarded).
pub var guard: int = 0
pub var cache: GeometryData? = none
## A feature's worker-side memo (cad_nodes.BlendMemo), kept while the
## node keeps its kind.
pub var memo: cad_nodes.BlendMemo
pub var dirty: bool = true
pub var failure: str = ""
## A warning of the last cook (see GeometryData.warning).
pub var warning: str = ""
## A Code node's printf output from its last cook.
pub var console: str = ""
pub var evaluations: int = 0
pub var source_revision: int = 0
pub var computing: bool = false
pub var progress: float = 0.0
pub var phase: str = ""
pub var summary: str = ""
pub var group_paths: list[str]
## Content stamp of the recipe (stamps.luc) and of the last result reported.
pub var stamp: int = 0
pub var cooked: int = 0
## A Material's shader, resolved from its nodes before it cooks
## (Network.resolve_material): its OpenPBR Surface's values and the
## renderer's graph text.
pub var surface_values: list[float]
pub var shader_graph: str = ""
## Object paths taken out of its result (the outliner's and takes'
## visibility for objects inside it); a path hides what is under it too.
pub var hidden: list[str]
## A frozen node's result file (cache_node.freeze_to), "" when it
## cooks: frozen, it reads the file and never its inputs.
pub var frozen: str = ""
## Whether its result follows the timeline (a Code node reading the
## frame or time): its stamp then includes the frame.
pub var time_dependent: bool = false
pub func init(self, id: int, kind: str, x: float, y: float) -> unit!:
if not (kind in kinds()):
error(ui.invalid, "Unknown node type")
self.id = id
self.kind = kind
self.name = f"{kind} {id}"
self.x = x
self.y = y
self.inputs = []
self.sources = []
self.memo = cad_nodes.BlendMemo()
for port in 0..<node_catalog.input_count(kind):
self.inputs.append(-1)
self.sources.append(0)
self.surface_values = []
self.values = []
for _ in 0..<(code_cook.value_count if kind in [code_cook.kind_name, script_cook.kind_name] else node_catalog.value_slots):
self.values.append(0.0)
for parameter in node_catalog.parameters(kind):
self.values[parameter.slot] = parameter.initial
self.texts = ["0" if kind == "PolyExtrude" else "", "group" if kind == "Selection Group" else ("geo" if kind == "Export" else "weight"), "renamed"]
if kind == "Camera" or kind == "Light":
self.texts = [f"{kind.lower()}{id}", "", ""]
if kind in ["Render", "Assign Material", "Fillet", "Chamfer"]:
self.texts = ["", "", ""]
if kind == "Name":
self.texts = ["", "piece", ""]
if kind == "Material":
self.texts = [f"materials/material{id}", "", ""]
if kind == code_cook.kind_name:
self.texts = ["", code_cook.starter(), "", "", ""]
if kind == script_cook.kind_name:
self.texts = []
for _ in 0..<script_cook.text_count:
self.texts.append("")
self.texts[script_cook.code_slot] = script_cook.starter()
if kind == "File":
# USD's Variants and Load payloads, empty: the stage as authored.
self.texts = ["", "", ""]
# A verb's text rows (Volume Visualization's group, fields and ramp)
# read the texts from slot 0, all empty at first.
let rows = node_catalog.text_row_count(kind)
if rows > 0:
self.texts = []
for _ in 0..<(rows if rows > 3 else 3):
self.texts.append("")
self.edits = []
self.group_paths = []
self.hidden = []
pub func copy(self) -> Node!:
let result = Node(self.id, self.kind, self.x, self.y)
result.name = self.name
result.enabled = self.enabled
result.parent = self.parent
result.output = self.output
result.visible = self.visible
result.inputs = self.inputs.copy()
result.sources = self.sources.copy()
result.surface_values = self.surface_values.copy()
result.shader_graph = self.shader_graph
result.values = self.values.copy()
result.texts = self.texts.copy()
result.edits = self.edits.copy()
result.guard = self.guard
result.cache = self.cache
result.memo = self.memo
result.dirty = self.dirty
result.failure = self.failure
result.warning = self.warning
result.console = self.console
result.evaluations = self.evaluations
result.source_revision = self.source_revision
result.summary = self.summary
result.group_paths = self.group_paths.copy()
result.hidden = self.hidden.copy()
result.frozen = self.frozen
result.time_dependent = self.time_dependent
result.stamp = self.stamp
result.cooked = self.cooked
return result
## `result` without the objects at its hidden paths.
pub func shown(self, result: GeometryData) -> GeometryData!:
if self.hidden.length == 0:
return result
let patterns: list[str] = []
for path in self.hidden:
patterns.append("\"" + path + "\"")
let kept = result.blasted(patterns.join(" "), false)
kept.warning = result.warning
return kept
## Pure node computation over resolved immutable inputs. Runtime invokes this
## only on the compute worker; synchronous callers use the same contract.
## `keys` are the inputs' content keys (their nodes' stamps) when the caller
## knows them: a Script node keeps an unchanged input's file.
pub func compute(self, data: GeometryData, second: GeometryData? = none, progress: func(float) -> unit!? = none, sources: SourceCache? = none, clock: list[float] = [], keys: list[int] = []) -> GeometryData!:
if self.frozen != "":
return load_frozen(self.frozen)
let v = self.values
let rotation = Vector3(radians(v[4]), radians(v[5]), radians(v[6]))
let scale = Vector3(v[7], v[8], v[9])
let pivot = Vector3(v[10], v[11], v[12])
let translation = Vector3(v[1], v[2], v[3]).add(pivot).subtract(Matrix4.compose(Vector3(), rotation, scale).transform_point(pivot))
# A Group places its children as one instance, hidden with it.
if node_catalog.places_children(self.kind):
return GeometryData().with_instance(data, translation, rotation, scale, self.visible)
if node_catalog.is_set_verb(self.kind):
if not self.enabled:
return data
return evaluate_set_verb(self.kind, v, self.texts, data, second)
if cad_nodes.is_cad_only(self.kind):
if not self.enabled:
return data
return cad_nodes.evaluate_cad(self.kind, v, data, cad_nodes.tag_of(self.id), second, self.texts, self.memo)
if self.kind in node_catalog.sources():
if not self.enabled:
return GeometryData()
if self.kind == "File":
if is_usd_path(self.texts[0]):
if let cache = sources:
return cache.load_usd(self.texts[0].trim(), v, self.texts)
return load_usd(self.texts[0].trim(), v, self.texts)
if is_fbx_path(self.texts[0]):
if let cache = sources:
return cache.load_fbx(self.texts[0].trim(), v)
return load_fbx(self.texts[0].trim(), v)
if let cache = sources:
return cache.load(self.texts[0].trim(), v[0])
return load_geometry(self.texts[0].trim(), v[0])
return GeometryData(source_geometry(self.kind, v))
if not self.enabled or self.kind in ["Switch", "Null"]:
return data
if self.kind == "Camera":
return add_camera(self.id, v, self.texts, data)
if self.kind == "Light":
return add_light(self.id, v, self.texts, data)
if self.kind == "Render":
return check_render(self.texts, data)
if self.kind == "Material":
return add_material(self.id, self.surface_values, self.texts, data, self.shader_graph)
if self.kind == "Assign Material":
return assign_material(self.texts, data, second else error(ui.invalid, "Connect the materials input"))
if self.kind == code_cook.kind_name:
return code_cook.cook(self.values, self.texts, data, clock, second)
if self.kind == script_cook.kind_name:
let wired = [self.inputs[0] >= 0, self.inputs[1] >= 0]
if let cache = sources:
return script_cook.cook(self.id, self.values, self.texts, data, clock, second, wired, progress, cache.scripts, cache.folder, keys)
let hosts = ScriptHosts()
let result = script_cook.cook(self.id, self.values, self.texts, data, clock, second, wired, progress, hosts) catch failure:
hosts.close()
error(failure.code, failure.message)
hosts.close()
return result
if self.kind == "Cache":
return cook_cache(reads_file(self.kind, self.enabled, self.values), self.texts[0], self.stamp, data)
if self.kind == "Export":
if is_fbx_path(self.texts[0]) and self.texts[0].trim() != "":
return export_fbx(self.texts[0].trim(), data)
if is_ply_path(self.texts[0]):
return export_ply(self.texts[0].trim(), data)
if is_spz_path(self.texts[0]):
return export_spz(self.texts[0].trim(), data)
return cook_export(self.texts[0], self.texts[1], v, data)
if self.kind == "Blast":
# Object paths (they have a /) go by path; anything else is a
# group expression on the mesh, as Houdini's Blast takes:
# @name=wheel, 0-5, @P.y>0.
if self.texts[0].contains("/") or self.texts[0].trim() == "":
return data.blasted(self.texts[0], v[0] != 0.0)
# A point cloud without a mesh: the expression names its points.
if data.operand() == none and data.geometry.has("points"):
return points_deleted(data, self.texts[0], v[0] != 0.0)
let delete_values: list[float] = [v[0]]
for _ in 1..<node_catalog.value_slots:
delete_values.append(0.0)
return evaluate_verb("Delete", delete_values, self.texts, data.require_mesh())
if self.kind == "Tessellate":
if let cache = sources:
return cache.tessellated(data, int(v[0]), v[1], progress)
return data.tessellated(int(v[0]), v[1], progress)
if self.kind == "Transform":
return data.transformed(translation, rotation, scale)
if self.kind == "Merge":
return data.merged(second else error(ui.invalid, "Connect the second geometry input"))
if let kind = edit_kind(self.kind):
var result = kind.start(data)
for edit in self.edits:
result = kind.run(edit, result)
return result
# Mesh operators work on the mesh component; the other components
# (curves, points, volumes, SDFs, CAD beside a mesh) pass through.
if is_placement(self.kind):
return evaluate_placement(self.kind, v, data, second)
let operand = data.operand()
if self.kind == "Delete" and operand == none and data.geometry.has("points"):
return points_deleted(data, self.texts[0], v[0] != 0.0)
if node_catalog.is_mesh_verb(self.kind):
let mesh = operand else return data.passed("The input has no polygons; it passes through")
if self.guard != 0 and self.guard != mesh.topology_hash():
error(ui.invalid, "Group was selected on different topology. Reselect, or Keep IDs.")
let result = evaluate_verb(self.kind, v, self.texts, mesh)
let kept = data.with_operand(result.mesh else mesh)
kept.warning = result.warning
return kept
return evaluate_attributes(self.kind, v, self.texts, data, operand)
pub class Network:
pub var nodes: list[Node]
pub var next_id: int = 1
pub var selected: int = 1
## Nodes picked with the selected one (Shift-click, box): what Group,
## Delete and moving act on. It counts only while it holds `selected`
## (selection()), so setting `selected` alone picks just that node.
pub var picked: list[int]
pub var display: int = 1
pub var scope: int = -1
pub var preview: bool = false
pub var background: bool = false
pub var compute_mode: int = 3
## Set on worker copies while the viewport shows normals: publish guides.
pub var show_normals: bool = false
## The viewport's selection level (an Edit node's pick geometry follows it).
pub var level: int = 0
## A gizmo drag is live: its frames may show quick CAD previews.
pub var gesture: bool = false
## The viewport's CAD mesh divisions (ViewState.cad_quality).
pub var cad_quality: int = 16
## A prompt picks on a CAD body (Pick edges): its tagged tessellation is
## made to pick on; otherwise CAD bodies are not tessellated for picking.
pub var picking_cad: bool = false
## The node picked on while a tool prompt shows the tool's result (its
## input); -1: the displayed node (pick_node). Set on each rebuild.
pub var picking: int = -1
## The document's length unit ("mm" or "in"): lengths are kept in
## millimeters and shown in it (units.luc).
pub var units: str = "mm"
## The project file's folder ("" when unsaved): a Script node reads its
## relative file parameters from there (k.project()).
pub var folder: str = ""
pub var on_progress: func(int, float, str) -> unit!? = none
## Process-lifetime import caches shared by every copy of this graph.
pub var sources: SourceCache? = none
## Named states of the scene's switches (takes.luc), Main first; the
## active one's state is the nodes'.
pub var takes: list[Take]
pub var take: int = 0
## The timeline: the current frame, the range and frames per second
## (frame 1 is time 0, as in Houdini). Nodes whose result reads the
## time (Node.time_dependent) take the frame into their stamp.
pub var frame: float = 1.0
pub var start: float = 1.0
pub var end: float = 240.0
pub var fps: float = 24.0
pub func init(self, seed: bool = true) -> unit!:
self.nodes = []
self.picked = []
self.takes = [Take("Main")]
if seed:
_ = self.add("Cube", 40.0, 70.0)
pub func find(self, id: int) -> Node?:
for node in self.nodes:
if node.id == id:
return node
return none
pub func require(self, id: int) -> Node!:
return self.find(id) else error(ui.invalid, "Node no longer exists")
pub func add(self, kind: str, x: float, y: float) -> Node!:
if self.nodes.length >= 128:
error(ui.invalid, "This workspace supports up to 128 nodes")
var ancestor = self.scope
var depth = 0
while ancestor >= 0:
let group = self.require(ancestor)
if not node_catalog.holds_nodes(group.kind):
error(ui.invalid, "Only a Group, a CAD node or a Material can contain nodes")
ancestor = group.parent
depth += 1
if depth >= 16:
error(ui.invalid, "Group nesting is limited to 16 levels")
# A Material holds shader nodes, a CAD node CAD nodes, and only they do.
let context = self.context()
if not cad_nodes.allowed(kind, context, is_shader(kind)):
if context == "shading":
error(ui.invalid, "Inside a Material, only shader nodes")
if context == "cad":
error(ui.invalid, "Inside a CAD node, only CAD nodes (sketches, features, solids)")
error(ui.invalid, "Shader nodes go inside a Material" if is_shader(kind) else f"{kind} goes inside a CAD node")
let node = Node(self.next_id, kind, x, y)
node.parent = self.scope
self.next_id += 1
self.nodes.append(node)
# A new Material starts with the surface its nodes feed.
if kind == "Material":
let surface = Node(self.next_id, "OpenPBR Surface", 300.0, 60.0)
surface.parent = node.id
self.next_id += 1
self.nodes.append(surface)
if self.scope >= 0:
self.invalidate(self.scope)
return node
## The node whose geometry the viewport picks on.
pub func pick_node(self) -> int:
return self.picking if self.picking >= 0 else self.display
## The timeline's time in seconds at the current frame.
pub func time(self) -> float:
return (self.frame - 1.0) / self.fps
pub func copy(self) -> Network!:
let result = Network(false)
result.next_id = self.next_id
result.selected = self.selected
result.picked = self.picked.copy()
result.display = self.display
result.scope = self.scope
result.preview = self.preview
result.background = self.background
result.sources = self.sources
result.takes = []
for take in self.takes:
result.takes.append(take.copy())
result.take = self.take
result.units = self.units
result.folder = self.folder
result.frame = self.frame
result.start = self.start
result.end = self.end
result.fps = self.fps
for node in self.nodes:
result.nodes.append(node.copy())
return result
## The picked nodes in this scope, the selected one among them.
pub func selection(self) -> list[int]:
let primary = self.find(self.selected) else return []
if not (primary.id in self.picked):
return [primary.id]
let result: list[int] = []
for id in self.picked:
if let node = self.find(id):
if node.parent == self.scope:
result.append(id)
return result
## What the network shown holds: "shading" (a Material's shader nodes),
## "cad" (a CAD node's) or "geometry".
pub func context(self) -> str:
let scope = self.find(self.scope) else return "geometry"
if scope.kind == "Material":
return "shading"
if scope.kind == "CAD":
return "cad"
return "geometry"
## Whether the network shown is a Material's shader nodes.
pub func in_material(self) -> bool:
let scope = self.find(self.scope) else return false
return scope.kind == "Material"
## Fill a Material's shader from its nodes: the OpenPBR Surface's values
## (the defaults without one) and the renderer's graph text, one statement
## a `;`: each node, its unlinked inputs' constants and its links.
pub func resolve_material(self, material: Node) -> unit!:
let nodes = self.children(material.id)
var surface: Node? = none
for node in nodes:
if node.kind == "OpenPBR Surface" and node.enabled:
surface = node
material.surface_values = (surface else Node(0, "OpenPBR Surface", 0.0, 0.0)).values.copy()
let statements: list[str] = []
for node in nodes:
if not node.enabled:
continue
var setting = ""
if node.kind == "Math":
let operations = math_operations()
let chosen = operations[int(node.values[0])]
setting = " " + chosen.lower()
if node.kind == "Image Texture":
if node.texts[0].trim() == "":
continue
setting = " " + node.texts[0].trim() + (" data" if node.values[0] != 0.0 else "")
statements.append(f"node n{node.id} {graph_kind(node.kind)}{setting}")
let sockets = shader_nodes.inputs(node.kind)
for port in 0..<sockets.length:
let socket = sockets[port]
if let source = self.find(node.inputs[port]):
if not source.enabled or (source.kind == "Image Texture" and source.texts[0].trim() == ""):
continue
let outputs = shader_nodes.outputs(source.kind)
let output = outputs[node.sources[port]].name if node.sources[port] < outputs.length else outputs[0].name
statements.append(f"link n{node.id} {socket.name} n{source.id} {output}")
elif socket.slot >= 0 and node.kind != "OpenPBR Surface":
var line = f"input n{node.id} {socket.name}"
for k in 0..<socket.width:
line = line + f" {node.values[socket.slot + k]}"
statements.append(line)
material.shader_graph = statements.join("; ")
pub func local_nodes(self) -> list[Node]:
return self.children(self.scope)
pub func children(self, parent: int) -> list[Node]:
let result: list[Node] = []
for node in self.nodes:
if node.parent == parent:
result.append(node)
return result
## Connected components are local to a scope. Wires never imply parenting.
pub func outputs(self, parent: int) -> list[Node]:
let local = self.children(parent)
let visited: list[int] = []
let result: list[Node] = []
for seed in local:
if seed.id in visited:
continue
let island: list[Node] = []
let pending = [seed.id]
var explicit = false
while pending.length > 0:
let id = pending.pop()
if id in visited:
continue
visited.append(id)
for node in local:
if node.id == id:
island.append(node)
explicit = explicit or node.output == 1
for source in node.inputs:
if source >= 0:
pending.append(source)
elif id in node.inputs:
pending.append(node.id)
for node in island:
var terminal = true
for other in local:
if node.id in other.inputs:
terminal = false
if node.output == 1 or (not explicit and node.output == 0 and terminal):
result.append(node)
# Stable authoring order, independent of traversal and graph wiring.
let ordered: list[Node] = []
for node in local:
for exposed in result:
if exposed.id == node.id:
ordered.append(node)
return ordered
pub func is_output(self, id: int) -> bool!:
let node = self.require(id)
for exposed in self.outputs(node.parent):
if exposed.id == id:
return true
return false
pub func path(self) -> str!:
var id = self.scope
var path = ""
while id >= 0:
let node = self.require(id)
path = "/ " + node.name + " " + path
id = node.parent
return "/ scene " + path
pub func depends_on(self, source: int, ancestor: int) -> bool!:
let pending: list[int] = [source]
let visited: list[int] = []
while pending.length > 0:
let id = pending.pop()
if id == ancestor:
return true
if id < 0 or id in visited:
continue
visited.append(id)
let node = self.require(id)
for input in node.inputs:
pending.append(input)
return false
## Connect `source`'s output `output` (shader nodes have several) to
## `target`'s input `port`.
pub func connect(self, source: int, target: int, port: int, output: int = 0) -> unit!:
let upstream = self.require(source)
let node = self.require(target)
if upstream.parent != node.parent:
error(ui.invalid, "Connections must stay inside one Group; connect the Group's result instead")
if port < 0 or port >= node.inputs.length:
error(ui.invalid, "That node has no such geometry input")
if output < 0 or (is_shader(upstream.kind) and output >= shader_nodes.outputs(upstream.kind).length) or (not is_shader(upstream.kind) and output != 0):
error(ui.invalid, "That node has no such output")
if self.depends_on(source, target):
error(ui.invalid, "Connection rejected: it would create a cycle")
node.inputs[port] = source
node.sources[port] = output
self.invalidate(target)
pub func disconnect(self, target: int, port: int) -> unit!:
let node = self.require(target)
if port < 0 or port >= node.inputs.length:
error(ui.invalid, "That node has no such geometry input")
node.inputs[port] = -1
node.sources[port] = 0
self.invalidate(target)
pub func remove(self, id: int) -> unit!:
let parent = self.require(id).parent
let removed = [id]
var at = 0
while at < removed.length:
for node in self.nodes:
if node.parent == removed[at]:
removed.append(node.id)
at += 1
self.invalidate(id)
let remaining: list[Node] = []
for node in self.nodes:
if not (node.id in removed):
for port in 0..<node.inputs.length:
if node.inputs[port] in removed:
node.inputs[port] = -1
remaining.append(node)
self.nodes = remaining
if self.scope in removed:
self.scope = parent
if self.selected in removed:
let local = self.local_nodes()
self.selected = local[0].id if local.length > 0 else -1
if self.display in removed:
self.display = self.selected
if parent >= 0:
self.invalidate(parent)
## After `node`'s visibility flag changed: the Group holding it instances
## it by the flag, and a Group's own result carries it.
pub func visibility_changed(self, node: Node):
if node_catalog.places_children(node.kind):
self.invalidate(node.id)
elif node.parent >= 0:
self.invalidate(node.parent)
pub func invalidate(self, id: int):
let pending: list[int] = [id]
let visited: list[int] = []
while pending.length > 0:
let next = pending.pop()
if next in visited:
continue
visited.append(next)
for node in self.nodes:
if node.id == next:
node.dirty = true
node.failure = ""
if node.parent >= 0:
pending.append(node.parent)
if next in node.inputs:
pending.append(node.id)
pub func evaluate(self, id: int) -> Mesh!:
return self.evaluate_data(id).require_mesh()
pub func evaluate_data(self, id: int) -> GeometryData!:
if self.background:
let node = self.require(id)
if node.dirty or node.computing:
error(ui.invalid, "Computing geometry…")
if node.failure != "":
error(ui.invalid, node.failure)
return node.cache else GeometryData()
let visiting: list[int] = []
return self.evaluate_node(id, visiting)
func evaluate_node(self, id: int, visiting: list[int]) -> GeometryData!:
let node = self.require(id)
if id in visiting:
error(ui.invalid, "Cycle detected during evaluation")
if not node.dirty:
if node.failure != "":
error(ui.invalid, node.failure)
return node.cache else error(ui.invalid, "Missing cached node result")
visiting.append(id)
if let report = self.on_progress:
report(id, 0.0, "Computing")
let result = node.shown(self.cook(node, visiting)) catch failure:
_ = visiting.pop()
node.cache = none
node.group_paths = []
node.failure = f"{node.name}: {failure.message}"
node.dirty = false
error(ui.invalid, node.failure)
_ = visiting.pop()
node.cache = result
node.failure = ""
node.warning = result.warning
node.console = result.console
node.dirty = false
node.evaluations += 1
node.summary = result.description()
node.group_paths = result.paths()
if let report = self.on_progress:
report(id, 1.0, "Complete")
return result
func cook(self, node: Node, visiting: list[int]) -> GeometryData!:
# Shader nodes make no geometry: their Material reads them.
if is_shader(node.kind):
return GeometryData()
if node.kind == "Material":
self.resolve_material(node)
if node.frozen != "":
return node.compute(GeometryData())
if node_catalog.places_children(node.kind):
var children = GeometryData()
if node.enabled:
for child in self.outputs(node.id):
children = children.with_instance(self.evaluate_node(child.id, visiting), visible = child.visible)
return node.compute(children)
if node.kind in node_catalog.sources() or reads_file(node.kind, node.enabled, node.values):
return node.compute(GeometryData())
let port = int(node.values[0]) if node.kind == "Switch" and node.enabled else 0
# An Edit node starts from nothing when unconnected (it can create);
# a Camera or Light makes just its object.
if node_catalog.optional_input(node.kind) and node.inputs[0] < 0:
# A Code or Script node from nothing still reads the clock, and a
# Script its project's files.
if let cache = self.sources:
cache.folder = self.folder
return node.compute(GeometryData(), none, none, self.sources, [self.frame, self.time(), self.fps])
if port < 0 or port >= node.inputs.length or node.inputs[port] < 0:
error(ui.invalid, "Connect a geometry input")
let data = self.evaluate_node(node.inputs[port], visiting)
if not node.enabled or node.kind in ["Switch", "Null"]:
return data
var second: GeometryData? = none
if node.inputs.length == 2:
if node.inputs[1] >= 0:
second = self.evaluate_node(node.inputs[1], visiting)
elif node_catalog.requires_second(node.kind):
error(ui.invalid, "Connect the second geometry input")
let progress = func (fraction: float) -> unit!:
if let report = self.on_progress:
report(node.id, fraction, "Tessellating" if node.kind == "Tessellate" else "Computing")
if let cache = self.sources:
cache.folder = self.folder
return node.compute(data, second, progress, self.sources, [self.frame, self.time(), self.fps], self.input_keys(node))
## Content keys of `node`'s inputs in a local cook: an input's result is the
## same until its node cooks again (0 for an unwired input).
func input_keys(self, node: Node) -> list[int]:
let keys: list[int] = []
for id in node.inputs:
if let input = self.find(id):
keys.append(nonzero_key((input.id, input.evaluations, "local").hash()))
else:
keys.append(0)
return keys
## `key`, or 1 when it is 0 (0 means unknown).
func nonzero_key(key: int) -> int:
return key if key != 0 else 1