dymokomi/luce-geocore
Source of release 0.7.9
0.7.9 / src / verbs / verb.lucb
## Verbs: every modeling operation as one registered Base kernel, after
## Houdini's SOP verbs. A standalone node and a step of the Edit node call the
## same verb, which sees neither. `Verbs.run` resolves the group expression to
## bits on the verb's domain, runs the kernel, builds the output mesh, carries
## every attribute and group through the kernel's provenance, and returns the
## output selection (what the verb made: Extrude's front faces, Inset's inner
## faces), which the viewport adopts after a tool.
import interop
from luce_std import math
import memory
import errors
import sync
import strings
from luce_std import parallel
import core.attribute_ops
from core.growing import Growing
from core.strings import TableBuilder, table_count
from core.hash import FullKey
from core.shared import Column
from core.float3 import Float3
from core.bits import Bits, BitsBuilder, popcount, trailing_zeros
from core.attributes import Attribute, AttributeStore, Domain, DataType, Storage, Role
from core.geometry import Bounds
from math.vector import Vector3
from math.matrix import Matrix4
from geometries.polygon import set_trail, trail_from, changed_points, with_group_bits, Mesh, mesh_share, mesh_dispose, mesh_adopt, assembled, kept_faces, edge_parents, moved_storage, put_attribute, precise_span, mesh_positions, remove_attribute, edge_bits_from_pairs, concatenated, MeshPart
from geometries.triangle_index import TriangleIndex
from primitives import placement, grid_mesh, box_mesh, quad_sphere_mesh, uv_sphere_mesh, capsule_mesh, cylinder_mesh, tube_mesh, disc_mesh, torus_mesh, helix_mesh, platonic_mesh, icosphere_mesh
from geometries.triangulation.polygon_triangulation import area_normal
import geometries.triangulation.face_scratch
from geometries.point_hash import PointHash, Cell
from geometries.topology.connectivity import Topology
from groups import GroupType, is_blank, guess_domain, GroupResult, GroupReport, group_bits, Selection, adopt_selection, strict_conversion, selection_bits
from selecting import converted, rule_at, rule_count, run_rule, mirror_tolerance, mirror_map, symmetric, Delimits, delimits_for, finding_count, finding_label, finding_domain, finding_bits
from core.limits import max_points, check_mesh_size
from core.verb_specs import ParmKind, ParmSpec, PickSpec, KeySpec, PlaceSpec, Parms, filled_parms
from luce_std import ramp
from luce_std import sort
## A verb with no pick declared takes one, at every level.
let no_picks: PickSpec[1] = [PickSpec("")]
## A verb with no keys for its drag.
let no_keys: KeySpec[1] = [KeySpec("", -1, "")]
## A verb that takes no other domain as it is.
let no_domains: Domain[1] = [Domain.detail]
## The picks many tools share: faces, edges, whole pieces or their faces,
## and points, edges or faces.
let pick_faces: PickSpec[1] = [PickSpec("Faces", "faces")]
let pick_edges: PickSpec[1] = [PickSpec("Edges", "edges")]
let pick_pieces: PickSpec[1] = [PickSpec("Faces", "objects faces")]
let pick_components: PickSpec[1] = [PickSpec("Components", "points edges faces")]
## Whole pieces, or their points, edges or faces: a deformer's.
let pick_pieces_points: PickSpec[1] = [PickSpec("Components", "objects points edges faces")]
## Weighted parents of interpolated elements (a new point on an edge, a new
## corner inside a face): element e takes entries offsets[e]..<offsets[e+1].
pub struct Mix:
pub var offsets: Growing[i32]
pub var parents: Growing[i32]
pub var weights: Growing[f32]
pub func init():
self.offsets = Growing[i32]()
self.parents = Growing[i32]()
self.weights = Growing[f32]()
pub func close():
self.offsets.close()
self.parents.close()
self.weights.close()
## What a kernel reads: the input mesh, its group as bits of the verb's
## domain (every element when the group is empty) and the parameters.
pub struct VerbInput:
pub let mesh: const Mesh*
pub let group: Bits
pub let parms: Parms
## Mirror across X, Y or Z (1..3; 0 none): the group is symmetric already,
## and point verbs move mirrored points to mirrored places.
pub let symmetry: i64 = 0
## The domain of `group`: the verb's, or its second domain.
pub let domain: Domain = Domain.face
## The second pick's elements (Bridge's second loop, Target Weld's
## target), on the domain its levels name, when one was given.
pub let second: Bits? = none
## The reference surface of a verb that takes one (Verb.inputs 2: a
## node's second input, an Edit Mesh's Reference): Shrinkwrap's target,
## the surface Relax keeps its points on.
pub let reference: const Mesh*? = none
## The last frame of a drag when it is given (Verbs.run's `over`): a
## verb that builds its mesh may move only the points the last frame
## says depend on what changed (Mesh.trail), instead of building again.
pub let over: const Mesh*? = none
## What a kernel returns: new positions over the same topology, a topology
## built with parents, or a finished mesh; and the output selection.
pub struct VerbOutput:
## Position verbs: every point's new position (relative to the input's
## origin) and the points that moved.
pub var positions: Column[Float3]
pub var moved: Growing[u32]
pub var built: bool = false
pub var builder: TopologyBuilder
## Verbs that make their mesh themselves (subsets).
pub var mesh: Mesh*? = none
## The output selection and its domain.
pub var selection: BitsBuilder
pub var selection_domain: Domain = Domain.face
## A warning for the node's info line (static text), and how many
## elements it concerns.
pub var warning: str = ""
pub var skipped: usize = 0
## A built mesh's points a later frame repositions (see Mesh.trail; a
## verb may mark entries it dropped), and the key of everything the frame
## was built from but those positions; with `over_key`, `positions` are
## the last frame's (`over`) with `moved` (those points) placed again,
## nothing built.
pub var trail_key: u64 = 0
pub var trail_points: Growing[u32]
pub var over_key: u64 = 0
pub func init():
self.positions = Column[Float3]()
self.moved = Growing[u32]()
self.built = false
self.builder = TopologyBuilder()
self.mesh = none
self.selection = BitsBuilder(Column[u64](), 0)
self.selection_domain = Domain.face
self.warning = ""
self.skipped = 0
self.trail_key = 0
self.trail_points = Growing[u32]()
self.over_key = 0
pub func close():
self.positions.release()
self.moved.close()
self.trail_points.close()
self.builder.close()
if let mesh = self.mesh: mesh_dispose(mesh)
self.mesh = none
self.selection.close()
pub struct Verb:
## The node kind and recipe name ("PolyExtrude").
pub let name: str
pub let category: str
pub let description: str
## The domain the kernel works on; other group types convert to it.
pub let domain: Domain
## Whether the group may name other domains (converted).
pub let converts: bool
pub let parms: const ParmSpec[]
## False: positions and attributes only, element ids stable.
pub let changes_topology: bool
pub let cook: func(const VerbInput*, VerbOutput*) -> unit!
## Groups of other domains convert with "any" related element (Blast:
## a point deletes every face using it) instead of the default rules.
pub let loose: bool = false
## Other domains the kernel takes as they are (PolyExtrude: edges and
## points); none for a verb that converts every group to its domain.
pub let also: const Domain[] = no_domains[..<0]
## Groups of other domains convert with "all" related elements (Dissolve:
## a face group dissolves only the edges between its faces).
pub let strict: bool = false
## Whether numbers may follow the parameters (PolyDraw's drawn corners).
pub let trailing: bool = false
## Whether the group stays on its own domain, whichever it is (the
## Select verbs: a pattern of selected points, edges or faces).
pub let native: bool = false
## The inputs its node has: 1, or 0 for a primitive (made from nothing:
## no group; as an Edit step it adds to the edited mesh), or 2 for a
## verb that reads a reference surface (VerbInput.reference), which
## `second_required` says it cannot do without.
pub let inputs: usize = 1
pub let second_required: bool = false
# How the verb is offered as a modeling tool. luced-3d builds its tool
# registry from these, so a verb added to `makers` reaches the node
# menu, the Edit Mesh tools, the menus, the marking menus, the
# right-click menu and the docs with no other edit.
## The tool's label ("Bevel" for PolyBevel; "": the name).
pub let label: str = ""
## "Create", "Modify" or "Select"; "" when the verb is a node only.
pub let section: str = ""
## The group menus list it under ("Extrude", "Cut", "Shape", …).
pub let family: str = ""
## A luciaos-assets icon name.
pub let icon: str = ""
## What it works on; none declared is one pick at every level.
pub let picks: const PickSpec[] = no_picks[..<0]
## The parameter a drag in the viewport sets after it runs (-1: none),
## and how the pointer sets it (verbs/drag.lucb): "length" a world
## distance hauled away from the selection's center, "normal" along the
## selection's average normal, "amount" a share of the parameter's
## range, "angle" turned about the center, "slide" along the rails
## `rails` gives.
pub let drag: i64 = -1
pub let drag_mode: str = "length"
## Whether the value follows the pointer as soon as the tool runs, no
## button held (Blender's Extrude and Edge Slide); else a drag sets it.
pub let follows: bool = false
## The count parameter the wheel steps while the drag lasts (-1: none).
pub let wheel: i64 = -1
## The vector parameter X, Y and Z set while the drag lasts (an axis
## lock), and the menu parameter set to its last choice with it (-1:
## none).
pub let axis: i64 = -1
pub let axis_choice: i64 = -1
## Keys that change the tool while its drag lasts (Bevel's A, P, S for
## the value the drag sets, M, V, O, I, Z, N to cycle menus, C, H, U, K
## to flip toggles), as Blender's modal keys.
pub let keys: const KeySpec[] = no_keys[..<0]
## The rails a "slide" drag runs along, from the input and parameters.
pub let rails: (func(const VerbInput*, Rails*) -> unit!)? = none
## Viewport input it takes besides the selection: "" none, "stroke"
## (the knife), "place" (PolyDraw's clicked corners), "hover" (Loop
## Cut's ring under the pointer, placed by a click), "create" (a
## primitive drawn on the ground or a surface: `place`), "pen" (Poly
## Pen's faces built under the pointer).
pub let gesture: str = ""
## How the "create" gesture sets a primitive's rows.
pub let place: PlaceSpec? = none
## Whether, with nothing selected, it runs on everything.
pub let whole: bool = false
## The select rule it runs instead of `cook` (selecting/registry.lucb's
## index; -1: none).
pub let rule: i64 = -1
## Whether, run on its first pick alone, it still wants its second
## (Bridge with fewer than two loops; Target Weld always); none: the
## second pick is never asked for.
pub let wants: (func(const VerbInput*) -> bool!)? = none
## Whether the kernel takes groups on `domain` as they are (`also`).
pub func takes(domain: Domain) -> bool:
for other in self.also:
if other == domain: return true
return false
## A run's product: the output mesh, its selection and the warning.
pub struct VerbRun:
pub var mesh: Mesh*
pub var selection: Column[u64]
pub var selection_count: usize
pub var selection_domain: Domain
pub var warning: str
pub var misses: usize
pub func close():
mesh_dispose(self.mesh)
self.selection.release()
## Run `verb` on `mesh`: the group (text; empty is every element) on
## `group_type`'s domain (the second pick's `second` read the same way),
## made symmetric across `symmetry` (0 none, 1 X, 2 Y, 3 Z), converted to
## the verb's domain. With `keep`, the output
## selection is the group carried through the verb (a new element is
## selected when all its parents were) instead of what the verb made.
pub func run_verb(verb: const Verb*, mesh: const Mesh*, group: str, group_type: i64, numbers: const f64[], symmetry: i64 = 0, keep: bool = false, second: str = "", reference: const Mesh*? = none, over: const Mesh*? = none) -> VerbRun!:
if verb.second_required and reference == none: error(errors.invalid, "this operation needs a reference surface: connect one to its second input")
var resolved = try resolve_group(verb, mesh, group, group_type, symmetry)
defer resolved.close()
var picked = try second_pick(verb, mesh, second, group_type)
defer picked.close()
let domain = resolved.domain
let target = resolved.target
# The group rides through the verb as `.carried` when it is kept.
var carrier: interop.Reference[Mesh]? = none
defer:
if let owner = carrier: owner.release()
var source = mesh
if keep:
let owner = try with_group_bits(mesh, ".carried", domain, resolved.chosen.view())
carrier = owner
source = owner.value()
let bits = resolved.bits.view()
var values = try filled_parms(verb.parms, numbers, verb.trailing)
defer values.close()
var output = VerbOutput()
defer output.close()
var second_bits: Bits? = none
if not is_blank(second) and verb.picks.length > 1: second_bits = picked.view()
let input = VerbInput(source, bits, Parms(values.view()), symmetry, target, second_bits, reference, over if not keep else none)
if verb.rule >= 0:
let rule = rule_at((usize)verb.rule)
let made = try run_rule(&rule, source, bits, target, values.view())
output.selection.close()
output.selection = made.bits
output.selection_domain = made.domain
else:
let cook = verb.cook
try cook(&input, &output)
let product = try finish(source, &output, over if not keep else none)
# Edges the kernel selected by their points: found on the output.
if output.built and output.builder.selected_edges.count > 0:
select_edges(product, &output) catch failure:
mesh_dispose(product)
error(failure.code, failure.message)
var selection = output.selection.finish()
var selection_domain = output.selection_domain
if keep:
let carried_index = product.attribute_on(".carried", domain)
if carried_index >= 0:
let entry = product.attribute_entry(carried_index) catch failure:
mesh_dispose(product)
selection.release()
error(failure.code, failure.message)
selection.release()
selection = Column[u64].copy_of(u64[]((u64*)entry.data.view().data, entry.data.view().length // 8)) catch failure:
mesh_dispose(product)
error(failure.code, failure.message)
selection_domain = domain
remove_attribute(product, ".carried", domain) catch failure:
mesh_dispose(product)
selection.release()
error(failure.code, failure.message)
# The output selection also rides in the mesh as the group `.selection`
# (Houdini's cook selection), so it reaches the viewport with the result.
mark_selection(product, &selection, selection_domain) catch failure:
mesh_dispose(product)
selection.release()
error(failure.code, failure.message)
let count = product.domain_size(selection_domain) catch failure:
mesh_dispose(product)
selection.release()
error(failure.code, failure.message)
return VerbRun(product, selection, count, selection_domain, output.warning, resolved.misses)
## The second pick's expression, read on `group_type`'s domain as the
## first is, as bits on the domain its levels name first (points, edges or
## faces); none given is no bits.
func second_pick(verb: const Verb*, mesh: const Mesh*, expression: str, group_type: i64) -> BitsBuilder!:
if is_blank(expression) or verb.picks.length < 2: return try BitsBuilder.zeros(0)
let target = pick_domain(&verb.picks[1])
let named = try GroupType.of(group_type)
var domain = named.domain(target)
if named == GroupType.guess: domain = try guess_domain(mesh, expression, target)
var result = try group_bits(mesh, expression, domain)
defer result.bits.release()
var bits = try BitsBuilder.copy_of(Bits(result.bits.view(), try mesh.domain_size(domain)))
if domain == target: return bits
defer bits.close()
let topology = try Topology.of(mesh)
return try converted(&topology, bits.view(), domain, target, strict_conversion(domain, target))
## The domain a pick's first level names (faces for objects or none).
func pick_domain(pick: const PickSpec*) -> Domain:
if strings.starts_with(pick.levels, "points"): return Domain.point
if strings.starts_with(pick.levels, "edges"): return Domain.edge
return Domain.face
## Whether `verb` on `group` alone (as `run_verb` reads it) wants its
## second pick.
pub func verb_wants_second(verb: const Verb*, mesh: const Mesh*, group: str, group_type: i64, numbers: const f64[]) -> bool!:
let check = verb.wants else return false
if verb.picks.length < 2: return false
var resolved = try resolve_group(verb, mesh, group, group_type, 0)
defer resolved.close()
var values = try filled_parms(verb.parms, numbers, verb.trailing)
defer values.close()
let input = VerbInput(mesh, resolved.bits.view(), Parms(values.view()), 0, resolved.target)
return try check(&input)
## A group as a verb reads it: `chosen` on the domain it names (made
## symmetric), and `bits` on the domain the kernel works on.
struct Resolved:
var chosen: BitsBuilder
var domain: Domain
var bits: BitsBuilder
var target: Domain
var misses: usize
func close():
self.chosen.close()
self.bits.close()
## Verb `verb`'s group on `mesh`: the expression (empty is every element)
## on `group_type`'s domain, made symmetric across `symmetry` (0 none,
## 1 X, 2 Y, 3 Z), converted to the domain the kernel works on.
func resolve_group(verb: const Verb*, mesh: const Mesh*, group: str, group_type: i64, symmetry: i64) -> Resolved!:
let expression = group if not is_blank(group) else "*"
let named = try GroupType.of(group_type)
var domain = named.domain(verb.domain)
if named == GroupType.guess: domain = try guess_domain(mesh, expression, verb.domain)
let target = domain if verb.native or verb.takes(domain) else verb.domain
if not verb.converts and domain != target: error(errors.invalid, "this operation works on another component type")
if symmetry < 0 or symmetry > 3: error(errors.invalid, "symmetry is 0 (none), 1 (X), 2 (Y) or 3 (Z)")
var result = try group_bits(mesh, expression, domain)
defer result.bits.release()
var chosen = try BitsBuilder.copy_of(Bits(result.bits.view(), try mesh.domain_size(domain)))
errdefer chosen.close()
if symmetry > 0:
var mirrored = try symmetric(mesh, chosen.view(), domain, symmetry)
chosen.close()
chosen = mirrored
var bits = try BitsBuilder.copy_of(chosen.view())
errdefer bits.close()
if domain != target and expression == "*":
# Everything is everything on the verb's domain too (loose points
# with it): the cached group, not a conversion of the whole mesh on
# every frame of a stroke.
var all = try group_bits(mesh, expression, target)
defer all.bits.release()
bits.close()
bits = try BitsBuilder.copy_of(Bits(all.bits.view(), try mesh.domain_size(target)))
elif domain != target:
let topology = try Topology.of(mesh)
var moved = try converted(&topology, bits.view(), domain, target, (strict_conversion(domain, target) or verb.strict) and not verb.loose)
bits.close()
bits = moved
return Resolved(chosen, domain, bits, target, result.report.misses)
## The kernel's output as a mesh: moved positions share everything else, a
## built topology carries every attribute through its provenance. Moved
## positions are made over `over` instead when it differs from the source
## only in positions and its output selection (a drag's last frame, the
## same action run again): its normals, shading and GPU copies then change
## only where points moved since.
func finish(source: const Mesh*, output: VerbOutput*, over: const Mesh*? = none) -> Mesh*!:
if let made = output.mesh:
output.mesh = none
return made
if output.over_key != 0:
# The last frame's mesh with the points that depend on the dragged
# value placed again: its topology, caches and GPU copies kept.
let previous = over else trap("a verb repositioned a last frame it was not given")
# Authored normals stay as the build carried them through the parents.
let made = try moved_storage(previous, output.positions, output.moved.view(), keep_normals = true)
if (try degenerate_around(made, output.moved.view())) <= (try degenerate_around(previous, output.moved.view())):
set_trail(made, output.over_key, output.trail_points.view()) catch failure:
mesh_dispose(made)
error(failure.code, failure.message)
return made
mesh_dispose(made)
output.warning = "The operation would collapse faces; the input passes through"
output.selection.close()
output.selection = try BitsBuilder.zeros(0)
return try mesh_share(source)
if output.built:
# Faces the kernel made degenerate (a bridge between coplanar loops,
# say): nothing sensible to show, so the input passes through.
let built: Mesh*? = output.builder.finish(source) catch failure:
if failure.code != errors.invalid: error(failure.code, failure.message)
output.warning = "The operation would make degenerate faces; the input passes through"
recover none
if let made = built:
# Meshes keep faces without an area; a verb making new ones
# still refuses.
if degenerate_faces(made) <= degenerate_faces(source):
if output.trail_key != 0:
set_trail(made, output.trail_key, output.trail_points.view()) catch failure:
mesh_dispose(made)
error(failure.code, failure.message)
return made
mesh_dispose(made)
output.warning = "The operation would make degenerate faces; the input passes through"
output.selection.close()
output.selection = try BitsBuilder.zeros(0)
output.builder.selected_edges.clear()
return try mesh_share(source)
if not output.positions.is_empty():
let base = mesh_positions_id(source)
if let previous = over:
if source.repositions(previous):
# The points that changed since the last frame: among those it
# moved and those this one moved when it says what it moved
# (a drag: O(moved)), else found by comparing every point.
var moved: u32[]
if let trail = trail_from(previous, base): moved = try changed_among(previous.point_span(), output.positions.view(), trail, output.moved.view())
else: moved = try changed_points(previous.point_span(), output.positions.view())
defer free(moved) in memory.heap
let made = try moved_storage(previous, output.positions, moved)
if (try degenerate_around(made, moved)) <= (try degenerate_around(previous, moved)):
set_trail(made, base, output.moved.view()) catch failure:
mesh_dispose(made)
error(failure.code, failure.message)
return made
mesh_dispose(made)
# Meshes keep faces without an area, but a modeling verb that collapses
# faces (points moved onto each other) has nothing sensible to make: the
# input passes through with a warning, as for built faces above.
let moved: Mesh*? = moved_storage(source, output.positions, output.moved.view()) catch failure:
if failure.code != errors.invalid: error(failure.code, failure.message)
output.warning = "The operation would collapse faces; the input passes through"
recover none
if let made = moved:
# Only the faces round the moved points can have lost their area.
if (try degenerate_around(made, output.moved.view())) <= (try degenerate_around(source, output.moved.view())):
set_trail(made, base, output.moved.view()) catch failure:
mesh_dispose(made)
error(failure.code, failure.message)
return made
mesh_dispose(made)
output.warning = "The operation would collapse faces; the input passes through"
return try mesh_share(source)
## The points in `last` or `now` (either order, repeats allowed) whose
## stored positions differ between `previous` and `next`, ascending; the
## caller frees the list.
func changed_among(previous: const Float3[], next: const Float3[], last: const u32[], now: const u32[]) -> u32[]!:
let all = try new u32[last.length + now.length] --- in memory.heap
defer free(all) in memory.heap
memory.copy(all[..<last.length], last, last.length)
memory.copy(all[last.length..], now, now.length)
sort.stable(all, point_before)
var count: usize = 0
for at in 0..<all.length:
let point = all[at]
if at > 0 and all[at - 1] == point: continue
let a = previous[(usize)point]
let b = next[(usize)point]
if a.x != b.x or a.y != b.y or a.z != b.z:
all[count] = point
count += 1
let moved = try new u32[count] --- in memory.heap
memory.copy(moved, all[..<count], count)
return moved
func point_before(a: u32, b: u32) -> bool:
return a < b
## The output selection as the edges between the builder's selected point
## pairs.
func select_edges(product: const Mesh*, output: VerbOutput*) -> !:
var bits = try BitsBuilder.zeros((usize)(try product.edge_count()))
errdefer bits.close()
_ = try edge_bits_from_pairs(product, output.builder.selected_edges.view(), &bits)
output.selection.close()
output.selection = bits
output.selection_domain = Domain.edge
## Replace any `.selection` group of `mesh` with `bits` on `domain`. No
## bits at all is a kernel that selected nothing; any other length must be
## the domain's.
func mark_selection(mesh: Mesh*, bits: Column[u64]*, domain: Domain) -> !:
let domains: Domain[4] = [Domain.point, Domain.corner, Domain.face, Domain.edge]
for other in domains: try remove_attribute(mesh, ".selection", other)
let count = try mesh.domain_size(domain)
if bits.count() == 0:
var empty = try BitsBuilder.zeros(count)
bits.release()
*bits = empty.finish()
if bits.count() != (count + 63) // 64: trap("a verb's selection does not cover its domain")
try put_attribute(mesh, try Attribute.group_of(".selection", domain, count, bits.view()))
## How many faces round points `points` have no area (a zero normal),
## counting a face once per point it is round.
func degenerate_around(mesh: const Mesh*, points: const u32[]) -> usize!:
let around = try mesh.point_face_span()
let normals = mesh.face_normal_span()
var count: usize = 0
for point in points:
for slot in (usize)around.0[(usize)point]..<(usize)around.0[(usize)point + 1]:
let normal = normals[(usize)around.1[slot]]
if normal.x == 0.0 and normal.y == 0.0 and normal.z == 0.0: count += 1
return count
## How many faces have no area (a zero normal).
func degenerate_faces(mesh: const Mesh*) -> usize:
var count: usize = 0
for normal in mesh.face_normal_span():
if normal.x == 0.0 and normal.y == 0.0 and normal.z == 0.0: count += 1
return count