Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-image

Source of release 0.45.0

0.45.0 / src / canvas / shape_layers.lucb

#==============================================================================================
#
#   canvas/shape_layers - Shapes that stay shapes
#
#   DESCRIPTION:
#       A rectangle (with rounded corners), an ellipse, a line, a regular polygon or a pen
#       path kept as what it is — its box, its fill and stroke, and a 2×3
#       transform — and drawn again from that, through luce-svg, on every change: moved,
#       scaled or turned it stays crisp, as Photoshop's shape layers. A vector layer holds a
#       list of them (vector_elements.lucb; luce-vector draws them). Painting, filtering or distorting its pixels
#       turns it into an ordinary layer, as with text.
#
#==============================================================================================

extend Canvas:
    ## Make layer `id` a vector layer of one shape — `kind` 0 a rectangle
    ## (corners rounded by `radius`), 1 an ellipse, 2 a line from (`x`, `y`) by
    ## (`width`, `height`), 3 a regular polygon of `sides` — in the box (`x`,
    ## `y`, `width`, `height`), filled and stroked as given (linear colors; a
    ## line is its stroke). On a vector layer the shape replaces its target
    ## element (the active one, else the topmost). It stays a shape, crisp
    ## however it is moved, scaled or turned. One step.
    pub func set_shape(id: i64, kind: i64, x: f64, y: f64, width: f64, height: f64, sides: i64, radius: f64,
                       filled: bool, fill_red: f64, fill_green: f64, fill_blue: f64,
                       stroked: bool, stroke_red: f64, stroke_green: f64, stroke_blue: f64, stroke_width: f64) -> !:
        let values: f64[22] = [(f64)kind, x, y, width, height, (f64)sides, radius, 1.0 if filled else 0.0, fill_red, fill_green, fill_blue,
                               1.0 if stroked else 0.0, stroke_red, stroke_green, stroke_blue, stroke_width, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
        try set_layer_shape(&self, (u64)id, try shape_from_values(values))

    ## `set_shape`'s shape added on top of layer `id`'s elements instead, named
    ## after its kind and active: a pixel layer with nothing painted becomes a
    ## vector layer. One step.
    pub func add_shape(id: i64, kind: i64, x: f64, y: f64, width: f64, height: f64, sides: i64, radius: f64,
                       filled: bool, fill_red: f64, fill_green: f64, fill_blue: f64,
                       stroked: bool, stroke_red: f64, stroke_green: f64, stroke_blue: f64, stroke_width: f64) -> !:
        let values: f64[22] = [(f64)kind, x, y, width, height, (f64)sides, radius, 1.0 if filled else 0.0, fill_red, fill_green, fill_blue,
                               1.0 if stroked else 0.0, stroke_red, stroke_green, stroke_blue, stroke_width, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
        try add_vector_element(&self, (u64)id, try shape_from_values(values), "", "Shape")

    ## The target element's fill, stroke, corner radius and sides changed, its
    ## geometry and transform kept. One step; a slider dragged coalesces.
    pub func restyle_shape(id: i64, filled: bool, fill_red: f64, fill_green: f64, fill_blue: f64,
                           stroked: bool, stroke_red: f64, stroke_green: f64, stroke_blue: f64, stroke_width: f64, radius: f64, sides: i64) -> !:
        let style: f64[11] = [(f64)sides, radius, 1.0 if filled else 0.0, fill_red, fill_green, fill_blue,
                              1.0 if stroked else 0.0, stroke_red, stroke_green, stroke_blue, stroke_width]
        try restyle_target(&self, (u64)id, style[..<11])

    ## Layer `id` made a vector layer of a pen path (or, on a vector layer, its
    ## target element drawn as one) from the points collected with `add_point`,
    ## three an anchor in document pixels — the point, the handle coming in, the
    ## handle going out — joined by cubic curves, closed back to the first when
    ## `closed`; filled and stroked as `set_shape`. One step.
    pub func set_path(id: i64, closed: bool, filled: bool, fill_red: f64, fill_green: f64, fill_blue: f64,
                      stroked: bool, stroke_red: f64, stroke_green: f64, stroke_blue: f64, stroke_width: f64) -> !:
        let style: f64[11] = [3.0, 0.0, 1.0 if filled else 0.0, fill_red, fill_green, fill_blue,
                              1.0 if stroked else 0.0, stroke_red, stroke_green, stroke_blue, stroke_width]
        try set_layer_shape(&self, (u64)id, try self.collected_path(closed, style[..<11]))

    ## `set_path`'s path added on top of layer `id`'s elements instead, active. One step.
    pub func add_path(id: i64, closed: bool, filled: bool, fill_red: f64, fill_green: f64, fill_blue: f64,
                      stroked: bool, stroke_red: f64, stroke_green: f64, stroke_blue: f64, stroke_width: f64) -> !:
        let style: f64[11] = [3.0, 0.0, 1.0 if filled else 0.0, fill_red, fill_green, fill_blue,
                              1.0 if stroked else 0.0, stroke_red, stroke_green, stroke_blue, stroke_width]
        try add_vector_element(&self, (u64)id, try self.collected_path(closed, style[..<11]), "", "Path")

    ## The Vector panel's new path: an empty path element named `name` on top of
    ## layer `id`, active, for the Pen to draw into. One step.
    pub func add_empty_path(id: i64, name: str) -> !:
        var no_path: f64[]
        try add_vector_element(&self, (u64)id, ShapeSpec(kind = 4, filled = false, stroked = true, stroke_width = 1.0, path = no_path), name, "New Path")

    ## The collected points (`add_point`) as a path spec styled by `style`
    ## (`restyle_shape`'s values from sides on), which the caller owns.
    func collected_path(closed: bool, style: const f64[]) -> ShapeSpec!:
        let collected = self.polygon[..<self.polygon_count]
        self.polygon_count = 0
        if collected.length < 2 * anchor_values:
            error(invalid, "a path needs at least two anchors")
        var values: f64[22] = [4.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
        for at in 0..<(usize)11:
            values[5 + at] = style[at]
        var spec = try shape_from_values(values[..<22])
        spec.closed = closed
        spec.path = try owned_path(collected)
        return spec

    ## How many anchors the path the layer at `index` targets has; 0 for any
    ## other layer or element, and for an outline of several runs.
    pub func layer_path_count(index: i64) -> i64!:
        let spec = target_spec(try self.record(index)) else return 0
        if spec.kind != 4 or spec.subpaths.length > 0:
            return 0
        return (i64)(spec.path.length // anchor_values)

    ## Whether the targeted path of the layer at `index` is closed.
    pub func layer_path_closed(index: i64) -> bool!:
        let spec = target_spec(try self.record(index)) else return false
        return spec.closed

    ## Value `field` of anchor `anchor` of the path the layer at `index`
    ## targets, in document pixels: 0 and 1 the point, 2 and 3 the handle
    ## coming in, 4 and 5 the handle going out.
    pub func layer_path_value(index: i64, anchor: i64, field: i64) -> f64!:
        let spec = target_spec(try self.record(index)) else error(invalid, "the layer is not a path")
        if spec.kind != 4:
            error(invalid, "the layer is not a path")
        let count = (i64)(spec.path.length // anchor_values)
        if anchor < 0 or anchor >= count or field < 0 or field > 5:
            error(invalid, "no such path value")
        let at = (usize)anchor * anchor_values + (usize)(field - field % 2)
        let x = spec.path[at]
        let y = spec.path[at + 1]
        let m = spec.matrix
        return m[0] * x + m[2] * y + m[4] if field % 2 == 0 else m[1] * x + m[3] * y + m[5]

    ## Whether the layer at `index` is a vector layer.
    pub func layer_shaped(index: i64) -> bool!:
        return (try self.record(index)).shaped

    ## Value `field` of the shape the layer at `index` targets: 0 kind, 1..4
    ## the box, 5 sides, 6 radius, 7 filled, 8..10 the fill, 11 stroked,
    ## 12..14 the stroke, 15 its width, 16..21 the transform.
    pub func layer_shape_value(index: i64, field: i64) -> f64!:
        let spec = target_spec(try self.record(index)) else error(invalid, "the layer is not a shape")
        if field < 0 or field >= 22:
            error(invalid, "a shape has values 0..21")
        return shape_values(spec)[(usize)field]

## `Canvas.set_shape`: layer `id` made a vector layer of `spec` alone, or, when
## it is one already, its target element (vector_elements.lucb) drawn from
## `spec` instead, as one step.
func set_layer_shape(canvas: Canvas*, id: u64, spec: ShapeSpec) -> !:
    # `spec`'s path is the element's from here on; freed if it does not get there.
    var owned = spec
    let index = shape_layer_index(canvas, id) catch failure:
        release_spec_path(&owned)
        error(failure.code, failure.message)
    let record = canvas.records[index]
    if record.group or record.adjustment >= 0:
        release_spec_path(&owned)
        error(invalid, "only a pixel layer can hold a shape")
    let name = "Path" if spec.kind == 4 else "Shape"
    if record.shaped:
        if let at = target_element(&canvas.records[index]):
            try replace_element_spec(canvas, index, at, owned, name)
            return
    let element = try made_element(kind_name(spec.kind), owned)
    var no_list: VectorElement[]
    try commit_elements(canvas, index, try list_with(no_list, 0, element), none, -1, name, -1)

func shape_layer_index(canvas: Canvas*, id: u64) -> usize!:
    try canvas.require_open()
    try canvas.require_idle()
    return try canvas.index(id)

## Pixels of layer `id` about to change as pixels: it is no longer a vector layer.
func rasterize_shape(canvas: Canvas*, id: u64):
    let index = canvas.index(id) catch _:
        return
    canvas.records[index].shaped = false
    release_elements(&canvas.records[index])

## Every vector layer's elements and graph output moved by (`dx`, `dy`), with its pixels.
func shift_shapes(canvas: Canvas*, dx: f64, dy: f64):
    for index in 0..<canvas.count:
        for at in 0..<canvas.records[index].elements.length:
            canvas.records[index].elements[at].spec.matrix[4] += dx
            canvas.records[index].elements[at].spec.matrix[5] += dy
        place_graph(&canvas.records[index], [1.0, 0.0, 0.0, 1.0, dx, dy])

## `spec` with the document map `forward` (an affine map, source to
## destination) applied after its own; false in `ok` when the map is not
## affine, which a shape cannot follow.
func transformed_shape(spec: ShapeSpec, forward: Warp) -> ShapeSpec?:
    let affine = affine_of(forward) else return none
    let a = affine[0]
    let b = affine[1]
    let c = affine[2]
    let d = affine[3]
    let e = affine[4]
    let f = affine[5]
    let old = spec.matrix
    var moved = spec
    moved.matrix = [a * old[0] + c * old[1], b * old[0] + d * old[1],
                    a * old[2] + c * old[3], b * old[2] + d * old[3],
                    a * old[4] + c * old[5] + e, b * old[4] + d * old[5] + f]
    # The stroke grows with the shape, as Photoshop's: by the map's mean scale.
    moved.stroke_width = spec.stroke_width * math.sqrt(math.abs(a * d - b * c))
    return moved

## The document map `forward` as (a, b, c, d, e, f), as a shape's matrix is;
## none when it is not affine.
func affine_of(forward: Warp) -> f64[6]?:
    let m = forward.m
    if math.abs(m[6]) > 1e-9 or math.abs(m[7]) > 1e-9 or math.abs(m[8]) < 1e-12:
        return none
    return [m[0] / m[8], m[3] / m[8], m[1] / m[8], m[4] / m[8], m[2] / m[8], m[5] / m[8]]