Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.8

0.11.8 / src / geometry_data.luc

## A node's cooked result: a thin wrapper around luce-geocore's GeometrySet,
## which holds its mesh, CAD models (luce-cad's family), point cloud and
## instances. The set is immutable and shares its arrays; what this class
## adds is Luce-side caching: the CAD preview meshes, and wrappers of the
## instances' sets so their previews persist too. CAD stays analytic until a
## Tessellate node.
from luce_geocore.geocore import Mesh, GeometrySet, Fields, InstanceBuilder
from luce_3d.graphics import Vector3, Matrix4
from luce_cad.model import CadModel
from luce_cad.cad_geometry import CadGeometry
from luce_cad.cad_curves import CadCurves
from luce_cad.measure import CadCheck
from cad_preview import CadPreview, tessellation_warning

pub class GeometryData:
    pub let geometry: GeometrySet
    ## The set's own mesh (not its instances').
    pub let mesh: Mesh?
    ## Content key of the import this data was parsed from (0: derived data).
    pub var origin: int = 0
    ## What the node that made this data wants the user to know, although it
    ## succeeded ("nothing to fill; the input passes through").
    pub var warning: str = ""
    ## What a Code node's printf calls said (capped), for its console.
    pub var console: str = ""
    ## A Sketch's state for its editor (sketch_node.SketchState, as text).
    pub var sketch_state: str = ""
    ## What an Auto setting chose ("Cut" for an Extrude's Auto operation).
    pub var automatic: str = ""
    ## Where a CAD feature's viewport handles stand (feature_handles.luc's
    ## text: one handle a line), made by its cook.
    pub var handles: str = ""
    ## A Check node's measurements (luce-cad's CadCheck): the lines the
    ## viewport draws over the result, and its one-line report, which
    ## stands for the description.
    pub var check: CadCheck? = none
    pub var report: str = ""
    ## A mesh the viewport shades in place of this data's bodies, which stay
    ## what the data is (picked, measured, passed on): a Check node's
    ## deviation colors over its CAD body, as Alias's Deviation Map overlays
    ## the surfaces it measures.
    pub var tint: Mesh? = none
    ## An Edit node's pick geometry for this data (made once), and the group
    ## naming what its last step created on it ("" none), which the pick
    ## geometry carries as `.selection`.
    pub var pick_cache: Mesh? = none
    pub var created: str = ""
    ## Edit CAD's Align steps so far, each as align_ops.constraint wrote
    ## it: a later CV drag on rows one of them set runs it again (the
    ## owner's rule for aligned rows).
    pub var aligns: list[str] = []
    var preview_cache: CadPreview? = none
    ## Wrappers of the instances' sets, made once, in instance order.
    var children: list[GeometryData]? = none
    ## The surface preview of the set's SDF and volume, made once.
    var field_cache: Mesh? = none
    var field_checked: bool = false
    var field_quick: bool = false

    pub func init(self, mesh: Mesh? = none, geometry: GeometrySet? = none) -> unit!:
        var chosen = geometry else GeometrySet()
        if geometry == none:
            if let polygons = mesh:
                chosen = GeometrySet.of_mesh(polygons)
        self.geometry = chosen
        self.mesh = chosen.mesh() if geometry != none else mesh

    pub func models(self) -> list[CadModel]!:
        let result: list[CadModel] = []
        for index in 0..<CadGeometry.model_count(self.geometry):
            result.append(CadGeometry.model(self.geometry, index))
        return result

    ## What this data's CAD edge lines depend on (0: unknown, or no CAD):
    ## its models' edges and placements, and its instances' placements.
    pub func edges_key(self) -> int!:
        if not self.has_cad() and self.instance_count() == 0:
            return 0
        var key = "cad-edges".hash()
        for model in self.models():
            let part = model.edges_key()
            if part == 0:
                return 0
            key = (key, part).hash()
        for index in 0..<self.instance_count():
            if not self.instance_visible(index):
                continue
            let child = self.instance(index).edges_key()
            if child == 0:
                return 0
            key = (key, child, self.instance_translation(index), self.instance_rotation(index), self.instance_scale(index)).hash()
        return key

    pub func has_cad(self) -> bool!:
        return CadGeometry.model_count(self.geometry) > 0

    ## Whether the set holds CAD curves (luce-cad's cad_curves objects).
    pub func has_curves(self) -> bool!:
        return CadCurves.count(self.geometry) > 0

    ## What the viewport draws for the set's own SDF and level sets: their
    ## surface (luce-geocore keeps it with the component), or none. `quick`
    ## (a drag's frames) takes a coarse SDF surface; a full request after one
    ## replaces it.
    pub func field_preview(self, quick: bool = false) -> Mesh?!:
        if not self.field_checked or (self.field_quick and not quick):
            self.field_checked = true
            self.field_quick = quick
            if Fields.present(self.geometry):
                self.field_cache = Fields.preview(self.geometry, quick)
        return self.field_cache

    # -- Instances.

    pub func instance_count(self) -> int:
        return self.geometry.instance_count()

    ## Instance `index`'s data; the same object on every call.
    pub func instance(self, index: int) -> GeometryData!:
        if self.children == none:
            let made: list[GeometryData] = []
            for at in 0..<self.geometry.instance_count():
                made.append(GeometryData(geometry = self.geometry.instance(at)))
            self.children = made
        return (self.children else [])[index]

    pub func instance_translation(self, index: int) -> Vector3!:
        return self.geometry.instance_translation(index)
    ## XYZ radians.
    pub func instance_rotation(self, index: int) -> Vector3!:
        return self.geometry.instance_rotation(index)
    pub func instance_scale(self, index: int) -> Vector3!:
        return self.geometry.instance_scale(index)
    pub func instance_visible(self, index: int) -> bool!:
        return self.geometry.instance_visible(index)
    pub func instance_matrix(self, index: int) -> Matrix4!:
        return Matrix4.compose(self.geometry.instance_translation(index), self.geometry.instance_rotation(index), self.geometry.instance_scale(index))

    ## This data with `child` added as an instance; `child` keeps serving as
    ## the new instance's data (and its preview).
    pub func with_instance(self, child: GeometryData, translation: Vector3? = none, rotation: Vector3? = none, scale: Vector3? = none, visible: bool = true) -> GeometryData!:
        let result = GeometryData(geometry = self.geometry.with_instance(child.geometry, translation else Vector3(), rotation else Vector3(), scale else Vector3(1.0, 1.0, 1.0), visible))
        let kept: list[GeometryData] = []
        for index in 0..<self.instance_count():
            kept.append(self.instance(index))
        kept.append(child)
        result.children = kept
        return result

    ## Every one of `children` added as an instance, in order, in one pass
    ## (luce-geocore's InstanceBuilder: no copy of the growing collection per
    ## child); each child keeps serving as its instance's data (and preview).
    pub func with_instances(self, children: list[GeometryData]) -> GeometryData!:
        if children.length == 0:
            return self
        let builder = InstanceBuilder.of(self.geometry)
        let one = Vector3(1.0, 1.0, 1.0)
        for child in children:
            builder.add(child.geometry, Vector3(), Vector3(), one)
        let result = GeometryData(geometry = builder.finish())
        let kept: list[GeometryData] = []
        for index in 0..<self.instance_count():
            kept.append(self.instance(index))
        for child in children:
            kept.append(child)
        result.children = kept
        return result

    ## `copies`, this data placed `count` times by luce-geocore in one pass
    ## (GeometrySet.copies_at_points, copies_along), each copy's instances
    ## wrapped in one instance as `transformed` wraps them: the wrappers keep
    ## this data's instance wrappers (and their previews).
    pub func with_copies(self, copies: GeometrySet, count: int) -> GeometryData!:
        let result = GeometryData(geometry = copies)
        if self.instance_count() > 0:
            let kept: list[GeometryData] = []
            for index in 0..<self.instance_count():
                kept.append(self.instance(index))
            let wrapped: list[GeometryData] = []
            for copy in 0..<count:
                let inner = GeometryData(geometry = copies.instance(copy))
                inner.children = kept
                wrapped.append(inner)
            result.children = wrapped
        return result

    # -- Whole-data operations.

    pub func paths(self) -> list[str]!:
        let text = self.geometry.paths()
        return [] if text == "" else text.split("\n")

    ## The paths that name CAD curves (the outliner draws them as curves).
    pub func curve_paths(self) -> list[str]!:
        let found: list[str] = []
        if not self.has_curves():
            return found
        for index in 0..<CadCurves.count(self.geometry):
            found.append(CadCurves.name(self.geometry, index))
        return found

    ## One mesh of every polygon, instances baked; fails on CAD (Tessellate
    ## first).
    pub func require_mesh(self) -> Mesh!:
        if self.instance_count() == 0:
            if let mesh = self.mesh:
                if not self.has_cad(): return mesh
        return self.geometry.realized()

    ## What mesh operators work on: the set's own mesh; without one, the
    ## polygons of its instances realized (CAD fails and asks for a
    ## Tessellate node, as before). None when there are no polygons: the other
    ## components pass mesh operators through, as in Houdini.
    pub func operand(self) -> Mesh?!:
        if let mesh = self.mesh:
            return mesh
        if self.instance_count() > 0 or self.has_cad():
            return self.require_mesh()
        return none

    ## This data with `mesh` in place of what `operand` gave: every other
    ## component kept (shared); instances realized into it go.
    pub func with_operand(self, mesh: Mesh) -> GeometryData!:
        var geometry = self.geometry.with_mesh(mesh)
        if self.mesh == none and self.instance_count() > 0:
            geometry = geometry.without("instances")
        return GeometryData(geometry = geometry)

    ## This data with `geometry` in its place, which must hold the same
    ## instances and CAD (it only gained cameras or lights): their wrappers
    ## and preview are kept.
    pub func with_geometry(self, geometry: GeometrySet) -> GeometryData!:
        let result = GeometryData(geometry = geometry)
        result.children = self.children
        result.preview_cache = self.preview_cache
        return result

    ## This data unchanged, with a warning for the node that passed it on
    ## (and what it tells a sketch editor: the same set's sketches).
    pub func passed(self, warning: str) -> GeometryData!:
        let result = GeometryData(geometry = self.geometry)
        result.warning = warning
        result.sketch_state = self.sketch_state
        return result

    ## The CAD preview, made once. `quick` (a drag's frames) lets models with
    ## moved control vertices show their quick preview; false asks for full
    ## tessellations (replacing a quick preview); none takes what is made.
    ## `divisions` asks for that fineness (none: what is made, else 16).
    pub func preview(self, progress: func(float) -> unit!? = none, quick: bool? = none, divisions: int? = none) -> CadPreview!:
        let wanted = quick else false
        if let cached = self.preview_cache:
            let same = divisions == none or divisions == cached.divisions
            if same and (quick == none or wanted or not cached.quick):
                return cached
        let result = CadPreview(self.models(), progress = progress, quick = wanted, divisions = divisions else 16)
        self.preview_cache = result
        return result

    pub func merged(self, other: GeometryData) -> GeometryData!:
        let result = GeometryData(geometry = self.geometry.merged(other.geometry))
        # Instances of both keep their wrappers (and previews).
        if self.instance_count() + other.instance_count() > 0:
            let kept: list[GeometryData] = []
            for index in 0..<self.instance_count():
                kept.append(self.instance(index))
            for index in 0..<other.instance_count():
                kept.append(other.instance(index))
            result.children = kept
        return result

    ## Placed by translation, rotation (XYZ radians) and scale. Instances are
    ## wrapped in one instance under the placement; a CAD preview is placed
    ## rather than remade.
    pub func transformed(self, translation: Vector3, rotation: Vector3, scale: Vector3) -> GeometryData!:
        if Matrix4.compose(translation, rotation, scale).is_identity():
            return self
        let result = GeometryData(geometry = self.geometry.transformed(translation, rotation, scale))
        if self.instance_count() > 0:
            let inner = GeometryData(geometry = result.geometry.instance(0))
            let kept: list[GeometryData] = []
            for index in 0..<self.instance_count():
                kept.append(self.instance(index))
            inner.children = kept
            result.children = [inner]
        if let cached = self.preview_cache:
            result.preview_cache = CadPreview([], cached, Matrix4.compose(translation, rotation, scale))
        return result

    pub func tessellated(self, divisions: int, edge_size: float = 0.0, progress: func(float) -> unit!? = none) -> GeometryData!:
        let result = GeometryData(geometry = CadGeometry.tessellated(self.geometry, divisions, edge_size, progress))
        if let mesh = result.mesh:
            result.warning = tessellation_warning(mesh)
        return result

    ## Elements whose object path matches `expression` kept, or removed.
    pub func blasted(self, expression: str, keep: bool) -> GeometryData!:
        return GeometryData(geometry = self.geometry.blasted(expression, keep))

    ## Resident bytes for the worker's result store: shared arrays count once
    ## within a result, and CAD previews on top.
    pub func footprint(self) -> int!:
        var total = 256 + self.geometry.footprint()
        if let preview = self.preview_cache:
            for mesh in preview.meshes:
                total += 256 + mesh.column_bytes()
            total += preview.point_count() * 24
        for child in self.children else []:
            if child.preview_cache != none: total += child.footprint()
        return total

    pub func description(self) -> str!:
        if self.report != "":
            return self.report
        return self.geometry.description()

## The world direction toward the viewport's key light (the workspace's
## directional light): fog volumes are shadowed for it.
pub func key_light() -> Vector3:
    return Vector3(3.0, 5.0, 2.0)

## Analytic CAD, as a File node imports it.
pub func cad_data(model: CadModel) -> GeometryData!:
    return GeometryData(geometry = CadGeometry.of_model(model))