/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module WebGL
 */
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
import { Id64 } from "@itwin/core-bentley";
import { BatchType, PackedFeature } from "@itwin/core-common";
import { ShaderProgramExecutor } from "./ShaderProgram";
/** Iterates over features visible in tiles selected for display by a Target by inspecting its RenderCommands.
 * @internal
 */
export class VisibleTileFeatures {
    includeNonLocatable;
    renderCommands;
    target;
    iModel;
    constructor(commands, options, target, iModel) {
        this.includeNonLocatable = true === options.includeNonLocatable;
        this.renderCommands = commands;
        this.target = target;
        this.iModel = iModel;
        target.compositor.preDraw();
    }
    [Symbol.iterator]() {
        return iterator(this);
    }
}
const clippedPasses = [
    15 /* RenderPass.BackgroundMap */,
    1 /* RenderPass.OpaqueLayers */,
    2 /* RenderPass.OpaqueLinear */,
    3 /* RenderPass.OpaquePlanar */,
    5 /* RenderPass.OpaqueGeneral */,
    7 /* RenderPass.TranslucentLayers */,
    8 /* RenderPass.Translucent */,
    11 /* RenderPass.OverlayLayers */,
];
function isFeatureVisible(feature, target, includeNonLocatable) {
    const ovrs = target.currentFeatureSymbologyOverrides;
    if (!ovrs)
        return true;
    const app = target.currentBranch.getFeatureAppearance(ovrs, feature.elementId.lower, feature.elementId.upper, feature.subCategoryId.lower, feature.subCategoryId.upper, feature.geometryClass, feature.modelId.lower, feature.modelId.upper, BatchType.Primary, feature.animationNodeId);
    return undefined !== app && (includeNonLocatable || !app.nonLocatable);
}
function* commandIterator(features, pass) {
    const env_1 = { stack: [], error: void 0, hasError: false };
    try {
        const commands = features.renderCommands.getCommands(pass);
        const executor = __addDisposableResource(env_1, new ShaderProgramExecutor(features.target, pass), false);
        for (const command of commands) {
            if (command.opcode !== "drawPrimitive")
                command.execute(executor);
            if (command.opcode !== "pushBatch")
                continue;
            const ovrs = command.batch.getOverrides(features.target, features.target.currentBranch);
            if (ovrs.allHidden)
                continue;
            const scratchFeature = PackedFeature.createWithIndex();
            const table = command.batch.featureTable;
            for (const feature of table.iterable(scratchFeature)) {
                if (!ovrs.anyOverridden || isFeatureVisible(feature, features.target, features.includeNonLocatable)) {
                    yield {
                        elementId: Id64.fromUint32PairObject(feature.elementId),
                        subCategoryId: Id64.fromUint32PairObject(feature.subCategoryId),
                        geometryClass: feature.geometryClass,
                        modelId: Id64.fromUint32PairObject(feature.modelId),
                        iModel: command.batch.batchIModel ?? features.iModel,
                    };
                }
            }
        }
    }
    catch (e_1) {
        env_1.error = e_1;
        env_1.hasError = true;
    }
    finally {
        __disposeResources(env_1);
    }
}
function* iterator(features) {
    try {
        features.target.pushViewClip();
        for (const pass of clippedPasses)
            yield* commandIterator(features, pass);
    }
    finally {
        features.target.popViewClip();
    }
}
//# sourceMappingURL=VisibleTileFeatures.js.map