dymokomi/luced-3d
Source of release 0.11.1
## The editor's state: the node network and its undo history, the
## displayed geometry and its component selection, the selection level, and
## the transactions every change goes through (perform, begin/commit,
## undo/redo). It cooks the graph (rebuild), synchronously or on the worker
## (poll_compute), and publishes the scene. It holds the view (camera and
## display settings, view_state.luc) and the viewport's line batches
## (viewport_batches.luc). Commands on it live beside it: node_commands,
## selection_commands, modeling_commands and placing_commands.
from luce_geocore.geocore import Mesh, Selection
from luce_3d.graphics import Scene, Group, Vector3, Matrix4, AmbientLight, DirectionalLight, SurfaceHits, SurfaceHit
from place_prompt import PlacePrompt
from tool_prompt import ToolPrompt
from network import Network, Node
from tools import tool_run
from history import History, Snapshot
from scene_projection import append_bounds
from local_cook import cook_outputs
from overlay_lines import OverlayLines
from compute_session import ComputeSession
from display_publisher import DisplayPublisher
from node_evaluation import SourceCache
from view_state import ViewState
from viewport_batches import ViewportBatches
from edit_kinds import is_edit, edit_kind
from geometry_data import GeometryData
from edit_types import EditKind, EditLevel
import edit_mesh
pub class Workspace:
pub var network: Network
pub let history: History
pub let scene: Scene
let objects: Group
pub let view: ViewState
pub let batches: ViewportBatches
pub var geometry: Mesh? = none
## Components of `geometry` (a luce-geocore Selection), on any displayed
## node; none when nothing is selected.
pub var selection: Selection? = none
## The selection level: an index into levels() (an Edit node's kind's,
## else Edit Mesh's: Object, Polygons, Edges, Vertices, Corners). Node
## selection and display are independent.
pub var component_mode: int = 1
## Edit kinds by node kind, made once each (they hold closures).
let edit_kinds: map[str, EditKind]
let mesh_levels: list[EditLevel]
## A tool waiting for its components (Houdini's tool → select), or
## Reselect of a node's group.
pub var prompt: ToolPrompt? = none
## A face or corners being placed in the viewport (place_prompt.luc).
pub var placing: PlacePrompt? = none
## What the next result of the displayed node selects (sync_selection):
## the displayed verb's output selection (Extrude's front faces), at
## level `pending_level` for a create step's piece (-1: the output's
## own); or group `pending_group` of Group Type `pending_type` (Reselect).
pub var adopt_output: bool = false
pub var pending_level: int = -1
pub var pending_group: str = ""
pub var pending_type: int = 0
pub var edit_tool: str = "Select"
## A gizmo drag's frames are being previewed (preview_move and
## preview_parameters); commit cooks the released result in full.
pub var dragging: bool = false
pub var revision: int = 0
pub var notice: str = ""
## The open transaction: the state before it, its label, and whether it
## changed anything (only then does it become an undo step).
pub var pending: Snapshot? = none
var pending_label: str = ""
pub var pending_changed: bool = false
pub var compute: ComputeSession? = none
pub let publisher: DisplayPublisher
let sources: SourceCache
var pending_frame: bool = false
var project_epoch: int = 0
pub func init(self) -> unit!:
self.view = ViewState()
self.batches = ViewportBatches()
self.sources = SourceCache()
self.edit_kinds = {}
self.mesh_levels = edit_mesh.levels()
self.network = Network()
self.network.sources = self.sources
self.history = History()
self.scene = Scene()
self.objects = Group()
self.publisher = DisplayPublisher(self.objects)
self.scene.add(self.objects)
self.scene.add(AmbientLight(intensity = 0.35))
self.scene.add(DirectionalLight(direction = Vector3(3.0, 5.0, 2.0), intensity = 0.85))
self.rebuild()
## Install a validated document. Old worker generations cannot overwrite it;
## the source epoch also prevents reusing stale imports with recycled IDs.
pub func replace_network(self, graph: Network) -> unit!:
self.pending = none
self.pending_changed = false
self.pending_frame = false
for node in self.network.nodes:
if node.source_revision > self.project_epoch: self.project_epoch = node.source_revision
self.project_epoch += 1
for node in graph.nodes:
node.source_revision = self.project_epoch
self.network = graph
self.network.background = self.compute != none
self.network.sources = self.sources
self.history.changes.clear()
self.history.cursor = 0
self.selection = none
self.prompt = none
self.component_mode = 1
self.notice = ""
self.rebuild()
## Frame the selected components while editing, else every displayed mesh.
pub func frame_cube(self) -> unit!:
let points: list[Vector3] = []
if self.selected_count() > 0:
let mesh = self.geometry else return
let chosen = self.selection else return
# The selection's box, in Base.
let box = chosen.bounds(mesh)
let bounds = mesh.bounds()
self.frame_points([box.minimum, box.maximum], bounds.maximum.subtract(bounds.minimum).length() * 0.01)
return
if let session = self.compute:
if session.busy:
self.pending_frame = true
return
for point in self.publisher.bounds:
points.append(point)
# Curves frame by their drawn lines, with the worker or without.
for batch in self.batches.curve_batches:
if batch.count() > 0:
let box = batch.bounds()
points.append(box.minimum)
points.append(box.maximum)
var candidates = self.network.outputs(self.network.scope)
if let node = self.network.find(self.network.display):
if self.network.preview or node.kind == "Group":
candidates = [node]
if self.compute != none:
candidates = []
for node in candidates:
if not node.visible:
continue
let data = self.network.evaluate_data(node.id) catch failure:
continue
append_bounds(data, Matrix4(), points)
self.frame_points(points)
## Frame `points`, from at least `least` away.
func frame_points(self, points: list[Vector3], least: float = 0.001) -> unit!:
self.view.frame(points, least)
self.revision += 1
pub func reset_view(self) -> unit!:
self.view.yaw = 0.7
self.view.pitch = 0.5
self.frame_cube()
## Normal guides are made on the worker only while they are shown.
pub func toggle_normals(self) -> unit!:
self.view.normals_visible = not self.view.normals_visible
self.revision += 1
if self.compute != none and self.view.normals_visible:
self.rebuild()
pub func toggle_hulls(self) -> unit!:
self.view.hulls_visible = not self.view.hulls_visible
self.revision += 1
pub func toggle_grid(self) -> unit!:
self.view.grid_visible = not self.view.grid_visible
self.revision += 1
pub func set_display_mode(self, mode: int) -> unit!:
if self.view.set_display_mode(mode):
self.revision += 1
pub func selected(self) -> Node?:
return self.network.find(self.network.selected)
## Components can be picked whenever the viewport shows a node's mesh.
pub func selecting(self) -> bool:
return self.geometry != none
## The Edit kind of node kind `name` (kept once made), or none.
pub func kind_of(self, name: str) -> EditKind?:
if let known = self.edit_kinds[name]:
return known
let made = edit_kind(name) else return none
self.edit_kinds[name] = made
return made
## The selected node's Edit kind, when it is an enabled Edit node.
pub func active_kind(self) -> EditKind?:
let node = self.selected() else return none
if not node.enabled:
return none
return self.kind_of(node.kind)
## The selection levels: the selected Edit node's kind's, else Edit
## Mesh's (any displayed mesh selects on them).
pub func levels(self) -> list[EditLevel]:
if let kind = self.active_kind():
return kind.levels
return self.mesh_levels
pub func level(self) -> EditLevel:
let all = self.levels()
return all[self.component_mode if self.component_mode < all.length else 0]
## The kind whose tools the viewport offers: the active Edit node's,
## else Edit Mesh's (tools on any displayed mesh make verb nodes).
pub func strip_kind(self) -> EditKind:
return self.active_kind() else (self.kind_of(edit_mesh.kind_name) else trap("Edit Mesh"))
## Whether viewport tool `name` applies at the current level: the Edit
## node's kind offers it there (Edit Mesh's tools on another node's mesh).
pub func tool_available(self, name: str) -> bool!:
let kind = self.active_kind() else return tool_run(name, 0.5) != none
if name in kind.primitives or name in kind.draw_tools:
return true
let tool = kind.tool(name) else return false
return tool.offered(self.component_mode)
## The level that selects single elements of `domain` (Polygons rather
## than Object), or the first level.
pub func level_of(self, domain: int) -> int:
let all = self.levels()
for index in 0..<all.length:
if all[index].domain_number() == domain and all[index].piece == none:
return index
for index in 0..<all.length:
if all[index].domain_number() == domain:
return index
return 0
## The Edit overlay's mode for the level's domain (0 points, 1 edges,
## 2 faces, 3 corners).
pub func overlay_mode(self) -> int:
let domain = self.domain()
return 1 if domain == 4 else (3 if domain == 1 else domain)
## The selection's domain on the pick geometry (0 points, 4 edges,
## 2 faces, 1 corners) and the Group Type steps and verb nodes read.
pub func domain(self) -> int:
return self.level().domain_number()
pub func group_type(self) -> int:
return self.level().group_number()
## The soft selection the viewport tints: the selected Edit node's soft
## radius, falloff and symmetry, where its moves honor them (Edit Mesh,
## and Edit CAD's control vertices, both through Transform Components);
## a radius of 0 elsewhere.
pub func soft_selection(self) -> list[float]:
let node = self.selected() else return [0.0, 0.0, 0.0]
let honored = node.kind == "Edit Mesh" or (node.kind == "Edit CAD" and self.group_type() == 1)
if not honored or not self.editing() or node.values.length < 4:
return [0.0, 0.0, 0.0]
return [node.values[1], node.values[2], node.values[3]]
## The selection on the displayed mesh (empty when there is none).
pub func current_selection(self) -> Selection?!:
let mesh = self.geometry else return none
if let chosen = self.selection:
if chosen.domain() == self.domain() and chosen.fits(mesh): return chosen
return Selection.empty(mesh, self.domain())
## The selected components' ids, ascending (tests and small selections).
pub func selected_ids(self) -> list[int]:
let result: list[int] = []
let chosen = self.selection else return result
var at = chosen.next(-1)
while at >= 0:
result.append(at)
at = chosen.next(at)
return result
pub func selected_count(self) -> int:
let chosen = self.selection else return 0
return chosen.count()
pub func editing(self) -> bool:
let node = self.selected() else return false
return is_edit(node.kind) and node.enabled and (not node.dirty or self.pending != none) and node.id == self.network.display and self.geometry != none
pub func transforming(self) -> bool:
let node = self.selected() else return false
return node.kind in ["Transform", "Group"] and node.enabled
## Parameter gizmos submit absolute gesture values; no mesh work on UI thread.
pub func preview_parameters(self, values: list[float]) -> unit!:
let before = self.pending else return
self.dragging = true
let original = before.graph.require(self.network.selected)
let node = self.selected() else return
node.values = values.copy()
self.pending_changed = values != original.values
self.network.invalidate(node.id)
self.rebuild()
pub func snapshot(self) -> Snapshot!:
return Snapshot(self.network, self.selection, self.component_mode)
pub func begin(self, label: str) -> unit!:
if self.pending != none:
return
self.pending = self.snapshot()
self.pending_label = label
self.pending_changed = false
pub func commit(self) -> unit!:
let before = self.pending else return
let changed = self.pending_changed
if changed:
self.history.push(self.pending_label, before, self.snapshot())
self.pending = none
self.pending_changed = false
self.revision += 1
# A drag's frames were previews: the released result is cooked in full.
if self.dragging:
self.dragging = false
self.rebuild()
pub func cancel(self) -> unit!:
let before = self.pending else return
self.pending = none
self.pending_changed = false
self.dragging = false
self.restore(before)
pub func in_transaction(self) -> bool:
return self.pending != none
pub func restore(self, snapshot: Snapshot) -> unit!:
self.network = snapshot.graph.copy()
self.network.background = self.compute != none
self.selection = snapshot.selection
self.component_mode = snapshot.mode
self.rebuild()
pub func undo(self) -> unit!:
if self.placing != none:
self.cancel_placing()
return
if self.pending != none:
self.cancel_prompt()
return
if self.history.can_undo():
self.history.cursor -= 1
self.restore(self.history.changes[self.history.cursor].before)
pub func redo(self) -> unit!:
if self.pending != none:
self.cancel_prompt()
if self.history.can_redo():
let snapshot = self.history.changes[self.history.cursor].after
self.history.cursor += 1
self.restore(snapshot)
## Every mutation enters this command transaction path, including scripts
## and UI gestures. Invalid topology/links roll back without losing history.
pub func perform(self, label: str, action: func() -> unit!) -> unit!:
let owns = self.pending == none
if owns:
self.begin(label)
action() catch failure:
self.cancel()
self.notice = failure.message
self.revision += 1
return
self.pending_changed = true
self.revision += 1
if owns:
self.commit()
pub func rebuild(self) -> unit!:
if let session = self.compute:
self.network.level = self.component_mode
self.network.gesture = self.dragging
session.submit(self.network, self.view.mesh_mode(), self.view.normals_visible)
self.revision += 1
return
# The displayed Edit node's own lines (its kind's guides).
var guides: func(GeometryData, OverlayLines) -> unit!? = none
if let node = self.network.find(self.network.display):
if node.enabled:
if let kind = self.kind_of(node.kind):
guides = kind.guides
let cooked = cook_outputs(self.network, self.objects, self.batches, self.view.mesh_mode(), guides)
self.notice = cooked.notice
self.geometry = none
if let node = cooked.node:
self.geometry = self.picked(node, cooked.data else trap("display"))
self.sync_selection()
self.revision += 1
## What the viewport picks on for displayed `node`: its Edit kind's
## geometry for the level, else its mesh.
func picked(self, node: Node, data: GeometryData) -> Mesh?!:
if node.enabled:
if let kind = self.kind_of(node.kind):
return kind.pick(data, self.component_mode) catch failure:
recover none
return data.mesh
## Runtime UI uses a persistent worker; deterministic tests/scripts may cook
## synchronously. Published scenes remain visible while replacements compute.
pub func enable_compute(self) -> unit!:
if self.compute == none:
self.compute = ComputeSession()
self.network.background = true
self.rebuild()
pub func poll_compute(self) -> bool!:
let session = self.compute else return false
let progress = session.poll_progress(self.network)
let completed = session.service.completed()
if completed == 0:
return progress
if completed != session.generation:
session.service.release_result(self.publisher.kept)
return progress
self.notice = session.read_report(self.network) catch failure:
session.service.release_result(self.publisher.kept)
session.busy = false
self.notice = failure.message
self.revision += 1
return true
if session.service.failed() or session.resync:
session.service.release_result(self.publisher.kept)
# The worker lost its mirror: send the whole graph once.
if session.resync:
self.rebuild()
self.revision += 1
return true
if self.publisher.adopt(session.service, self.network):
self.batches.adopt(session.service)
self.geometry = self.publisher.geometry
self.sync_selection()
session.service.release_result(self.publisher.kept)
self.revision += 1
if self.pending_frame:
self.pending_frame = false
self.frame_cube()
return true
## The nearest visible surface along a view ray (the displayed scene).
pub func surface_at(self, origin: Vector3, direction: Vector3) -> SurfaceHit!:
return SurfaceHits.cast(self.objects, origin, direction)
pub func cancel_placing(self) -> unit!:
if self.placing == none:
return
self.placing = none
self.notice = ""
self.revision += 1
## Esc: drop the prompted node (or the reselection) with the transaction.
pub func cancel_prompt(self) -> unit!:
self.prompt = none
self.pending_group = ""
self.notice = ""
self.cancel()
## The components' center; the bounds center without a selection.
pub func selection_center(self) -> Vector3!:
let mesh = self.geometry else return Vector3()
let chosen = self.current_selection() else return mesh.bounds().minimum.add(mesh.bounds().maximum).multiply_scalar(0.5)
return chosen.center(mesh)
## A new result of the displayed node: adopt a tool's output selection
## (switching the component type, as Houdini does), a reselection's
## group, or drop a selection that no longer fits.
func sync_selection(self) -> unit!:
let mesh = self.geometry else return
if self.component_mode >= self.levels().length:
self.component_mode = 0
self.selection = none
# A create step's piece: selected at its level (Object).
if self.adopt_output and self.pending_level >= 0:
self.adopt_output = false
self.component_mode = self.pending_level
self.pending_level = -1
if mesh.group_size(".selection", self.domain()) >= 0:
self.selection = Selection.of(mesh, ".selection", self.domain())
return
if self.pending_group != "":
let domain = [0, 0, 4, 2, 1][self.pending_type] if self.pending_type > 0 else self.domain()
self.component_mode = self.level_of(domain)
self.selection = Selection.of(mesh, self.pending_group, domain)
self.pending_group = ""
return
if self.adopt_output:
self.adopt_output = false
for domain in [2, 4, 0, 1]:
if mesh.group_size(".selection", domain) >= 0:
self.component_mode = self.level_of(domain)
self.selection = Selection.of(mesh, ".selection", domain)
return
if let chosen = self.selection:
if chosen.domain() != self.domain() or not chosen.fits(mesh):
self.selection = none