"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 Tiles
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeImdlGraphics = decodeImdlGraphics;
exports.createGraphicTemplateFromDescription = createGraphicTemplateFromDescription;
exports.createGraphicFromDescription = createGraphicFromDescription;
const core_bentley_1 = require("@itwin/core-bentley");
const core_geometry_1 = require("@itwin/core-geometry");
const core_common_1 = require("@itwin/core-common");
const AuxChannelTable_1 = require("../common/internal/render/AuxChannelTable");
const SurfaceParams_1 = require("../common/internal/render/SurfaceParams");
const ParseImdlDocument_1 = require("../common/imdl/ParseImdlDocument");
const VertexIndices_1 = require("../common/internal/render/VertexIndices");
const GraphicBranch_1 = require("../render/GraphicBranch");
const InstancedGraphicParams_1 = require("../common/render/InstancedGraphicParams");
const GraphicDescriptionBuilderImpl_1 = require("../common/internal/render/GraphicDescriptionBuilderImpl");
const Symbols_1 = require("../common/internal/Symbols");
const GraphicTemplate_1 = require("../render/GraphicTemplate");
async function loadNamedTexture(name, namedTex, options) {
    // Reasons a texture could be embedded in the tile content instead of requested separately from the backend:
    // - external textures are disabled
    // - the texture name is not a valid Id64 string
    // - the texture is below a certain backend-hardcoded size threshold
    // The bufferViewJson being defined signifies any of the above conditions. In that case, the image content
    // has been embedded in the tile contents. Otherwise, we will attempt to request the image content separately
    // from the backend.
    try {
        let textureType = core_common_1.RenderTexture.Type.Normal;
        const isGlyph = core_bentley_1.JsonUtils.asBool(namedTex.isGlyph);
        const isTileSection = !isGlyph && core_bentley_1.JsonUtils.asBool(namedTex.isTileSection);
        if (isGlyph)
            textureType = core_common_1.RenderTexture.Type.Glyph;
        else if (isTileSection)
            textureType = core_common_1.RenderTexture.Type.TileSection;
        // We produce unique tile sections for very large (> 8 megapixel) textures, and unique glyph atlases for raster text.
        // Neither should be cached.
        const cacheable = !isGlyph && !isTileSection;
        const ownership = cacheable ? { iModel: options.iModel, key: name } : undefined;
        const bufferViewId = core_bentley_1.JsonUtils.asString(namedTex.bufferView);
        const bufferViewJson = 0 !== bufferViewId.length ? options.document.json.bufferViews[bufferViewId] : undefined;
        if (undefined !== bufferViewJson) { // presence of bufferViewJson signifies we should read the texture from the tile content
            const byteOffset = core_bentley_1.JsonUtils.asInt(bufferViewJson.byteOffset);
            const byteLength = core_bentley_1.JsonUtils.asInt(bufferViewJson.byteLength);
            if (0 === byteLength)
                return undefined;
            const texBytes = options.document.binaryData.subarray(byteOffset, byteOffset + byteLength);
            const format = namedTex.format;
            const source = new core_common_1.ImageSource(texBytes, format);
            return await options.system.createTextureFromSource({ source, ownership, type: textureType, transparency: namedTex.transparency });
        }
        // bufferViewJson was undefined, so attempt to request the texture directly from the backend
        // eslint-disable-next-line @typescript-eslint/no-deprecated
        const params = new core_common_1.RenderTexture.Params(cacheable ? name : undefined, textureType);
        return options.system.createTextureFromElement(name, options.iModel, params, namedTex.format);
    }
    catch {
        return undefined;
    }
}
async function loadNamedTextures(options) {
    const result = new Map();
    const namedTextures = options.document.json.namedTextures;
    if (!namedTextures)
        return result;
    const promises = new Array();
    for (const [name, namedTexture] of Object.entries(namedTextures)) {
        const texture = options.system.findTexture(name, options.iModel);
        if (texture) {
            result.set(name, texture);
            continue;
        }
        else if (namedTexture) {
            promises.push(loadNamedTexture(name, namedTexture, options).then((tx) => {
                if (tx)
                    result.set(name, tx);
            }));
        }
    }
    if (promises.length > 0)
        await Promise.all(promises);
    return result;
}
function constantLodParamPropsFromJson(propsJson) {
    if (undefined === propsJson)
        return undefined;
    const constantLodPops = {
        repetitions: core_bentley_1.JsonUtils.asDouble(propsJson.repetitions, 1.0),
        offset: { x: propsJson.offset ? core_bentley_1.JsonUtils.asDouble(propsJson.offset[0]) : 0.0, y: propsJson.offset ? core_bentley_1.JsonUtils.asDouble(propsJson.offset[1]) : 0.0 },
        minDistClamp: core_bentley_1.JsonUtils.asDouble(propsJson.minDistClamp, 1.0),
        maxDistClamp: core_bentley_1.JsonUtils.asDouble(propsJson.maxDistClamp, 4096.0 * 1024.0 * 1024.0),
    };
    return constantLodPops;
}
function textureMappingFromJson(json, options) {
    if (!json)
        return undefined;
    const texture = options.textures.get(core_bentley_1.JsonUtils.asString(json.name));
    if (!texture)
        return undefined;
    const paramsJson = json.params;
    const tf = paramsJson.transform;
    const paramProps = {
        textureMat2x3: new core_common_1.TextureMapping.Trans2x3(tf[0][0], tf[0][1], tf[0][2], tf[1][0], tf[1][1], tf[1][2]),
        textureWeight: core_bentley_1.JsonUtils.asDouble(paramsJson.weight, 1.0),
        mapMode: core_bentley_1.JsonUtils.asInt(paramsJson.mode),
        worldMapping: core_bentley_1.JsonUtils.asBool(paramsJson.worldMapping),
        useConstantLod: core_bentley_1.JsonUtils.asBool(paramsJson.useConstantLod),
        constantLodProps: constantLodParamPropsFromJson(paramsJson.constantLodParams),
    };
    const textureMapping = new core_common_1.TextureMapping(texture, new core_common_1.TextureMapping.Params(paramProps));
    const normalMapJson = json.normalMapParams;
    if (normalMapJson) {
        let normalMap;
        const normalTexName = core_bentley_1.JsonUtils.asString(normalMapJson.textureName);
        if (normalTexName.length === 0 || undefined !== (normalMap = options.textures.get(normalTexName))) {
            textureMapping.normalMapParams = {
                normalMap,
                greenUp: core_bentley_1.JsonUtils.asBool(normalMapJson.greenUp),
                scale: core_bentley_1.JsonUtils.asDouble(normalMapJson.scale, 1),
                useConstantLod: core_bentley_1.JsonUtils.asBool(normalMapJson.useConstantLod),
            };
        }
    }
    return textureMapping;
}
function getMaterial(mat, options) {
    if (typeof mat !== "string") {
        const args = (0, ParseImdlDocument_1.toMaterialParams)(mat);
        return options.system.createRenderMaterial(args);
    }
    if (!options.iModel) {
        return undefined;
    }
    const material = options.system.findMaterial(mat, options.iModel);
    if (material || !options.document?.json.renderMaterials)
        return material;
    const json = options.document.json.renderMaterials[mat];
    if (!json)
        return undefined;
    function colorDefFromJson(col) {
        return col ? core_common_1.ColorDef.from(col[0] * 255 + 0.5, col[1] * 255 + 0.5, col[2] * 255 + 0.5) : undefined;
    }
    // eslint-disable-next-line @typescript-eslint/no-deprecated
    const params = new core_common_1.RenderMaterial.Params(mat);
    params.diffuseColor = colorDefFromJson(json.diffuseColor);
    if (json.diffuse !== undefined)
        params.diffuse = core_bentley_1.JsonUtils.asDouble(json.diffuse);
    params.specularColor = colorDefFromJson(json.specularColor);
    if (json.specular !== undefined)
        params.specular = core_bentley_1.JsonUtils.asDouble(json.specular);
    params.reflectColor = colorDefFromJson(json.reflectColor);
    if (json.reflect !== undefined)
        params.reflect = core_bentley_1.JsonUtils.asDouble(json.reflect);
    if (json.specularExponent !== undefined)
        params.specularExponent = json.specularExponent;
    if (undefined !== json.transparency)
        params.alpha = 1.0 - json.transparency;
    params.refract = core_bentley_1.JsonUtils.asDouble(json.refract);
    params.shadows = core_bentley_1.JsonUtils.asBool(json.shadows);
    params.ambient = core_bentley_1.JsonUtils.asDouble(json.ambient);
    if (undefined !== json.textureMapping)
        params.textureMapping = textureMappingFromJson(json.textureMapping.texture, options);
    // eslint-disable-next-line @typescript-eslint/no-deprecated
    return options.system.createMaterial(params, options.iModel);
}
function getModifiers(primitive) {
    const mod = primitive.modifier;
    switch (mod?.type) {
        case "instances":
            return { instances: InstancedGraphicParams_1.InstancedGraphicParams.fromProps(mod) };
        case "viewIndependentOrigin":
            return {
                viOrigin: core_geometry_1.Point3d.fromJSON(mod.origin),
            };
        default:
            return {};
    }
}
function createPrimitiveGeometry(primitive, options, viOrigin) {
    switch (primitive.type) {
        case "point":
            return options.system.createPointStringGeometry({
                ...primitive.params,
                vertices: (0, ParseImdlDocument_1.toVertexTable)(primitive.params.vertices),
                indices: new VertexIndices_1.VertexIndices(primitive.params.indices),
            }, viOrigin);
        case "polyline":
            return options.system.createPolylineGeometry({
                ...primitive.params,
                vertices: (0, ParseImdlDocument_1.toVertexTable)(primitive.params.vertices),
                polyline: {
                    ...primitive.params.polyline,
                    indices: new VertexIndices_1.VertexIndices(primitive.params.polyline.indices),
                    prevIndices: new VertexIndices_1.VertexIndices(primitive.params.polyline.prevIndices),
                },
            }, viOrigin);
        case "mesh": {
            const surf = primitive.params.surface;
            let material;
            if (surf.material) {
                if (!surf.material.isAtlas)
                    material = (0, SurfaceParams_1.createSurfaceMaterial)(getMaterial(surf.material.material, options));
                else
                    material = surf.material;
            }
            let textureMapping;
            if (surf.textureMapping) {
                let texture;
                if (typeof surf.textureMapping.texture === "string") {
                    texture = options.textures.get(surf.textureMapping.texture);
                }
                else {
                    const gradient = core_common_1.Gradient.Symb.fromJSON(surf.textureMapping.texture);
                    texture = options.system.getGradientTexture(gradient, options.iModel);
                }
                if (texture)
                    textureMapping = { texture, alwaysDisplayed: surf.textureMapping.alwaysDisplayed };
            }
            return options.system.createMeshGeometry({
                ...primitive.params,
                edges: primitive.params.edges ? (0, ParseImdlDocument_1.edgeParamsFromImdl)(primitive.params.edges) : undefined,
                vertices: (0, ParseImdlDocument_1.toVertexTable)(primitive.params.vertices),
                auxChannels: primitive.params.auxChannels ? AuxChannelTable_1.AuxChannelTable.fromJSON(primitive.params.auxChannels) : undefined,
                surface: {
                    ...primitive.params.surface,
                    material,
                    textureMapping,
                    indices: new VertexIndices_1.VertexIndices(primitive.params.surface.indices),
                },
            }, viOrigin);
        }
    }
}
function createPrimitiveGraphic(primitive, options) {
    const mods = getModifiers(primitive);
    const geometry = createPrimitiveGeometry(primitive, options, mods.viOrigin);
    return geometry ? options.system.createRenderGraphic(geometry, mods.instances) : undefined;
}
function createPatternGeometries(primitives, options) {
    const geometries = [];
    for (const primitive of primitives) {
        const geometry = createPrimitiveGeometry(primitive, options, undefined);
        if (geometry)
            geometries.push(geometry);
    }
    return geometries;
}
function createPatternGraphic(params, options) {
    const geometries = options.patterns.get(params.symbolName);
    if (!geometries || geometries.length === 0)
        return undefined;
    const clip = core_geometry_1.ClipVector.fromJSON(params.clip);
    const clipVolume = clip?.isValid ? options.system.createClipVolume(clip) : undefined;
    if (!clipVolume)
        return undefined;
    const viewIndependentOrigin = params.viewIndependentOrigin ? core_geometry_1.Point3d.fromJSON(params.viewIndependentOrigin) : undefined;
    const pattern = options.system.createAreaPattern({
        xyOffsets: params.xyOffsets,
        featureId: params.featureId,
        orgTransform: core_geometry_1.Transform.fromJSON(params.orgTransform),
        origin: core_geometry_1.Point2d.fromJSON(params.origin),
        scale: params.scale,
        spacing: core_geometry_1.Point2d.fromJSON(params.spacing),
        patternToModel: core_geometry_1.Transform.fromJSON(params.modelTransform),
        range: core_geometry_1.Range3d.fromJSON(params.range),
        symbolTranslation: core_geometry_1.Point3d.fromJSON(params.symbolTranslation),
        viewIndependentOrigin,
    });
    if (!pattern)
        return undefined;
    const branch = new GraphicBranch_1.GraphicBranch(true);
    for (const geometry of geometries) {
        const graphic = options.system.createRenderGraphic(geometry, pattern);
        if (graphic)
            branch.add(graphic);
    }
    return branch.isEmpty ? undefined : options.system.createGraphicBranch(branch, core_geometry_1.Transform.createIdentity(), { clipVolume });
}
function createNodeGraphics(node, options) {
    if (undefined === node.groupId)
        return createPrimitivesNodeGraphics(node, options);
    const graphics = [];
    for (const child of node.nodes) {
        graphics.push(...createPrimitivesNodeGraphics(child, options));
    }
    if (graphics.length === 0)
        return graphics;
    const branch = new GraphicBranch_1.GraphicBranch(true);
    branch.groupNodeId = node.groupId;
    branch.entries.push(...graphics);
    return [options.system.createBranch(branch, core_geometry_1.Transform.createIdentity())];
}
function createPrimitivesNodeGraphics(node, options) {
    let graphics = [];
    for (const primitive of node.primitives) {
        const graphic = primitive.type === "pattern" ? createPatternGraphic(primitive.params, options) : createPrimitiveGraphic(primitive, options);
        if (graphic)
            graphics.push(graphic);
    }
    if (!graphics.length)
        return graphics;
    if (undefined !== node.layerId) {
        const layerGraphic = 1 === graphics.length ? graphics[0] : options.system.createGraphicList(graphics);
        graphics = [options.system.createGraphicLayer(layerGraphic, node.layerId)];
    }
    else if (undefined !== node.animationNodeId) {
        const branch = new GraphicBranch_1.GraphicBranch(true);
        branch.animationId = node.animationId;
        branch.animationNodeId = node.animationNodeId;
        branch.entries.push(...graphics);
        graphics = [options.system.createBranch(branch, core_geometry_1.Transform.createIdentity())];
    }
    return graphics;
}
/** @internal */
async function decodeImdlGraphics(options) {
    const textures = await loadNamedTextures(options);
    if (options.isCanceled && options.isCanceled())
        return undefined;
    const patterns = new Map();
    const graphicsOptions = { ...options, textures, patterns };
    for (const [name, primitives] of options.document.patterns)
        patterns.set(name, createPatternGeometries(primitives, graphicsOptions));
    const system = options.system;
    const graphics = [];
    for (const node of options.document.nodes) {
        graphics.push(...createNodeGraphics(node, graphicsOptions));
    }
    switch (graphics.length) {
        case 0: return undefined;
        case 1: return graphics[0];
        default: return system.createGraphicList(graphics);
    }
}
function remapGraphicDescription(descr, context) {
    if (descr.remapContext === context) {
        // Already remapped.
        return;
    }
    else if (descr.remapContext) {
        throw new Error("You cannot create a graphic from a GraphicDescription using two different contexts");
    }
    descr.remapContext = context;
    const batch = descr.batch;
    if (!batch) {
        return;
    }
    if (core_bentley_1.Id64.isTransient(batch.modelId)) {
        const modelLocalId = context.remapTransientLocalId(core_bentley_1.Id64.getLocalId(batch.modelId));
        batch.modelId = core_bentley_1.Id64.fromLocalAndBriefcaseIds(modelLocalId, 0xffffff);
    }
    const data = batch.featureTable.data;
    const remapId = (offset) => {
        const hi = data[offset + 1];
        if (hi >= 0xffffff00) {
            const hi8 = hi & 0xff;
            const lo = data[offset];
            // Avoid bitwise operators because they truncate at 32 bits (we need 40) and are stupid about the sign bit.
            const sourceLocalId = lo + (hi8 * 0xffffffff);
            const localId = context.remapTransientLocalId(sourceLocalId);
            data[offset] = localId & 0xffffffff;
            data[offset + 1] = 0xffffff00 + hi8;
        }
    };
    const subCatsOffset = 3 * batch.featureTable.numFeatures;
    for (let i = 0; i < subCatsOffset; i += 3) {
        remapId(i);
    }
    const subCatsEnd = undefined !== batch.featureTable.numSubCategories ? subCatsOffset + 2 * batch.featureTable.numSubCategories : data.length;
    for (let i = subCatsOffset; i < subCatsEnd; i++) {
        remapId(i);
    }
    if (undefined !== batch.featureTable.numSubCategories) {
        for (let i = subCatsEnd; i < data.length; i++) {
            remapId(i + 1);
        }
    }
}
/** @internal */
function createGraphicTemplateFromDescription(descr, context, system) {
    if (!(0, GraphicDescriptionBuilderImpl_1.isGraphicDescription)(descr)) {
        throw new Error("Invalid GraphicDescription");
    }
    remapGraphicDescription(descr, context);
    const graphicsOptions = {
        system,
        textures: context[Symbols_1._textures],
        patterns: new Map(),
    };
    const geometry = [];
    for (const primitive of descr.primitives) {
        const mods = getModifiers(primitive);
        // GraphicDescriptionBuilder providers no way to include instances in a GraphicDescription.
        (0, core_bentley_1.assert)(undefined === mods?.instances);
        const geom = createPrimitiveGeometry(primitive, graphicsOptions, mods.viOrigin);
        if (geom) {
            geometry.push(geom);
        }
    }
    let batch;
    if (descr.batch) {
        const featureTable = (0, ParseImdlDocument_1.convertFeatureTable)(descr.batch.featureTable, descr.batch.modelId);
        batch = {
            options: { ...descr.batch },
            range: core_geometry_1.Range3d.fromJSON(descr.batch.range),
            featureTable,
        };
    }
    let branch;
    if (descr.translation) {
        branch = { transform: core_geometry_1.Transform.createTranslation(core_geometry_1.Point3d.fromJSON(descr.translation)) };
    }
    return (0, GraphicTemplate_1.createGraphicTemplate)({
        nodes: [{ geometry }],
        batch,
        branch,
        noDispose: true,
    });
}
/** @internal */
function createGraphicFromDescription(descr, context, system) {
    const template = createGraphicTemplateFromDescription(descr, context, system);
    return system.createGraphicFromTemplate({ template });
}
//# sourceMappingURL=ImdlGraphicsCreator.js.map