/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Geometry
 */
import { ByteStream } from "@itwin/core-bentley";
import { BentleyGeometryFlatBuffer, IndexedPolyface } from "@itwin/core-geometry";
function nextChunk(stream) {
    if (stream.remainingLength < 8) {
        // Consume remaining bytes.
        stream.curPos = stream.length;
        return undefined;
    }
    // Type codes are a sequence of four uppercase ASCII letters.
    const chars = [stream.readUint8(), stream.readUint8(), stream.readUint8(), stream.readUint8()];
    if (chars.some((c) => c < 65 || c > 90))
        return undefined;
    const dataLength = stream.readUint32();
    const data = dataLength > 0 ? stream.nextBytes(dataLength) : undefined;
    return {
        type: String.fromCharCode(...chars),
        data,
    };
}
/** Convert the output of [IModelConnection.generateElementMeshes]($frontend) into an array of [Polyface]($core-geometry)s.
 * @param data Encoded polyfaces obtained from [IModelConnection.generateElementMeshes]($frontend).
 * @returns a list of decoded polyfaces.
 * @beta
 */
export function readElementMeshes(data) {
    const polyfaces = [];
    const stream = ByteStream.fromUint8Array(data);
    const firstChunk = nextChunk(stream);
    if (!firstChunk || "LMSH" !== firstChunk.type)
        return polyfaces;
    while (stream.remainingLength > 0) {
        const chunk = nextChunk(stream);
        if (!chunk || chunk.type !== "PLFC" || !chunk.data)
            continue;
        try {
            const geom = BentleyGeometryFlatBuffer.bytesToGeometry(chunk.data, true);
            if (geom instanceof IndexedPolyface)
                polyfaces.push(geom);
        }
        catch {
            //
        }
    }
    return polyfaces;
}
//# sourceMappingURL=ElementMesh.js.map