All files / src illusion-engine.ts

100% Statements 225/225
75.48% Branches 157/208
96.67% Functions 29/30
100% Lines 225/225

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 2251x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 24x 6x 6x 24x 24x 24x 31x 31x 7x 7x 7x 7x 31x 31x 3x 3x 3x 31x 31x 1x 1x 31x 31x 1x 1x 31x 31x 7x 7x 31x 31x 31x 31x 31x 31x 31x 1x 1x 31x 31x 31x 31x 31x 12x 12x 12x 12x 31x 31x 31x 31x 31x 31x 31x 31x 8x 8x 8x 8x 7x 8x 8x 8x 31x 31x 31x 31x 31x 31x 11x 11x 11x 11x 31x 31x 31x 31x 31x 31x 31x 31x 31x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 5x 5x 5x 5x 5x 2x 2x 3x 3x 5x 1x 5x 5x 5x 5x 3x 4x 4x 4x 6x 4x 4x 31x 31x 31x 31x 31x 26x 26x 26x 26x 31x 31x 31x 31x 31x 31x 7x 1x 1x 6x 6x 7x 7x 31x 31x 31x 31x 31x 31x 4x 4x 3x 4x 4x 4x 31x 31x 31x 31x 31x 31x 31x 3x 3x 31x 31x 31x 31x 31x 31x 31x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 2x 2x 31x
 
import { MessageType } from './core/message-type';
import { Target } from './model/target';
import { Servicer } from './servicer/servicer';
import { Options } from './options';
import { Source } from './model/source';
import { FilterType } from './enums/filter-type';
import { Filter } from './model/filter';
import { Layer } from './model/layer';
import { FileSystem } from './model/file-system'
import { ParserType } from './enums/parser-type';
import { ZipOptions } from './interfaces/zip-options';
import { FiltersConfig } from './interfaces/filters-config';
 
 
const engineCommands = MessageType.engine;
 
export class IllusionEngine {
    private _fileSystem?: FileSystem;
    layers: Array<Layer>;
    target?: Target;
 
    constructor(
        private servicer: Servicer,
        public options: Options,
    ) {
        this.layers = [];
    }
 
    get fileSystem() {
        if(!this._fileSystem) {
            this._fileSystem = new FileSystem(this.servicer, this.options);
        }
 
        return this._fileSystem;
    }
    
    async init() {
        const { workResource, enableLog } = this.options;
        // 由于外部需要动态的支持是否加密模式,所以底层默认开启加密模式,对于明文数据需要在外边先加密一次
        await this.servicer.do(engineCommands.init, [workResource, enableLog, true]);
    }
 
    async prepare(target: Target) {
        await this.servicer.do(engineCommands.prepare, [target.id]);
        this.target = target;
    } 
 
    async submit(clock: number) {
        await this.servicer.do(engineCommands.submit, [clock]);
    }
 
    async stop() {
        await this.servicer.do(engineCommands.stop, []);
    }
 
    async shutdown() {
        await this.servicer.do(engineCommands.shutdown, [])
    }
 
    /**
     * 注册离屏画布
     * @param id - 注册的 id, TODO: id 大于 12 个字符时底层解析有问题,原因不明
     * @param canvas - 画布
     */
    async registerOffscreenCanvas(id: string, canvas: OffscreenCanvas) {
        await this.servicer.do(engineCommands.registerOffscreenCanvas, [id, canvas], [canvas]);
    }
 
    /**
     * 创建数据源
     */
    async createSource(): Promise<Source> {
        const { id } = await this.servicer.do(MessageType.source.create, []);
        const source = new Source(id, this.servicer);
        return source;
    }
 
    /**
     * 创建视图目标
     * @param canvasId - 视图目标 id
     * @param width - 宽度
     * @param height - 高度
     */
    async createTarget(canvasId: string, width: number, height: number): Promise<Target> {
        const { id } = await this.servicer.do(MessageType.viewTarget.create, [canvasId, width, height]);
        const target = new Target(id, width, height, this.servicer);
        // 如果开启 worker, target 自动设置为离屏模式
        if(this.options.useWorker) {
            await target.setOffscreen(true);
        }
        return target;
    }
 
    /**
     * 创建内置的滤镜
     * @param filterType - 滤镜类型
     */
    async createFilterByType(filterType: FilterType) {
        const filterResult = await this.servicer.do(MessageType.filter.createByFilterType, [filterType]);
        const filter = new Filter(filterResult, this.servicer);
        return filter;
    }
 
    /**
     * 通过 shader 创建滤镜
     * @param vs - 顶点着色器文件地址
     * @param fs - 片原着色器文件地址
     * @param name - 滤镜名称
     * @param filterType - 滤镜类型
     */
    async createFilterByShader(vs: string, fs: string, name: string, filterType: FilterType = FilterType.CUSTOM) {
        const filterResult = await this.servicer.do(MessageType.filter.createByShader, [vs, fs, name, filterType]);
        const filter = new Filter(filterResult, this.servicer);
        return filter;
    }
 
    /**
     * 通过滤镜 zip 包生成滤镜,会将 zip 包中的 shader 写入文件系统中
     * @param zipData - zip 包数据
     * @param options - 解析配置
     * @param isEncrypted - zip 包内容是否加密
     */
    async createFiltersByZip(zipData: any, options?: ZipOptions, isEncrypted: boolean = true) {
        const { config: configString, files } = await this.fileSystem.loadZip(zipData, options, isEncrypted);
        let config: FiltersConfig | null = null;
        try {
            config = JSON.parse(configString) as FiltersConfig;
        }
        catch { }
        
        if(!config || !config.filters) {
            throw new Error('filers config invalid');
        }
 
        await Promise.all(config.filters.map(filter => {
            const version = filter.version;
            const shaders = [filter.fs, filter.vs];
            return Promise.all(shaders.filter(shader => shader).map(async(shaderName) => {
                const file = files.find(file => file.name.includes(filter.fs));
                if(!file) {
                    throw new Error(`${shaderName} is not exist in zip`);
                }
 
                let content = await file.async('uint8array');
                if(!isEncrypted) {
                    const encryptBuffer = await this.fileSystem.encryptBuffer(content);
                    content = new Uint8Array(encryptBuffer);
                }
                await this.fileSystem.writeShader(content, shaderName, version);
            }));
        }));
 
        const _filters = await this.servicer.do(MessageType.filter.createByConfig, [configString, this.options.workResource, ParserType.Filter, true]);
        return _filters.map((filterResult: { id: string, params: any, name: string, type: number}) => {
            return new Filter(filterResult, this.servicer);
        });
    }
 
    /**
     * 创建图层
     */
    async createLayer() {
        const { id } = await this.servicer.do(MessageType.layer.create, []);
        const layer = new Layer(id, this.servicer);
        return layer;
    }
 
    /**
     * 添加图层
     * @param layer 图层
     */
    async addLayer(layer: Layer) {
        if(this.layers.includes(layer)) {
            return;
        }
 
        await this.servicer.do(engineCommands.addLayer, [layer.id]);
        this.layers.push(layer);
    }
 
    /**
     * 移除图层
     * @param layer 
     */
    async removeLayer(layer: Layer) {
        const index = this.layers.indexOf(layer);
        if(index >= 0) {
            await this.servicer.do(engineCommands.removeLayer, [layer.id]);
            this.layers.splice(index, 1);
        }
    }
 
    /**
     * 监听事件
     * @param eventName - 事件名
     * @param listener - 事件触发方法
     */
    on(eventName: string, listener: (data: any) => void) {
        this.servicer.addMessageListener(eventName, listener);
    }
 
    /**
     * 监听事件,当事件触发一次后移除监听
     * @param eventName 
     * @param listener 
     */
    once(eventName: string, listener: (data: any) => void) {
        const func = (data: any) => {
            this.off(eventName, func);
            listener(data);
        }
 
        this.on(eventName, func);
    }
 
    /**
     * 移除事件监听
     * @param eventName - 事件名
     * @param listener - 事件触发方法
     */
    off(eventName: string, listener: (data: any) => void) {
        this.servicer.removeMessageListener(eventName, listener);
    }
}