dymokomi/luced-3d
Source of release 0.11.7
## Editor-owned geometry DAG. IDs survive history restores; meshes are immutable.
## What each level yields (the root's flagged objects, a container's output
## node, a Materials library) is decided here: docs/NETWORK-LEVELS.md. Wires
## stay inside data levels; an object reads another through an Import node.
from luce_geocore.geocore import Mesh
from geometry_data import GeometryData
from node import Node
import node_catalog
from node_evaluation import SourceCache
from cache_node import reads_file
from luce_ui import ui
from shader_nodes import is_shader, graph_kind, math_operations
from take import Take
import shader_nodes
import cad_nodes
from edit_kinds import is_edit, EditKinds
import levels
import import_node
import node_paths
import scene_nodes
from luce_cad.model import CadTolerances
pub func kinds() -> list[str]:
return node_catalog.kinds()
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]
## Wires picked in the network view, each (node, input port): the wire
## into that input. Delete removes them (selected_wires()).
pub var wires: list[(int, int)]
## The node the viewport edits and picks on in the scope: inside a data
## container the one with the display flag (set_display keeps them so).
pub var display: int = 1
pub var scope: int = -1
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
## The Edit CAD node edited at its CVs level, whose modeled faces' control
## nets are drawn (-1: none; elsewhere they are hidden, as Fusion's).
pub var cv_nets: int = -1
## A gizmo drag is live: its frames may show quick CAD previews.
pub var gesture: bool = false
## A drag (a gizmo's or a tool's) is live: its cooks show no Queued or
## Computing on their nodes (compute_session.luc).
pub var quiet: 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 Sketch whose input body's edges the editor's Project tool wants
## cast (-1: none); set on each rebuild.
pub var projecting: int = -1
## The Sketch sliced (slice_view.luc: the body in front of its plane
## not shown; -1: none); set on each rebuild.
pub var slicing: int = -1
## The Edit CAD sketch edited in the node projecting or sliced (its
## name; "": a Sketch node's); set on each rebuild.
pub var sketch_object: str = ""
## 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's CAD tolerances (positional, fit, tangent, curvature),
## saved beside the units: every body is built under them, and every
## node's stamp holds them (docs/research/KERNEL-ROBUSTNESS.md in
## luce-cad, 4.7).
pub var tolerances: CadTolerances
## 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
## The Edit kinds, made once and shared by every copy of this graph.
pub var kinds: EditKinds
## 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.tolerances = CadTolerances()
self.nodes = []
self.picked = []
self.wires = []
self.kinds = EditKinds()
self.takes = [Take("Main")]
if seed:
let cube = self.add("Box", 40.0, 70.0)
let geo = self.add("Geo", 40.0, 70.0)
cube.parent = geo.id
self.scope = geo.id
self.selected = cube.id
self.display = cube.id
## The nodes upstream of node `id` along first inputs, nearest first:
## what a failing node's viewport falls back on.
pub func upstream_chain(self, id: int) -> list[int]:
let chain: list[int] = []
var at = id
while chain.length < 64:
let node = self.find(at) else break
if node.inputs.length == 0 or node.inputs[0] < 0 or node.inputs[0] in chain:
break
at = node.inputs[0]
chain.append(at)
return chain
## The text of the nearest Sketch up `node`'s first inputs, which a
## Revolve's axis on a sketch line and a Thin Extrude's walls read (""
## for other nodes, or none).
pub func sketch_text(self, node: Node) -> str:
if not (node.kind in ["Revolve", "Extrude"]):
return ""
for id in self.upstream_chain(node.id):
let upstream = self.find(id) else return ""
if upstream.kind == "Sketch":
return upstream.texts[0]
return ""
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 context node 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 (context in ["cad", "shading"] and not node_catalog.allowed(kind, context)) or (context != "shading" and is_shader(kind)) or (context != "cad" and cad_nodes.is_cad_only(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")
# An object has no inputs (below), so an Input node in one has
# nothing to read.
if kind == "Input" and not self.has_inputs(self.scope):
error(ui.invalid, "Nothing is wired into an object; bring another one in with an Import node")
let node = Node(self.next_id, kind, x, y)
node.parent = self.scope
node.name = self.fresh_name(self.scope, kind, node.id)
self.next_id += 1
self.nodes.append(node)
# Nothing is wired on an object level: its nodes have no inputs.
if self.level_of(self.scope) == levels.object_level:
node.inputs = []
node.sources = []
# 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)
# On a data level a new node takes the display flag (its siblings
# lose it): what you just made is what you see.
if self.level_of(self.scope) == levels.data_level:
self.flag_alone(node)
if self.scope >= 0:
self.invalidate(self.scope)
return node
## Give `node` the display flag. On a data level it is a radio button:
## its siblings lose it, and it becomes the node the viewport shows.
## On an object level it only turns on.
pub func set_display(self, id: int) -> unit!:
let node = self.require(id)
if self.level_of(node.parent) == levels.data_level:
self.flag_alone(node)
elif not node.visible:
node.visible = true
self.visibility_changed(node)
if node.parent == self.scope:
self.display = id
## The node with the display flag on data level `parent`, else -1 (an
## object or library level has no single one).
pub func display_in(self, parent: int) -> int:
if self.level_of(parent) != levels.data_level:
return -1
for node in self.children(parent):
if node.visible:
return node.id
return -1
## How many of data level `parent`'s nodes have the display flag.
pub func display_count(self, parent: int) -> int:
var count = 0
for node in self.children(parent):
if node.visible:
count += 1
return count
func flag_alone(self, node: Node):
for sibling in self.children(node.parent):
sibling.visible = sibling.id == node.id
self.visibility_changed(node)
## What kind of level `parent`'s children form (levels.luc): the root and
## Groups in the scene context are object levels, Materials and Groups in
## it library levels, the rest data levels.
pub func level_of(self, parent: int) -> str:
let container = self.find(parent) else return levels.object_level
let context = self.context_at(parent)
if context == "scene":
return levels.object_level
if context == "materials" or container.kind == "Material":
return levels.library_level
return levels.data_level
## Whether container `parent`'s Input nodes have inputs to read: it sits
## on a data level (an object has none).
pub func has_inputs(self, parent: int) -> bool:
let container = self.find(parent) else return false
return container.inputs.length > 0
## The inputs a node on level `parent` has: none on an object level,
## otherwise its kind's.
pub func input_count(self, kind: str, parent: int) -> int:
return 0 if self.level_of(parent) == levels.object_level else node_catalog.input_count(kind)
## Whether `id` sits on an object level (the root or a scene Group).
pub func on_object_level(self, id: int) -> bool!:
return self.level_of(self.require(id).parent) == levels.object_level
## 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.wires = self.wires.copy()
result.display = self.display
result.scope = self.scope
result.background = self.background
result.sources = self.sources
result.kinds = self.kinds
result.takes = []
for take in self.takes:
result.takes.append(take.copy())
result.take = self.take
result.units = self.units
result.tolerances = self.tolerances
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
## The picked wires still connected in this scope.
pub func selected_wires(self) -> list[(int, int)]:
let result: list[(int, int)] = []
for (id, port) in self.wires:
if let node = self.find(id):
if node.parent == self.scope and port < node.inputs.length and node.inputs[port] >= 0:
result.append((id, port))
return result
## Nothing picked: no node and no wire.
pub func pick_nothing(self):
self.selected = -1
self.picked = []
self.wires = []
## Groups inherit the nearest enclosing typed context; the root is scene.
pub func context(self) -> str:
return self.context_at(self.scope)
pub func context_at(self, parent: int) -> str:
var id = parent
for _ in 0..<17:
let scope = self.find(id) else return "scene"
let context = node_catalog.child_context(scope.kind)
if context != "": return context
id = scope.parent
return "scene"
## Typed data stays directly usable by the next network (SDFs, grids,
## splats and material libraries must not become opaque instances).
pub func direct_children(self, node: Node) -> bool:
return node.kind in ["Geo", "SDF", "Volumes", "GSplats", "Materials"] or (node.kind == "Group" and self.context_at(node.parent) in ["sdf", "volumes", "gsplats", "materials"])
## Input nodes depend on the external source, never the containing
## node's result: that result depends on the Input's consumers.
pub func context_input(self, node: Node) -> int:
let parent = self.find(node.parent) else return -1
let port = int(node.values[0])
if not node_catalog.collects_children(parent.kind) or port < 0 or port >= parent.inputs.length: return -1
return parent.inputs[port]
## 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
## What level `parent` (-1: the root) yields to the level above, in
## authoring order (levels.luc): an object level's flagged nodes, a data
## level's one output node, a library's materials.
pub func outputs(self, parent: int) -> list[Node]:
return levels.yielded(self.level_of(parent), self.children(parent)).nodes
## Why what `parent` yields is ambiguous or missing ("" when it is not).
pub func output_warning(self, parent: int) -> str:
return levels.yielded(self.level_of(parent), self.children(parent)).warning
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)
if node.kind == "Input":
pending.append(self.context_input(node))
if node_catalog.collects_children(node.kind):
for child in self.outputs(node.id): pending.append(child.id)
if node.kind == "Render":
for child in self.outputs(-1): pending.append(child.id)
for imported in self.import_sources(node):
pending.append(imported.id)
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 network; connect the container and use an Input node inside")
if self.level_of(node.parent) == levels.object_level:
error(ui.invalid, "Objects are not wired together; bring one into another with an Import node")
if upstream.kind == "Render":
error(ui.invalid, "Render renders the scene; it has no output to connect")
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 gone = self.require(id)
let parent = gone.parent
# The display flag passes to the deleted node's first input, as in
# Houdini, so its data level still shows (and yields) something.
if gone.visible and self.level_of(parent) == levels.data_level:
if let input = self.find(gone.inputs[0] if gone.inputs.length > 0 else -1):
input.visible = true
if self.display == id:
self.display = input.id
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 display flag changed: what its level yields changed, so
## its container recooks (at the root, the Render nodes).
pub func visibility_changed(self, node: Node):
if node.parent >= 0:
self.invalidate(node.parent)
else:
self.invalidate_renders()
## Render nodes read the root's flagged objects, not wires.
func invalidate_renders(self):
for node in self.nodes:
if node.kind == "Render" and not node.dirty:
self.invalidate(node.id)
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)
elif node.kind != "Render":
for render in self.nodes:
if render.kind == "Render": pending.append(render.id)
if next in node.inputs:
pending.append(node.id)
if node.kind == "Input" and node.parent == next:
pending.append(node.id)
if node_paths.holds_paths(node.kind) and self.reads_by_path(node, next):
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.curve_paths = []
node.failure = f"{node.name}: {failure.message}"
node.dirty = false
error(ui.invalid, node.failure)
_ = visiting.pop()
node.cache = result
if cad_nodes.is_cad_only(node.kind) or is_edit(node.kind):
node.last_good = result
node.failure = ""
node.warning = result.warning
node.console = result.console
node.sketch_state = result.sketch_state
node.automatic = result.automatic
node.handles = result.handles
node.dirty = false
node.evaluations += 1
node.summary = result.description()
node.group_paths = result.paths()
node.curve_paths = result.curve_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(), tolerances = self.tolerances)
if node.kind == "Input":
let source = self.context_input(node)
return self.evaluate_node(source, visiting) if source >= 0 else GeometryData()
if node.kind == import_node.kind_name:
if not node.enabled:
return GeometryData()
# Several sources (a pattern) merge in authoring order.
let sources = self.import_read(node)
var result = import_node.placed(self.evaluate_node(sources[0].id, visiting), self.import_steps(node, sources[0]))
for at in 1..<sources.length:
result = result.merged(import_node.placed(self.evaluate_node(sources[at].id, visiting), self.import_steps(node, sources[at])))
return result
if node_catalog.collects_children(node.kind):
var children = GeometryData()
if node.enabled:
let listed: list[GeometryData] = []
for child in self.outputs(node.id):
let data = self.evaluate_node(child.id, visiting)
if self.direct_children(node):
children = children.merged(data)
else:
listed.append(data)
children = children.with_instances(listed)
let result = node.compute(children, direct_children = self.direct_children(node), tolerances = self.tolerances)
return warned(result, self.output_warning(node.id))
# Render renders the root: every flagged object there.
if node.kind == "Render":
var scene = GeometryData()
for child in self.outputs(-1):
scene = scene.merged(self.evaluate_node(child.id, visiting))
return self.render_result(node, scene)
# Sources, and nodes with no inputs (a Camera, a Light), cook from nothing.
if node.kind in node_catalog.sources() or node.inputs.length == 0 or reads_file(node.kind, node.enabled, node.values):
return node.compute(GeometryData(), tolerances = self.tolerances)
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).
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
# An Edit node's Reference is read though nothing is wired first.
var reference: GeometryData? = none
if node.enabled and node.inputs.length == 2 and node.inputs[1] >= 0:
reference = self.evaluate_node(node.inputs[1], visiting)
return node.compute(GeometryData(), reference, none, self.sources, [self.frame, self.time(), self.fps], gesture = self.gesture, tolerances = self.tolerances)
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", levels.output_kind]:
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), sketch = self.sketch_text(node), gesture = self.gesture, tolerances = self.tolerances)
## 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
# -- Import nodes (import_node.luc)
## The nodes Import node `node` reads, by its Object path: one, every
## match of a pattern, or none (not an Import, no path, nothing there).
## A source that reads the Import is still returned: import_read
## refuses it.
pub func import_sources(self, node: Node) -> list[Node]:
if node.kind != import_node.kind_name:
return []
let object = node_paths.row(node.kind, import_node.object_slot) else return []
return node_paths.reached(self.nodes, node, object)
## The sources Import node `node` cooks from, or why it can't.
pub func import_read(self, node: Node) -> list[Node]!:
let path = node.texts[import_node.object_slot].trim()
if path == "":
error(ui.invalid, "Choose the object to import")
let sources = self.import_sources(node)
if sources.length == 0:
error(ui.invalid, f"Nothing at {path}")
for source in sources:
if self.depends_on(source.id, node.id):
error(ui.invalid, "An Import can't read what it is part of")
return sources
## The placement steps Import node `node` applies to `source`'s result
## (import_node.carry), by its Transform menu: None keeps the source's
## own frame; Into This Object carries it into the Import's frame; Into
## Specified Object into the Transform Object's (blank: the world; ".":
## the source's own). Invert Transform carries it the other way.
pub func import_steps(self, node: Node, source: Node) -> list[float]!:
let own = import_node.frame(self.nodes, source)
var into = own
let mode = node.values[import_node.transform_slot]
if mode == import_node.into_this_object:
into = import_node.frame(self.nodes, node)
elif mode == import_node.into_specified_object:
let path = node.texts[import_node.transform_object_slot].trim()
if path == "":
into = []
elif path != ".":
let target = node_paths.resolve(self.nodes, node, path) else error(ui.invalid, f"No object at {path} to transform into")
into = import_node.frame(self.nodes, target)
if node.values[import_node.invert_slot] != 0.0:
return import_node.carry(source, into, own)
return import_node.carry(source, own, into)
# -- Render nodes
## The scene path of the camera Render node `node` looks through, by its
## Camera row (a node path): "" for the first camera when the row is
## blank; an error when no Camera is at the path.
pub func render_camera(self, node: Node) -> str!:
if node.texts[0].trim() == "":
return ""
let camera = node_paths.require(self.nodes, node, 0, "camera")
return scene_nodes.camera_path(camera.id, camera.texts)
## What Render node `node` yields from the root's `scene`: the scene,
## once its camera is there (bypassed: as it is).
pub func render_result(self, node: Node, scene: GeometryData) -> GeometryData!:
if not node.enabled:
return scene
return scene_nodes.check_render(self.render_camera(node), scene)
# -- Node paths (node_paths.luc)
## Whether invalidating `id` changes what node `node` reads by path: a
## node its paths reach; for an Import also a container above a source,
## above the Import or at or above its Transform Object (their
## placements place what it reads).
func reads_by_path(self, node: Node, id: int) -> bool:
let reached = node_paths.dependencies(self.nodes, node)
for each in reached:
if each.id == id:
return true
if node.kind != import_node.kind_name:
return false
let around: list[Node] = self.ancestors(node.parent)
for each in reached:
around.extend(self.ancestors(each.parent))
for container in around:
if container.id == id:
return true
return false
## Rename node `id`, rewriting the node paths that name it or pass
## through it. A name is one step of a path (node_paths.name_problem),
## and no sibling of the node has it.
pub func rename(self, id: int, name: str) -> unit!:
let node = self.require(id)
let problem = node_paths.name_problem(name)
if problem != "":
error(ui.invalid, problem)
for other in self.nodes:
if other.parent == node.parent and other.id != id and other.name == name:
error(ui.invalid, f"Another node here is called {name}")
self.keeping_paths(func () -> unit!:
node.name = name)
## A name no node in `parent` has, for a new node there (node paths
## name nodes): `stem` and `number`, or the next free number after it.
pub func fresh_name(self, parent: int, stem: str, number: int) -> str:
var at = number
while self.name_taken(parent, f"{stem} {at}"):
at += 1
return f"{stem} {at}"
## Whether a node in `parent` is called `name`.
pub func name_taken(self, parent: int, name: str) -> bool:
for node in self.nodes:
if node.parent == parent and node.name == name:
return true
return false
## Run `edit` (a rename, or nodes moved into another container) keeping
## every exact node path, in the nodes and in the takes, on the node it
## names, absolute or relative (node_paths.retarget). Paths only follow
## their nodes, so a holder recooks only when what it resolves to
## changed anyway (a pattern that matches more, a path to nothing that
## now finds a node).
pub func keeping_paths(self, edit: func() -> unit!) -> unit!:
let taken = node_paths.references(self.nodes, self.takes, self.take)
let before = self.path_resolutions()
edit()
_ = node_paths.retarget(self.nodes, self.takes, taken)
let after = self.path_resolutions()
for at in 0..<after.length:
let (id, reached) = after[at]
var same = false
for (old, was) in before:
same = same or (old == id and was == reached)
if not same:
self.invalidate(id)
## Each node holding paths, with what they reach (node_paths.resolution).
func path_resolutions(self) -> list[(int, int)]:
let result: list[(int, int)] = []
for node in self.nodes:
if node_paths.holds_paths(node.kind):
result.append((node.id, node_paths.resolution(self.nodes, node)))
return result
## Container `parent` and the containers above it, innermost first.
pub func ancestors(self, parent: int) -> list[Node]:
let result: list[Node] = []
var id = parent
for _ in 0..<17:
let container = self.find(id) else return result
result.append(container)
id = container.parent
return result
## `result` with `warning` when it has none of its own.
pub func warned(result: GeometryData, warning: str) -> GeometryData:
if warning != "" and result.warning == "":
result.warning = warning
return result
## `key`, or 1 when it is 0 (0 means unknown).
func nonzero_key(key: int) -> int:
return key if key != 0 else 1