Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-geocore

Source of release 0.7.8

0.7.8 / src / verbs / bridge.lucb

## Bridge: faces joining pairs of boundary loops or runs, after Blender's
## Bridge Edge Loops and Houdini's PolyBridge. The loops are the group's
## boundary chains: with a second pick, each chain of the first is paired
## with the nearest chain of the second; else the group's chains pair
## among themselves, each with the nearest other of the same kind (loops
## with loops, runs with runs). Faces as the first pick bridge their
## regions' outlines and go, as Blender's Bridge does with faces selected
## (two faces of a box make a tunnel). Chains with as many edges bridge
## with Cuts + 1 rows of quads, shaped as bridge_rows.lucb says
## (Interpolation, Smoothness, Profile); others zip together with
## triangles, by distance along each chain. A closed pair starts where the
## second loop comes nearest the first's start, turned by Twist. With Merge
## the two loops weld into one at Merge factor of the way between them. The
## bridge faces are the output selection (the merged edges with Merge).

let bridge_parms: ParmSpec[8] = [
    ParmSpec("Cuts", ParmKind.integer, 0.0, 0.0, 64.0, 1, "", "Loops of points across each bridge between its two ends (chains with as many edges)."),
    ParmSpec("Twist", ParmKind.integer, 0.0, -1000.0, 1000.0, 1, "", "Turn where a closed pair's second loop starts, by this many points."),
    ParmSpec("Interpolation", ParmKind.menu, 1.0, 0.0, 2.0, 1, "Linear|Blend path|Blend surface", "How the cuts run: straight across, along a curve leaving each loop square to its plane, or each along a curve leaving the faces beside it."),
    ParmSpec("Smoothness", ParmKind.number, 1.0, 0.0, 4.0, 1, "", "How far the blend curves keep their loops' directions.", 2.0),
    ParmSpec("Profile", ParmKind.number, 0.0, -2.0, 2.0, 1, "", "Swell (or pinch, below 0) the cuts away from the bridge's middle line."),
    ParmSpec("Profile shape", ParmKind.menu, 0.0, 0.0, 5.0, 1, "Smooth|Sphere|Root|Sharp|Linear|Inverse square", "How the swell grows from the ends to the middle.", more = true),
    ParmSpec("Merge", ParmKind.toggle, 0.0, 0.0, 1.0, 1, "", "Weld the two loops into one instead of bridging them (chains with as many edges).", more = true),
    ParmSpec("Merge factor", ParmKind.number, 0.5, 0.0, 1.0, 1, "", "Where merged loops meet: 0 at the first, 1 at the second.", more = true)]

let bridge_picks: PickSpec[2] = [
    PickSpec("Boundary edges", "edges faces", "Select two boundary loops or runs of edges (or faces whose outlines to bridge)"),
    PickSpec("Second loop", "edges", "Pick the loop to bridge to, then Enter")]

## Faces bridge their regions' outlines.
let bridge_also: Domain[1] = [Domain.face]

func bridge_verb() -> Verb:
    return Verb("Bridge", "Modeling", "Join pairs of boundary loops or runs with faces, or weld them", Domain.edge, true, bridge_parms, true, cook_bridge, false, bridge_also, section = "Modify", family = "Fill", icon = "bridge", picks = bridge_picks, drag = 4, drag_mode = "amount", wheel = 0, wants = bridge_wants)

## Whether the first pick alone has fewer than two chains to pair.
func bridge_wants(input: const VerbInput*) -> bool!:
    let topology = try Topology.of(input.mesh)
    var gone = try BitsBuilder.zeros(topology.faces())
    defer gone.close()
    var edges = try BitsBuilder.zeros(topology.edges())
    defer edges.close()
    if input.domain == Domain.face:
        gone.unite(input.group)
        try region_outlines(&topology, gone.view(), &edges)
    else:
        edges.unite(input.group)
    var chains = Chains()
    defer chains.close()
    try find_chains(&topology, edges.view(), &chains, gone.view())
    return chains.count() < 2

## The group's boundary chains: corners (each the one face corner of a
## boundary edge, in chain order) and where each chain starts.
struct Chains:
    var corners: Growing[i32]
    var starts: Growing[u32]
    var closed: Growing[u8]
    ## Per chain: whether it came from the second pick.
    var second: Growing[u8]

    func init():
        self.corners = Growing[i32]()
        self.starts = Growing[u32]()
        self.closed = Growing[u8]()
        self.second = Growing[u8]()

    func count() -> usize:
        return self.closed.count

    func size(chain: usize) -> usize:
        return (usize)(self.starts.items[chain + 1] - self.starts.items[chain])

    func close():
        self.corners.close()
        self.starts.close()
        self.closed.close()
        self.second.close()

func cook_bridge(input: const VerbInput*, output: VerbOutput*) -> !:
    var settings = try BridgeSettings.of(input.parms)
    let mesh = input.mesh
    let topology = try Topology.of(mesh)
    # Faces picked: their regions' outlines, the faces gone.
    var gone = try BitsBuilder.zeros(topology.faces())
    defer gone.close()
    var edges = try BitsBuilder.zeros(topology.edges())
    defer edges.close()
    if input.domain == Domain.face:
        gone.unite(input.group)
        try region_outlines(&topology, gone.view(), &edges)
    else:
        edges.unite(input.group)
    var chains = Chains()
    defer chains.close()
    try find_chains(&topology, edges.view(), &chains, gone.view())
    let first_count = chains.count()
    if let second = input.second:
        try find_chains(&topology, second, &chains, gone.view())
        for chain in first_count..<chains.count(): chains.second.items[chain] = 1
    let count = chains.count()
    let partner = try new i32[count] --- in memory.heap
    defer free(partner) in memory.heap
    let pairs = try pair_chains(mesh, &topology, &chains, partner[..<count])
    if pairs == 0:
        output.warning = "Bridge needs two boundary loops or runs (a second pick, or two in the group); the input passes through"
        return
    var builder = &output.builder
    try builder.begin(mesh)
    try builder.copy_points(mesh)
    output.built = true
    var run: usize = 0
    for face in 0..<topology.faces():
        if not gone.view().get(face): continue
        try builder.copy_faces(mesh, run, face)
        run = face + 1
    try builder.copy_faces(mesh, run, topology.faces())
    let first = builder.face_count()
    if settings.merge:
        try merge_pairs(mesh, &topology, &chains, partner[..<count], &settings, builder)
        return
    for chain in 0..<count:
        if partner[chain] > (i32)chain: try bridge_pair(mesh, &topology, &chains, chain, (usize)partner[chain], &settings, builder)
    output.selection = try BitsBuilder.zeros(builder.face_count())
    output.selection.set_range(first, builder.face_count())
    output.selection_domain = Domain.face
    if gone.view().population() > 0: try builder.drop_unused_points()
    if pairs * 2 < count: output.warning = "A boundary loop or run had no partner and was left open"
    elif settings.zipped > 0: output.warning = "Pairs of different lengths were zipped with triangles; Cuts and Profile need loops of as many edges"

## Each chain's partner (-1 none): with chains from a second pick, each
## first-pick chain takes the nearest second-pick chain of its kind, else
## each chain the nearest unpaired one of its kind. How many pairs.
func pair_chains(mesh: const Mesh*, topology: const Topology*, chains: const Chains*, partner: i32[]) -> usize!:
    let count = chains.count()
    var any_second = false
    for chain in 0..<count:
        partner[chain] = -1
        if chains.second.items[chain] != 0: any_second = true
    var pairs: usize = 0
    for chain in 0..<count:
        if partner[chain] >= 0 or (any_second and chains.second.items[chain] != 0): continue
        var best: i64 = -1
        var nearest = 0.0
        let here = chain_center(mesh, topology, chains, chain)
        for other in 0..<count:
            if other == chain or partner[other] >= 0 or chains.closed.items[other] != chains.closed.items[chain]: continue
            if any_second and chains.second.items[other] == 0: continue
            if not any_second and other < chain: continue
            let distance = chain_center(mesh, topology, chains, other).subtract(here).length()
            if best < 0 or distance < nearest:
                best = (i64)other
                nearest = distance
        if best < 0: continue
        partner[chain] = (i32)best
        partner[(usize)best] = (i32)chain
        pairs += 1
    return pairs

## The outline of faces `faces`: edges with exactly one face of the set.
func region_outlines(topology: const Topology*, faces: Bits, edges: BitsBuilder*) -> !:
    for edge in 0..<topology.edges():
        var inside: usize = 0
        for at in (usize)topology.edge_corner_offsets[edge]..<(usize)topology.edge_corner_offsets[edge + 1]:
            if faces.get((usize)topology.corner_faces[(usize)topology.edge_corners[at]]): inside += 1
        if inside == 1: edges.set(edge)

## The one corner of a face not `gone` that uses `edge`, or -1 (none, or
## several: not a boundary).
func open_corner(topology: const Topology*, edge: usize, gone: Bits) -> i32:
    var found: i32 = -1
    for at in (usize)topology.edge_corner_offsets[edge]..<(usize)topology.edge_corner_offsets[edge + 1]:
        let corner = topology.edge_corners[at]
        if gone.get((usize)topology.corner_faces[(usize)corner]): continue
        if found >= 0: return -1
        found = corner
    return found

## Chains of `group`'s boundary edges (one face left once the `gone` faces
## go): each point's boundary edge leaving it continues the chain; runs
## start where none arrives. Points where two boundary edges of the group
## leave are pinches, which no chain crosses. Chains are added to `chains`.
func find_chains(topology: const Topology*, group: Bits, chains: Chains*, gone: Bits) -> !:
    let points = topology.points
    let leaving = try new i32[points] --- in memory.heap
    defer free(leaving) in memory.heap
    let arriving = try new u8[points] --- in memory.heap
    defer free(arriving) in memory.heap
    for at in 0..<points:
        leaving[at] = -1
        arriving[at] = 0
    for edge in 0..<topology.edges():
        if not group.get(edge): continue
        let corner = open_corner(topology, edge, gone)
        if corner < 0: continue
        let point = (usize)topology.corners[(usize)corner]
        leaving[point] = corner if leaving[point] == -1 else -2
        let end = (usize)topology.corners[topology.next((usize)corner)]
        if arriving[end] < 255: arriving[end] += 1
    var used = try BitsBuilder.zeros(topology.corners.length)
    defer used.close()
    if chains.starts.count == 0: try chains.starts.push(0)
    # Open runs first (from points nothing arrives at), then closed loops.
    for pass in 0..<(usize)2:
        for point in 0..<points:
            let corner = leaving[point]
            if corner < 0 or used.view().get((usize)corner): continue
            if pass == 0 and arriving[point] != 0: continue
            let begin = chains.corners.count
            var at = corner
            var closed = false
            while at >= 0 and not used.view().get((usize)at):
                used.set((usize)at)
                try chains.corners.push(at)
                let next = leaving[(usize)topology.corners[topology.next((usize)at)]]
                if next == corner:
                    closed = true
                    break
                at = next
            if pass == 1 and not closed:
                chains.corners.count = begin
                continue
            try chains.starts.push((u32)chains.corners.count)
            try chains.closed.push(1 if closed else 0)
            try chains.second.push(0)

## Point `index` of a chain (its corners' points, then an open run's end)
## and the face corner at it.
func chain_point(topology: const Topology*, chains: const Chains*, chain: usize, index: usize) -> (i32, i32):
    let start = (usize)chains.starts.items[chain]
    let size = chains.size(chain)
    if index < size:
        let corner = chains.corners.items[start + index]
        return (topology.corners[(usize)corner], corner)
    let last = topology.next((usize)chains.corners.items[start + size - 1])
    return (topology.corners[last], (i32)last)

func chain_center(mesh: const Mesh*, topology: const Topology*, chains: const Chains*, chain: usize) -> Vector3:
    let size = chains.size(chain)
    var sum = Vector3()
    for index in 0..<size:
        let (point, _) = chain_point(topology, chains, chain, index)
        sum = sum.add(point_of(mesh, point))
    return sum.multiply_scalar(1.0 / (f64)size)