Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.3

0.9.3 / src / sketch / text.lucb

## A sketch as text, how the editor keeps it on its node: a line per
## entity, then a line per constraint, fields apart by spaces, numbers in
## their shortest exact form (they read back to the same bits):
##
##   p <x> <y> [c]                    a point; `c`: construction
##   l <start> <end> [c]              a line between two points
##   o <center> <radius> [c]          a circle
##   a <center> <start> <end> <radius> [c]   an arc
##   s <fit> <degree> <point>… [c]    a spline on its points (`fit` 1: through
##                                    them, 0: its control net)
##   e <center> <major> <minor> [c]   an ellipse
##   n <start> <end> <apex> <rho> [c] a conic
##   t <anchor> <height> <font> <content> [c]   a text; its font file
##                                    and what it says with %, space and
##                                    newline as %25, %20 and %0A (an
##                                    empty font: -)
##   r <entity> <role>                entity `entity` is part of the sketch
##                                    origin: 1 its point, 2 its x axis, 3
##                                    its y axis, 4 an axis's far end
##   j <entity> <reference>           curve `entity` projected from the
##                                    body edge `reference` names (escaped
##                                    as a text's words)
##   k <kind> <first> <second> <third> <value> <side> [d]
##                                    a constraint; `d`: driven
##   g <constraint> <a> <b>           where a dimension's label was put
##                                    (dimensions.lucb)
##   m <group> <source> <copy> <side> a pair of the Offset relation whose
##                                    first copy is `group`, beyond its first
##   f <name>                         a face whose loops are projected
##                                    (escaped as a text's words)
##
## Entities are numbered in order from 0 and may name any of the points; a
## constraint's kind is its ConstraintKind name. Points hold where the last
## solve left them.

## `sketch` as text, added to `out`.
pub func write_sketch(sketch: const Sketch*, out: Growing[u8]*) -> !:
    for e in sketch.entities.view():
        if e.kind == EntityKind.point:
            try put_text(out, "p")
            try put_number(out, sketch.params.items[(usize)e.first])
            try put_number(out, sketch.params.items[(usize)e.first + 1])
        elif e.kind == EntityKind.line:
            try put_text(out, "l")
            try put_index(out, e.first)
            try put_index(out, e.second)
        elif e.kind == EntityKind.circle:
            try put_text(out, "o")
            try put_index(out, e.first)
            try put_number(out, sketch.params.items[(usize)e.second])
        elif e.kind == EntityKind.spline:
            try put_text(out, "s")
            try put_index(out, e.fourth)
            try put_index(out, e.third)
            for at in 0..<e.second: try put_index(out, sketch.spline_point(e, at))
        elif e.kind == EntityKind.ellipse:
            try put_text(out, "e")
            try put_index(out, e.first)
            try put_index(out, e.third)
            try put_number(out, sketch.params.items[(usize)e.second])
        elif e.kind == EntityKind.text:
            try put_text(out, "t")
            try put_index(out, e.first)
            try put_number(out, sketch.params.items[(usize)e.second])
            try put_text(out, " ")
            let font = sketch.text_font(e)
            if font.length == 0: try put_text(out, "-")
            else: try put_escaped(out, font)
            try put_text(out, " ")
            try put_escaped(out, sketch.text_content(e))
        elif e.kind == EntityKind.conic:
            try put_text(out, "n")
            try put_index(out, e.first)
            try put_index(out, e.third)
            try put_index(out, e.fourth)
            try put_number(out, sketch.params.items[(usize)e.second])
        else:
            try put_text(out, "a")
            try put_index(out, e.first)
            try put_index(out, e.third)
            try put_index(out, e.fourth)
            try put_number(out, sketch.params.items[(usize)e.second])
        if e.construction: try put_text(out, " c")
        try out.push(10)
    for at in 0..<sketch.entities.count:
        let role = sketch.entities.items[at].origin
        if role == 0: continue
        try put_text(out, "r")
        try put_index(out, (i64)at)
        try put_index(out, role)
        try out.push(10)
    for l in sketch.links.view():
        try put_text(out, "j")
        try put_index(out, l.entity)
        try put_text(out, " ")
        try put_escaped(out, sketch.link_reference(l))
        try out.push(10)
    for k in sketch.constraints.view():
        try put_text(out, "k ")
        try put_text(out, kind_names()[(usize)(u8)k.kind])
        try put_index(out, k.first)
        try put_index(out, k.second)
        try put_index(out, k.third)
        try put_number(out, k.value)
        try put_number(out, k.side)
        if k.driven: try put_text(out, " d")
        try out.push(10)
    for at in 0..<sketch.constraints.count:
        let k = sketch.constraints.items[at]
        if not k.placed: continue
        try put_text(out, "g")
        try put_index(out, (i64)at)
        try put_number(out, k.label_a)
        try put_number(out, k.label_b)
        try out.push(10)
    for pair in sketch.offsets.view():
        try put_text(out, "m")
        try put_index(out, pair.group)
        try put_index(out, pair.source)
        try put_index(out, pair.copy)
        try put_number(out, pair.side)
        try out.push(10)
    for face in sketch.faces.view():
        try put_text(out, "f ")
        try put_escaped(out, sketch.face_reference(face))
        try out.push(10)

## The sketch `text` describes (empty text: an empty sketch).
pub func read_sketch(text: str) -> Sketch!:
    var s = new_sketch()
    errdefer s.close()
    # A spline's line: its tag, two numbers, up to 256 points and a mark.
    var fields: str[260] = ---
    for at in 0..<(usize)260: fields[at] = ""
    var start: usize = 0
    var checked = false
    let bytes = text.bytes
    while start < bytes.length:
        var end = start
        while end < bytes.length and bytes[end] != 10: end += 1
        let count = split((str)bytes[start..<end], fields[0..])
        start = end + 1
        if count == 0: continue
        let tag = fields[0]
        # A trailing mark only past the fields its line has (a text that
        # says `c` is not a construction text): `d` on a constraint, `c`
        # on an entity.
        let expected = fields_of(tag, count)
        let marked = expected >= 0 and count == (usize)expected + 1 and fields[count - 1] == ("d" if tag == "k" else "c") and tag != "j" and tag != "r" and tag != "f" and tag != "m" and tag != "g"
        let given = count - 1 if marked else count
        if tag == "p" and given == 3:
            _ = try s.add_point(try strings.parse_f64(fields[1]), try strings.parse_f64(fields[2]), marked)
        elif tag == "l" and given == 3:
            _ = try s.add(SketchEntity(EntityKind.line, try whole(fields[1]), try whole(fields[2]), -1, -1, marked))
        elif tag == "o" and given == 3:
            let r = (i64)s.params.count
            try s.params.push(try strings.parse_f64(fields[2]))
            _ = try s.add(SketchEntity(EntityKind.circle, try whole(fields[1]), r, -1, -1, marked))
        elif tag == "a" and given == 5:
            let r = (i64)s.params.count
            try s.params.push(try strings.parse_f64(fields[4]))
            _ = try s.add(SketchEntity(EntityKind.arc, try whole(fields[1]), r, try whole(fields[2]), try whole(fields[3]), marked))
        elif tag == "s" and given >= 5:
            let listed = (i64)s.lists.count
            for at in 3..<given: try s.lists.push(try whole(fields[at]))
            _ = try s.add(SketchEntity(EntityKind.spline, listed, (i64)(given - 3), try whole(fields[2]), try whole(fields[1]), marked))
        elif tag == "t" and given == 5:
            var content = Growing[u8]()
            defer content.close()
            var font = Growing[u8]()
            defer font.close()
            if fields[3] != "-": try unescape(fields[3], &font)
            try unescape(fields[4], &content)
            let anchor = try whole(fields[1])
            let label = Label(s.chars.count, content.count, s.chars.count + content.count, font.count)
            for byte in content.view(): try s.chars.push(byte)
            for byte in font.view(): try s.chars.push(byte)
            try s.labels.push(label)
            let r = (i64)s.params.count
            try s.params.push(try strings.parse_f64(fields[2]))
            _ = try s.add(SketchEntity(EntityKind.text, anchor, r, (i64)s.labels.count - 1, -1, marked))
        elif tag == "e" and given == 4:
            let r = (i64)s.params.count
            try s.params.push(try strings.parse_f64(fields[3]))
            _ = try s.add(SketchEntity(EntityKind.ellipse, try whole(fields[1]), r, try whole(fields[2]), -1, marked))
        elif tag == "n" and given == 5:
            let r = (i64)s.params.count
            try s.params.push(try strings.parse_f64(fields[4]))
            _ = try s.add(SketchEntity(EntityKind.conic, try whole(fields[1]), r, try whole(fields[2]), try whole(fields[3]), marked))
        elif tag == "r" and given == 3:
            let at = try whole(fields[1])
            let role = try whole(fields[2])
            if at < 0 or at >= (i64)s.entities.count or role < origin_point or role > origin_axis_end: error(invalid, "a sketch's origin line names an entity or a part it does not have")
            s.entities.items[(usize)at].origin = role
        elif tag == "j" and given == 3:
            var reference = Growing[u8]()
            defer reference.close()
            try unescape(fields[2], &reference)
            try s.link(try whole(fields[1]), (str)reference.view())
        elif tag == "k" and given == 7:
            if not checked:
                try check_entities(&s)
                checked = true
            let kind = try kind_named(fields[1])
            _ = try s.constrain(kind, try whole(fields[2]), try whole(fields[3]), try whole(fields[4]), try strings.parse_f64(fields[5]), try strings.parse_f64(fields[6]), marked)
        elif tag == "g" and given == 4:
            let at = try whole(fields[1])
            if at < 0 or at >= (i64)s.constraints.count: error(invalid, "a sketch's label place names a constraint the sketch does not have")
            s.constraints.items[(usize)at].placed = true
            s.constraints.items[(usize)at].label_a = try strings.parse_f64(fields[2])
            s.constraints.items[(usize)at].label_b = try strings.parse_f64(fields[3])
        elif tag == "m" and given == 5:
            if not checked:
                try check_entities(&s)
                checked = true
            try s.offset_pair(try whole(fields[1]), try whole(fields[2]), try whole(fields[3]), try strings.parse_f64(fields[4]))
        elif tag == "f" and given == 2:
            var name = Growing[u8]()
            defer name.close()
            try unescape(fields[1], &name)
            try s.project_face_name((str)name.view())
        else:
            error(invalid, "a sketch's text has a line it does not know")
    if not checked: try check_entities(&s)
    for l in s.links.view():
        if l.entity < 0 or l.entity >= (i64)s.entities.count or s.entities.items[(usize)l.entity].kind == EntityKind.text or l.reference_length == 0:
            error(invalid, "a sketch's projection names a curve the sketch does not have")
    return s

## How many fields a line of tag `tag` has before its mark (a spline's:
## all `count` but a trailing `c`), -1 for a tag there is not.
func fields_of(tag: str, count: usize) -> i64:
    if tag == "s": return (i64)count - 1
    if tag == "f": return 2
    if tag == "p" or tag == "l" or tag == "o" or tag == "j" or tag == "r": return 3
    if tag == "g": return 4
    if tag == "e": return 4
    if tag == "a" or tag == "n" or tag == "t" or tag == "m": return 5
    if tag == "k": return 7
    return -1

## Every curve read draws on points of the sketch (a curve may name points
## after it: a trimmed or filleted line's new end), a line's two apart, an
## arc's center and ends apart, a spline's degree 1..5, its radius,
## height or minor radius positive and its rho between 0 and 1.
func check_entities(s: const Sketch*) -> !:
    let count = (i64)s.entities.count
    var points = Growing[i64]()
    defer points.close()
    for e in s.entities.view():
        if e.kind == EntityKind.point: continue
        if e.kind == EntityKind.spline and (e.second < 2 or e.third < 1 or e.third > 5): error(invalid, "a sketch spline needs 2 points or more and a degree of 1 to 5")
        try s.points_of(e, &points)
        for p in points.view():
            if p < 0 or p >= count or s.entities.items[(usize)p].kind != EntityKind.point:
                error(invalid, "a sketch curve names a point the sketch does not have")
        if e.kind == EntityKind.line and e.first == e.second: error(invalid, "a sketch line needs two different points")
        if e.kind == EntityKind.arc and (e.first == e.third or e.first == e.fourth or e.third == e.fourth): error(invalid, "a sketch arc needs a center and two different ends")
        let scalar = s.scalar_of(e)
        if scalar >= 0 and not s.scalar_fits(e, s.params.items[(usize)scalar]): error(invalid, "a sketch curve's radius, height or minor radius is not positive, or its rho not between 0 and 1")

## The names of ConstraintKind's values, in order.
func kind_names() -> str[25]:
    return ["coincident", "on_curve", "horizontal", "vertical", "parallel", "perpendicular", "tangent", "equal", "fix", "midpoint",
            "concentric", "collinear", "symmetric", "distance", "line_distance", "horizontal_distance", "vertical_distance", "angle", "radius", "diameter", "curvature", "smooth", "offset", "sweep", "polygon"]

func kind_named(name: str) -> ConstraintKind!:
    let names = kind_names()
    for at in 0..<constraint_kind_count:
        if names[at] == name: return ConstraintKind((u8)at)
    error(invalid, "a sketch constraint has a kind it does not know")

## Split `line` at spaces into `fields`; how many there were (at most
## its length).
func split(line: str, fields: str[]) -> usize:
    var count: usize = 0
    var at: usize = 0
    let bytes = line.bytes
    while at < bytes.length and count < fields.length:
        while at < bytes.length and bytes[at] == 32: at += 1
        if at >= bytes.length: break
        var end = at
        while end < bytes.length and bytes[end] != 32: end += 1
        fields[count] = (str)bytes[at..<end]
        count += 1
        at = end
    return count

func whole(text: str) -> i64!:
    return strings.parse_i64(text) else error(invalid, "a sketch's text has an index that is not a whole number")

func put_text(out: Growing[u8]*, text: str) -> !:
    for byte in text.bytes: try out.push(byte)

func put_index(out: Growing[u8]*, value: i64) -> !:
    var buffer: u8[32] = ---
    try put_text(out, " ")
    try put_text(out, try strings.format_f64((f64)value, buffer[0..]))

func put_number(out: Growing[u8]*, value: f64) -> !:
    var buffer: u8[32] = ---
    try put_text(out, " ")
    try put_text(out, try strings.format_f64(value, buffer[0..]))

## `text` with %, space and newline written %25, %20, %0A.
func put_escaped(out: Growing[u8]*, text: str) -> !:
    for byte in text.bytes:
        if byte == 37: try put_text(out, "%25")
        elif byte == 32: try put_text(out, "%20")
        elif byte == 10: try put_text(out, "%0A")
        else: try out.push(byte)

## `text` with put_escaped's escapes read back onto `out`.
func unescape(text: str, out: Growing[u8]*) -> !:
    let bytes = text.bytes
    var at: usize = 0
    while at < bytes.length:
        if bytes[at] == 37:
            if at + 2 >= bytes.length: error(invalid, "a sketch text ends in a cut escape")
            let code = (str)bytes[at + 1..<at + 3]
            if code == "25": try out.push(37)
            elif code == "20": try out.push(32)
            elif code == "0A": try out.push(10)
            else: error(invalid, "a sketch text has an escape it does not know")
            at += 3
            continue
        try out.push(bytes[at])
        at += 1