Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.7

0.11.7 / src / node_evaluation.luc

## Operator dispatch only: modeling nodes run luce-geocore verbs; the rest
## call whole-mesh Base kernels.
from luce_geocore import geocore
from luce_geocore.geocore import AttributeKernels, Groups, Verbs, MaterialAssignment
import node_catalog
from edit_operations import node_numbers, second_of
from luce_ui import ui
from luce_obj.obj import Obj
from luce_step.step import Step
from luce_cad.model import CadTolerances
from luce_cad.modeling import CadModeling
from geometry_data import GeometryData, cad_data
from file_identity import file_identity
from usd_nodes import load_usd
from fbx_nodes import load_fbx
from ply_nodes import is_ply_path, load_ply
from spz_nodes import is_spz_path, load_spz
from script_hosts import ScriptHosts

## What a STEP file node does with a file looser than the project's
## positional tolerance (its Tolerances row, value slot 0).
pub let tolerances_ask = 0.0
pub let tolerances_keep = 1.0
pub let tolerances_adopt = 2.0

pub func load_geometry(path: str, option: float = 0.0, tolerances: CadTolerances? = none) -> GeometryData!:
    if path == "":
        error(ui.invalid, "Choose an external geometry file")
    if path.lower().ends_with(".obj"):
        return GeometryData(Obj.load(path))
    if is_ply_path(path):
        return load_ply(path)
    if is_spz_path(path):
        return load_spz(path)
    if path.lower().ends_with(".fbx"):
        return load_fbx(path, [0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0])
    if path.lower().ends_with(".step") or path.lower().ends_with(".stp"):
        return step_data(path, option, tolerances else CadTolerances())
    error(ui.invalid, "Unsupported geometry file extension")

## A STEP file's bodies under the project's `tolerances`: measured, and
## with `option` tolerances_adopt healed to them where their faces meet. A
## file looser than the positional tolerance says so on the node: what
## Ask leaves to choose, what Adopt could not heal.
func step_data(path: str, option: float, tolerances: CadTolerances) -> GeometryData!:
    let read = Step.load_model(path, 0.0, tolerances)
    let model = CadModeling.rechecked(read, tolerances, option == tolerances_adopt)
    let report = CadModeling.tolerance_report(model)
    let data = cad_data(model)
    if report.tolerant_edges == 0:
        return data
    let worst = f"{fixed_mm(report.worst)} mm"
    let edges = f"{report.tolerant_edges} edge{"" if report.tolerant_edges == 1 else "s"}"
    if option == tolerances_ask:
        data.warning = f"{edges} lie up to {worst} off their faces, looser than the project's {fixed_mm(tolerances.positional)} mm: choose Keep the file's or Adopt the scene's under Tolerances"
    elif option == tolerances_adopt:
        data.warning = f"{edges} could not be healed to the project's tolerance and stay tolerant, up to {worst}"
    return data

## A length in millimeters with at most six decimals, trailing zeros off.
pub func fixed_mm(value: float) -> str:
    var text = f"{value:.6f}"
    while text.ends_with("0") and text.contains("."):
        text = text[..<text.length - 1]
    if text.ends_with("."):
        text = text[..<text.length - 1]
    return text

## Process-lifetime import caches, so undo, reload and project reopen reuse
## parsed files and tessellations. Files are keyed by path, size, mtime,
## content hash, tolerance and the project's CAD tolerances; tessellations by the parsed model's key and
## options. A few recent entries each: they hold whole assemblies.
pub class SourceCache:
    let files: list[(int, GeometryData)]
    let tessellations: list[(int, GeometryData)]
    pub var hits: int = 0
    ## The Script nodes' builds and waiting processes, and the project's
    ## folder their relative files are read from.
    pub let scripts: ScriptHosts
    pub var folder: str = ""

    pub func init(self):
        self.files = []
        self.tessellations = []
        self.scripts = ScriptHosts()

    pub func load(self, path: str, tolerance: float, tolerances: CadTolerances) -> GeometryData!:
        let identity = file_identity(path) catch failure:
            # Let the loader report the missing or unreadable file.
            return load_geometry(path, tolerance, tolerances)
        let key = nonzero((path, tolerance, tolerances.positional, tolerances.fit, tolerances.tangent, tolerances.curvature, identity).hash())
        if let found = self.find(self.files, key):
            return found
        let data = load_geometry(path, tolerance, tolerances)
        data.origin = key
        remember(self.files, key, data)
        return data

    ## A USD File node's stage, keyed by the file and every USD option.
    pub func load_usd(self, path: str, values: list[float], texts: list[str]) -> GeometryData!:
        let identity = file_identity(path) catch failure:
            return load_usd(path, values, texts)
        let key = nonzero((path, "usd", values, texts[1], texts[2], identity).hash())
        if let found = self.find(self.files, key):
            return found
        let data = load_usd(path, values, texts)
        data.origin = key
        remember(self.files, key, data)
        return data

    ## An FBX File node's scene, keyed by the file and its FBX options.
    pub func load_fbx(self, path: str, values: list[float]) -> GeometryData!:
        let identity = file_identity(path) catch failure:
            return load_fbx(path, values)
        let key = nonzero((path, "fbx", values, identity).hash())
        if let found = self.find(self.files, key):
            return found
        let data = load_fbx(path, values)
        data.origin = key
        remember(self.files, key, data)
        return data

    pub func tessellated(self, data: GeometryData, divisions: int, edge_size: float, progress: func(float) -> unit!? = none) -> GeometryData!:
        if data.origin == 0:
            return data.tessellated(divisions, edge_size, progress)
        let key = nonzero((data.origin, divisions, edge_size).hash())
        if let found = self.find(self.tessellations, key):
            return found
        let result = data.tessellated(divisions, edge_size, progress)
        remember(self.tessellations, key, result)
        return result

    func find(self, entries: list[(int, GeometryData)], key: int) -> GeometryData?:
        for at in 0..<entries.length:
            let (stored, data) = entries[at]
            if stored == key:
                # Most recently used entries move to the end.
                entries.append(entries.remove_at(at))
                self.hits += 1
                return data
        return none

func remember(entries: list[(int, GeometryData)], key: int, data: GeometryData):
    entries.append((key, data))
    while entries.length > 4:
        _ = entries.remove_at(0)

func nonzero(value: int) -> int:
    return value if value != 0 else 1

## A modeling node's verb run: the mesh, and a warning when the verb passed
## its input through or the group named elements that do not exist.
## A verb of a reference surface (Shrinkwrap) reads `reference`, its
## second input's mesh.
pub func evaluate_verb(kind: str, v: list[float], text: list[str], mesh: geocore.Mesh, reference: geocore.Mesh? = none) -> GeometryData!:
    let result = Verbs.run(kind, mesh, text[0], int(v[node_catalog.group_type_slot]), node_numbers(kind, v), 0, false, second_of(kind, text, true), reference)
    let data = GeometryData(result.mesh())
    data.warning = result.warning()
    if data.warning == "" and result.misses() > 0:
        data.warning = f"{result.misses()} group numbers name no element"
    return data

## The mesh part of an attribute node (geometry_nodes.luc runs the rest).
pub func evaluate_operator(kind: str, v: list[float], text: list[str], input: geocore.Mesh, second: geocore.Mesh?) -> geocore.Mesh!:
    var mesh = input
    if kind == "AttributeDelete":
        return mesh.without_attribute(text[1], int(v[0]))
    if kind == "AttributeRename":
        return mesh.renamed_attribute(text[1], text[2], int(v[0]))
    if kind == "AttributePromote":
        return mesh.promoted_attribute(text[1], int(v[0]), int(v[1]))
    # Attribute nodes run whole-mesh Base kernels: one new column each.
    if kind == "Selection Group":
        return Groups.with_group(mesh, text[1], int(v[0]), text[0] if text[0].trim() != "" else "*")
    if kind == "Color":
        return AttributeKernels.filled(mesh, "Cd", 0, [v[0], v[1], v[2]], false, false, 0.0)
    # A text attribute on the group's faces, as Assign Material binds them.
    if kind == "Name":
        return MaterialAssignment.faces(mesh, text[0].trim(), "name", text[1].trim())
    if kind in ["AttributeCreate", "AttributeRandomize"]:
        let width = int(v[1])
        let values: list[float] = []
        for component in 0..<width:
            values.append(v[3 + component])
        return AttributeKernels.filled(mesh, text[1], int(v[0]), values, v[2] != 0.0, kind == "AttributeRandomize", v[7])
    if kind == "UVProject":
        return AttributeKernels.uv_project(mesh, v[0])
    if kind == "Normal":
        return AttributeKernels.normals(mesh, 2 if int(v[0]) == 2 else 0)
    if kind == "Measure":
        return AttributeKernels.face_areas(mesh)
    error(ui.invalid, "Operator has no evaluator")