"use strict";
/*---------------------------------------------------------------------------------------------
* 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
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.readElementMeshes = readElementMeshes;
const core_bentley_1 = require("@itwin/core-bentley");
const core_geometry_1 = require("@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
 */
function readElementMeshes(data) {
    const polyfaces = [];
    const stream = core_bentley_1.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 = core_geometry_1.BentleyGeometryFlatBuffer.bytesToGeometry(chunk.data, true);
            if (geom instanceof core_geometry_1.IndexedPolyface)
                polyfaces.push(geom);
        }
        catch {
            //
        }
    }
    return polyfaces;
}
//# sourceMappingURL=ElementMesh.js.map