Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-image

Source of release 0.45.1

0.45.1 / src / canvas / graph_layers.lucb

#==============================================================================================
#
#   canvas/graph_layers - A vector layer's node graph on the canvas: edits, steps and cells
#
#   DESCRIPTION:
#       A vector layer draws its hand-made elements and then its graph's output (luce-vector's
#       graph), both through the same cell renderer (luce-vector's vector). Every
#       change to either goes through `commit_layer`: the new elements and graph are
#       evaluated and drawn beside the old, the step recorded, and only then swapped in, so
#       an edit that cannot be made changes nothing. The cells drawn again are those the
#       changed element reaches and those of every generated shape that differs from before,
#       old place and new: a parameter that moves one clone redraws that clone's cells.
#
#       The output is kept on the record with the cache that made it. A copy for the history
#       keeps the graph only; the output is evaluated again when next it is needed.
#
#==============================================================================================

extend Canvas:
    ## A new vector layer named `name` on top, its graph a Star cloned round a
    ## circle into the Output, drawn; selected nowhere, its id returned. One step.
    pub func add_vector_layer(name: str) -> i64!:
        try self.require_idle()
        try self.begin_edit("New Vector Layer")
        defer self.end_edit()
        let id = try self.add_layer(name)
        let index = try self.index((u64)id)
        self.records[index].shaped = true
        let graph = try default_graph(self.extent_x, self.extent_y)
        var no_list: VectorElement[]
        if self.document == none:
            self.records[index].graph = graph
            return id
        try commit_layer(&self, index, no_list, graph, none, -1, "New Vector Layer", -1, false)
        return id

    pub func graph_node_count(index: i64) -> i64!:
        return (i64)(try self.record(index)).graph.nodes.length

    ## Value `field` of node `node` (its place, 0 the first): 0 its id, 1 its
    ## kind, 2 and 3 where the editor shows it, 4.. its values from slot 0.
    pub func graph_node_value(index: i64, node: i64, field: i64) -> f64!:
        let record = try self.record(index)
        if node < 0 or node >= (i64)record.graph.nodes.length or field < 0 or field >= 4 + (i64)node_slots:
            error(invalid, "no such node value")
        let entry = record.graph.nodes[(usize)node]
        if field == 0:
            return (f64)entry.id
        if field == 1:
            return (f64)entry.kind
        if field == 2:
            return entry.x
        if field == 3:
            return entry.y
        return entry.values[(usize)(field - 4)]

    pub func graph_link_count(index: i64) -> i64!:
        return (i64)(try self.record(index)).graph.links.length

    ## Value `field` of link `link`: 0 the id of the node it leaves, 1 the id
    ## of the node it enters, 2 that node's input.
    pub func graph_link_value(index: i64, link: i64, field: i64) -> i64!:
        let record = try self.record(index)
        if link < 0 or link >= (i64)record.graph.links.length:
            error(invalid, "no such link")
        let entry = record.graph.links[(usize)link]
        return (i64)entry.source_id if field == 0 else ((i64)entry.to if field == 1 else (i64)entry.port)

    ## A node of `kind` at (`x`, `y`) in layer `id`'s graph, with its defaults; its id.
    pub func add_graph_node(id: i64, kind: i64, x: f64, y: f64) -> i64!:
        let index = try graph_index(&self, (u64)id)
        var made: u32 = 0
        try commit_graph(&self, index, try graph_with_node(&self.records[index].graph, kind, x, y, &made), "Add Node", false)
        return (i64)made

    ## Node `node` of layer `id`'s graph taken away with its wires.
    pub func delete_graph_node(id: i64, node: i64) -> !:
        let index = try graph_index(&self, (u64)id)
        let ids: u32[1] = [(u32)node]
        try commit_graph(&self, index, try graph_without_nodes(&self.records[index].graph, ids[..<1]), "Delete Node", false)

    ## Node `from`'s output wired into input `port` of node `to`, replacing what
    ## fed it; refused across types or round a loop.
    pub func link_graph(id: i64, source_id: i64, to: i64, port: i64) -> !:
        let index = try graph_index(&self, (u64)id)
        try commit_graph(&self, index, try graph_with_link(&self.records[index].graph, (u32)source_id, (u32)to, (u32)port), "Connect", false)

    ## The wire into input `port` of node `to` taken away.
    pub func unlink_graph(id: i64, to: i64, port: i64) -> !:
        let index = try graph_index(&self, (u64)id)
        try commit_graph(&self, index, try graph_without_link(&self.records[index].graph, (u32)to, (u32)port), "Disconnect", false)

    ## Value `slot` of node `node` set (held to its parameter's range); a drag coalesces.
    pub func set_graph_value(id: i64, node: i64, slot: i64, value: f64) -> !:
        let index = try graph_index(&self, (u64)id)
        if slot < 0:
            error(invalid, "a node has values 0..23")
        try commit_graph(&self, index, try graph_with_value(&self.records[index].graph, (u32)node, (usize)slot, value), "Node Setting", true)

    ## Node `node` shown at (`x`, `y`) in the editor; nothing is drawn. A drag coalesces.
    pub func move_graph_node(id: i64, node: i64, x: f64, y: f64) -> !:
        let index = try graph_index(&self, (u64)id)
        try commit_graph(&self, index, try graph_with_position(&self.records[index].graph, (u32)node, x, y), "Move Node", true)

    ## How many shapes the layer at `index`'s graph puts out, evaluating it if it must.
    pub func generated_count(index: i64) -> i64!:
        _ = try self.record(index)
        try fresh_output(&self.records[(usize)index])
        return (i64)self.records[(usize)index].generated.count

    ## How many nodes the layer's last graph evaluation computed rather than reused.
    pub func graph_computed(index: i64) -> i64!:
        return (i64)(try self.record(index)).graph_evaluated

    pub func node_kind_count() -> i64:
        return node_kinds

    pub func node_kind_title(kind: i64) -> str:
        return node_info(kind).title

    ## A kind's output's port type (0 Shapes, 1 Points, 2 Number, 3 Color), -1 for none.
    pub func node_kind_output(kind: i64) -> i64:
        return node_info(kind).output

    pub func node_input_count(kind: i64) -> i64:
        return (i64)node_info(kind).input_count

    pub func node_input_name(kind: i64, port: i64) -> str:
        let info = node_info(kind)
        return info.inputs[(usize)port].name if port >= 0 and port < (i64)info.input_count else ""

    ## An input's port type; a Number wire may also go where a Color does.
    pub func node_input_type(kind: i64, port: i64) -> i64:
        let info = node_info(kind)
        return info.inputs[(usize)port].port_type if port >= 0 and port < (i64)info.input_count else -1

    ## The value slot an input drives, -1 for a data input.
    pub func node_input_slot(kind: i64, port: i64) -> i64:
        let info = node_info(kind)
        return info.inputs[(usize)port].slot if port >= 0 and port < (i64)info.input_count else -1

    pub func node_param_count(kind: i64) -> i64:
        return (i64)node_info(kind).param_count

    pub func node_param_name(kind: i64, param: i64) -> str:
        let info = node_info(kind)
        return info.params[(usize)param].name if param >= 0 and param < (i64)info.param_count else ""

    ## Value `field` of a parameter: 0 how it is edited (0 a number, 1 a whole
    ## number, 2 a toggle, 3 a color), 1 its slot, 2 and 3 its range.
    pub func node_param_value(kind: i64, param: i64, field: i64) -> f64:
        let info = node_info(kind)
        if param < 0 or param >= (i64)info.param_count:
            return 0.0
        let entry = info.params[(usize)param]
        return (f64)entry.kind if field == 0 else ((f64)entry.slot if field == 1 else (entry.low if field == 2 else entry.high))

## The record's graph output brought up to date with its graph and elements.
func fresh_output(record: Record*) -> !:
    if record.generated_fresh:
        return
    var output: ShapeList
    if record.graph.present():
        record.graph_evaluated = evaluate_graph(&record.graph, record.elements, &record.graph_cache, &output) catch failure:
            output.release()
            error(failure.code, failure.message)
    record.generated.release()
    record.generated = output
    record.generated_fresh = true

## The graph parts of a record copied for a copy that owns its own: the graph
## kept, its cache and output left to be made again. On failure it holds no graph.
func copy_graph_part(record: Record*) -> !:
    let source = record.graph
    var empty: Graph
    var no_cache: GraphCache
    var no_output: ShapeList
    record.graph = empty
    record.graph_cache = no_cache
    record.generated = no_output
    record.generated_fresh = false
    record.graph = try copied_graph(&source)

## Free a record's graph, its cache and its output.
func release_graph_part(record: Record*):
    free_graph(&record.graph)
    record.graph_cache.release()
    record.generated.release()
    record.generated_fresh = false

## The layer at `index` with `list` as its elements and `graph` as its graph, as
## step `name`: both taken over (freed, nothing changed, when it cannot be made).
## `dirty` marks the cells to draw again besides the changed element `changed` of
## `list` and the generated shapes that differ; none draws every cell. `active`
## becomes the active element; `joins` lets a repeat of the step coalesce.
func commit_layer(canvas: Canvas*, index: usize, list: VectorElement[], graph: Graph, dirty: CellMask*?, changed: i64, name: str, active: i64, joins: bool) -> !:
    var owned_list = list
    var owned_graph = graph
    var output: ShapeList
    errdefer:
        free_list(owned_list)
        free_graph(&owned_graph)
        output.release()
    let document = canvas.document else error(invalid, "draw the document once before drawing a shape")
    let record = &canvas.records[index]
    let id = record.id
    try fresh_output(record)
    if owned_graph.present():
        record.graph_evaluated = try evaluate_graph(&owned_graph, owned_list, &record.graph_cache, &output)
    var redraw = true
    if let cells = dirty:
        if changed >= 0 and changed < (i64)owned_list.length:
            try cells.mark(owned_list[(usize)changed])
        try mark_changed_shapes(cells, &record.generated, &output)
        redraw = cells.count() > 0
    var tiles: Tiles? = none
    errdefer:
        if let made = tiles:
            var dropped = made
            dropped.destroy()
    if redraw:
        let view = try drawn_elements(owned_list, &output)
        defer free_view(view)
        tiles = try vector_tiles(canvas, id, view, dirty)
    try canvas.remember_state(name, id if joins else 0)
    # From here nothing fails but the upload: the new content is the layer's.
    let target = &canvas.records[index]
    release_type(target)
    free_list(target.elements)
    target.elements = owned_list
    free_graph(&target.graph)
    target.graph = owned_graph
    target.generated.release()
    target.generated = output
    target.generated_fresh = true
    target.shaped = true
    target.active = active if active < (i64)owned_list.length else -1
    var no_list: VectorElement[]
    var no_graph: Graph
    var no_output: ShapeList
    owned_list = no_list
    owned_graph = no_graph
    output = no_output
    if let made = tiles:
        tiles = none
        try document.set_tiles(id, made)

## The layer at `index`'s graph replaced by `graph` (taken over) as step `name`,
## its elements kept.
func commit_graph(canvas: Canvas*, index: usize, graph: Graph, name: str, joins: bool) -> !:
    var owned = graph
    let list = copied_list(canvas.records[index].elements) catch failure:
        free_graph(&owned)
        error(failure.code, failure.message)
    var dirty = CellMask.create(canvas.extent_x, canvas.extent_y) catch failure:
        free_list(list)
        free_graph(&owned)
        error(failure.code, failure.message)
    defer dirty.close()
    try commit_layer(canvas, index, list, owned, &dirty, -1, name, canvas.records[index].active, joins)

## The vector layer `id`'s record index, for a graph edit.
func graph_index(canvas: Canvas*, id: u64) -> usize!:
    try canvas.require_open()
    try canvas.require_idle()
    let index = try canvas.index(id)
    if not canvas.records[index].shaped:
        error(invalid, "only a vector layer holds a node graph")
    return index

## The graph's output moved by the affine map `m` with the layer: its placement
## and the shapes it last made, which stay current.
func place_graph(record: Record*, m: f64[6]):
    if not record.graph.present():
        return
    record.graph.placement = compose(m, record.graph.placement_matrix())
    record.graph.placed = true
    for at in 0..<record.generated.count:
        record.generated.specs[at] = spec_mapped(record.generated.specs[at], m)

## The layer at `index`'s elements changed in place (one moved alone): its graph
## evaluated again from them, as a Path node takes one, and the cells of every
## output shape that changed marked. Its output must have been fresh before.
func follow_elements(canvas: Canvas*, index: usize, dirty: CellMask*) -> !:
    let record = &canvas.records[index]
    if not record.graph.present():
        return
    var output: ShapeList
    errdefer output.release()
    record.graph_evaluated = try evaluate_graph(&record.graph, record.elements, &record.graph_cache, &output)
    try mark_changed_shapes(dirty, &record.generated, &output)
    record.generated.release()
    record.generated = output
    record.generated_fresh = true

## Move every generated shape of the layer at `index` by (`dx`, `dy`), marking
## the cells each leaves and reaches.
func shift_generated(canvas: Canvas*, index: usize, dx: f64, dy: f64, dirty: CellMask*) -> !:
    let record = &canvas.records[index]
    if not record.graph.present():
        return
    try fresh_output(record)
    try dirty.mark_specs(record.generated.view())
    place_graph(record, [1.0, 0.0, 0.0, 1.0, dx, dy])
    try dirty.mark_specs(record.generated.view())