Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ply

Source of release 0.1.0

0.1.0 / src / header.lucb

## The PLY header: the format line, then elements, each with its properties,
## up to `end_header`. Names are views into the file's bytes, which must
## outlive the header. Lines may end in LF or CRLF; `comment` and
## `obj_info` lines are skipped.
import strings
from luce_std import utf8
from luce_geocore.core.growing import Growing
from scalars import Scalar, scalar_named, size_of
import errors

## How the body is stored.
pub enum Format as u8:
    ascii = 0
    little_endian = 1
    big_endian = 2

## One property of an element: a scalar, or a list of `kind` values led by a
## count of `count_kind`.
pub struct Property:
    pub var name: str
    pub var kind: Scalar
    pub var is_list: bool = false
    pub var count_kind: Scalar = Scalar.uint8

## One element: `count` rows of its properties, which are
## `properties[first..<first + properties]` of the header. `stride` is the
## bytes of a binary row when it has no lists (0 otherwise).
pub struct Element:
    pub var name: str
    pub var count: usize
    pub var first: usize
    pub var properties: usize
    pub var stride: usize

## The parsed header and where the body starts.
pub struct Header:
    pub var format: Format = Format.ascii
    pub var elements: Growing[Element]
    pub var properties: Growing[Property]
    ## The offset of the first body byte.
    pub var body: usize = 0

    ## The index of the element called `name`, or -1.
    pub func find(name: str) -> i64:
        for at in 0..<self.elements.count:
            if self.elements.items[at].name == name: return (i64)at
        return -1

    ## The properties of element `element`.
    pub func properties_of(element: usize) -> const Property[]:
        let found = &self.elements.items[element]
        return self.properties.view()[found.first..<found.first + found.properties]

    ## The index within element `element` of property `name`, or -1.
    pub func property(element: usize, name: str) -> i64:
        let all = self.properties_of(element)
        for at in 0..<all.length:
            if all[at].name == name: return (i64)at
        return -1

    pub func close():
        self.elements.close()
        self.properties.close()

## Headers longer than this are refused.
let most_header_bytes: usize = 1048576
## Rows per element at most (a GeometrySet's columns count in u32 items).
let most_rows: u64 = 2147483647

## Parse the header at the start of `data`.
pub func parse_header(data: const u8[]) -> Header!:
    var header = Header()
    errdefer header.close()
    var at: usize = 0
    var number: usize = 0
    var element_open = false
    while true:
        if at >= data.length or at >= most_header_bytes:
            error(errors.invalid, "the PLY header has no end_header line")
        var end = at
        while end < data.length and data[end] != 10: end += 1
        if end == data.length: error(errors.invalid, "the PLY header has no end_header line")
        var stop = end
        if stop > at and data[stop - 1] == 13: stop -= 1
        let line = data[at..<stop]
        at = end + 1
        number += 1
        var words: str[8]
        let count = split_words(line, words)
        if number == 1:
            if count != 1 or words[0] != "ply": error(errors.invalid, "not a PLY file: it does not start with ply")
            continue
        if count == 0: continue
        let keyword = words[0]
        if keyword == "comment" or keyword == "obj_info": continue
        if keyword == "format":
            if count < 3 or words[2] != "1.0": error(errors.unsupported, "PLY format version must be 1.0")
            if words[1] == "ascii": header.format = Format.ascii
            elif words[1] == "binary_little_endian": header.format = Format.little_endian
            elif words[1] == "binary_big_endian": header.format = Format.big_endian
            else: error(errors.invalid, "unknown PLY format")
        elif keyword == "element":
            if count != 3: error(errors.invalid, "a PLY element line is: element <name> <count>")
            let rows = strings.parse_u64(words[2]) else error(errors.invalid, "a PLY element count is not a whole number")
            if rows > most_rows: error(errors.limit, "a PLY element has more than 2^31 rows")
            try header.elements.push(Element(name = words[1], count = (usize)rows, first = header.properties.count, properties = 0, stride = 0))
            element_open = true
        elif keyword == "property":
            if not element_open: error(errors.invalid, "a PLY property comes before any element")
            var property = Property(name = words[count - 1], kind = Scalar.uint8)
            if count == 5 and words[1] == "list":
                property.is_list = true
                property.count_kind = scalar_named(words[2]) else error(errors.invalid, "unknown PLY list count type")
                property.kind = scalar_named(words[3]) else error(errors.invalid, "unknown PLY property type")
                if property.count_kind == Scalar.float32 or property.count_kind == Scalar.float64:
                    error(errors.invalid, "a PLY list count must be an integer type")
            elif count == 3:
                property.kind = scalar_named(words[1]) else error(errors.invalid, "unknown PLY property type")
            else:
                error(errors.invalid, "a PLY property line is: property <type> <name>")
            try header.properties.push(property)
            header.elements.items[header.elements.count - 1].properties += 1
        elif keyword == "end_header":
            break
        else:
            error(errors.invalid, "unknown PLY header line")
    if number < 3: error(errors.invalid, "the PLY header has no format line")
    if not utf8.valid(data[..<at]): error(errors.invalid, "the PLY header is not UTF-8 text")
    header.body = at
    for index in 0..<header.elements.count:
        var stride: usize = 0
        for property in header.properties_of(index):
            if property.is_list:
                stride = 0
                break
            stride += size_of(property.kind)
        header.elements.items[index].stride = stride
    return header

## Split `line` at spaces and tabs into `words`, at most eight; returns how
## many (a ninth word and later are ignored).
func split_words(line: const u8[], words: str[]) -> usize:
    var count: usize = 0
    var at: usize = 0
    while at < line.length and count < words.length:
        while at < line.length and (line[at] == 32 or line[at] == 9): at += 1
        if at == line.length: break
        let start = at
        while at < line.length and line[at] != 32 and line[at] != 9: at += 1
        words[count] = (str)line[start..<at]
        count += 1
    return count