1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813 |
- import { Nullable, IndicesArray, DataArray } from "../types";
- import { Engine, EngineCapabilities } from "../Engines/engine";
- import { VertexBuffer } from "../Meshes/buffer";
- import { InternalTexture } from "../Materials/Textures/internalTexture";
- import { IInternalTextureLoader } from "../Materials/Textures/internalTextureLoader";
- import { Texture } from "../Materials/Textures/texture";
- import { BaseTexture } from "../Materials/Textures/baseTexture";
- import { VideoTexture } from "../Materials/Textures/videoTexture";
- import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
- import { Effect } from "../Materials/effect";
- import { DataBuffer } from '../Meshes/dataBuffer';
- import { Tools } from "../Misc/tools";
- import { Observer } from "../Misc/observable";
- import { EnvironmentTextureTools, EnvironmentTextureSpecularInfoV1 } from "../Misc/environmentTextureTools";
- import { Color4, Matrix, Viewport, Color3 } from "../Maths/math";
- import { Scene } from "../scene";
- import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
- import { IPipelineContext } from './IPipelineContext';
- import { WebRequest } from '../Misc/webRequest';
- import { NativeShaderProcessor } from './Native/nativeShaderProcessor';
- import { IMatrixLike, IVector2Like, IVector3Like, IVector4Like, IColor3Like, IColor4Like } from '../Maths/math.like';
- import { Logger } from "../Misc/logger";
- interface INativeEngine {
- requestAnimationFrame(callback: () => void): void;
- createVertexArray(): any;
- deleteVertexArray(vertexArray: any): void;
- bindVertexArray(vertexArray: any): void;
- createIndexBuffer(data: ArrayBufferView): any;
- deleteIndexBuffer(buffer: any): void;
- recordIndexBuffer(vertexArray: any, buffer: any): void;
- createVertexBuffer(data: ArrayBufferView): any;
- deleteVertexBuffer(buffer: any): void;
- recordVertexBuffer(vertexArray: any, buffer: any, location: number, byteOffset: number, byteStride: number, numElements: number, type: number, normalized: boolean): void;
- createProgram(vertexShader: string, fragmentShader: string): any;
- getUniforms(shaderProgram: any, uniformsNames: string[]): WebGLUniformLocation[];
- getAttributes(shaderProgram: any, attributeNames: string[]): number[];
- setProgram(program: any): void;
- setState(culling: boolean, zOffset: number, reverseSide: boolean): void;
- setZOffset(zOffset: number): void;
- getZOffset(): number;
- setDepthTest(enable: boolean): void;
- getDepthWrite(): boolean;
- setDepthWrite(enable: boolean): void;
- setColorWrite(enable: boolean): void;
- setBlendMode(blendMode: number): void;
- setMatrix(uniform: WebGLUniformLocation, matrix: Float32Array): void;
- setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void;
- setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void;
- setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void;
- setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void;
- setFloatArray(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
- setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
- setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
- setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
- setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void;
- setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void;
- setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void;
- setFloat(uniform: WebGLUniformLocation, value: number): void;
- setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void;
- setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void;
- setBool(uniform: WebGLUniformLocation, bool: number): void;
- setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void;
- createTexture(): WebGLTexture;
- loadTexture(texture: WebGLTexture, buffer: ArrayBuffer | ArrayBufferView | Blob, mipMap: boolean): void;
- loadCubeTexture(texture: WebGLTexture, data: Array<Array<ArrayBufferView>>, flipY : boolean): void;
- getTextureWidth(texture: WebGLTexture): number;
- getTextureHeight(texture: WebGLTexture): number;
- setTextureSampling(texture: WebGLTexture, filter: number): void; // filter is a NativeFilter.XXXX value.
- setTextureWrapMode(texture: WebGLTexture, addressModeU: number, addressModeV: number, addressModeW: number): void; // addressModes are NativeAddressMode.XXXX values.
- setTextureAnisotropicLevel(texture: WebGLTexture, value: number): void;
- setTexture(uniform: WebGLUniformLocation, texture: Nullable<WebGLTexture>): void;
- deleteTexture(texture: Nullable<WebGLTexture>): void;
- createFrameBuffer(texture: WebGLTexture, width: number, height: number, format: number, samplingMode: number, generateStencilBuffer: boolean, generateDepthBuffer: boolean, generateMipMaps: boolean): WebGLFramebuffer;
- bindFrameBuffer(frameBuffer: WebGLFramebuffer): void;
- unbindFrameBuffer(frameBuffer: WebGLFramebuffer): void;
- drawIndexed(fillMode: number, indexStart: number, indexCount: number): void;
- draw(fillMode: number, vertexStart: number, vertexCount: number): void;
- clear(r: number, g: number, b: number, a: number, backBuffer: boolean, depth: boolean, stencil: boolean): void;
- getRenderWidth(): number;
- getRenderHeight(): number;
- }
- class NativePipelineContext implements IPipelineContext {
- // TODO: async should be true?
- public isAsync = false;
- public isReady = false;
- // TODO: what should this do?
- public _handlesSpectorRebuildCallback(onCompiled: (compiledObject: any) => void): void {
- throw new Error("Not implemented");
- }
- public nativeProgram: any;
- private _valueCache: { [key: string]: any } = {};
- private _uniforms: { [key: string]: Nullable<WebGLUniformLocation> };
- public engine: NativeEngine;
- public context?: WebGLRenderingContext;
- public vertexShader?: WebGLShader;
- public fragmentShader?: WebGLShader;
- public isParallelCompiled: boolean;
- public onCompiled?: () => void;
- public transformFeedback?: WebGLTransformFeedback | null;
- public _fillEffectInformation(effect: Effect, uniformBuffersNames: { [key: string]: number }, uniformsNames: string[], uniforms: { [key: string]: Nullable<WebGLUniformLocation> }, samplerList: string[], samplers: { [key: string]: number }, attributesNames: string[], attributes: number[]) {
- const engine = this.engine;
- if (engine.supportsUniformBuffers) {
- for (var name in uniformBuffersNames) {
- effect.bindUniformBlock(name, uniformBuffersNames[name]);
- }
- }
- const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames);
- effectAvailableUniforms.forEach((uniform, index) => {
- uniforms[uniformsNames[index]] = uniform;
- });
- this._uniforms = uniforms;
- let index: number;
- for (index = 0; index < samplerList.length; index++) {
- const sampler = effect.getUniform(samplerList[index]);
- if (sampler == null) {
- samplerList.splice(index, 1);
- index--;
- }
- }
- samplerList.forEach((name, index) => {
- samplers[name] = index;
- });
- attributes.push(...engine.getAttributes(this, attributesNames));
- }
- /**
- * Release all associated resources.
- **/
- public dispose() {
- this._uniforms = { };
- }
- /** @hidden */
- public _cacheMatrix(uniformName: string, matrix: IMatrixLike): boolean {
- var cache = this._valueCache[uniformName];
- var flag = matrix.updateFlag;
- if (cache !== undefined && cache === flag) {
- return false;
- }
- this._valueCache[uniformName] = flag;
- return true;
- }
- /** @hidden */
- public _cacheFloat2(uniformName: string, x: number, y: number): boolean {
- var cache = this._valueCache[uniformName];
- if (!cache) {
- cache = [x, y];
- this._valueCache[uniformName] = cache;
- return true;
- }
- var changed = false;
- if (cache[0] !== x) {
- cache[0] = x;
- changed = true;
- }
- if (cache[1] !== y) {
- cache[1] = y;
- changed = true;
- }
- return changed;
- }
- /** @hidden */
- public _cacheFloat3(uniformName: string, x: number, y: number, z: number): boolean {
- var cache = this._valueCache[uniformName];
- if (!cache) {
- cache = [x, y, z];
- this._valueCache[uniformName] = cache;
- return true;
- }
- var changed = false;
- if (cache[0] !== x) {
- cache[0] = x;
- changed = true;
- }
- if (cache[1] !== y) {
- cache[1] = y;
- changed = true;
- }
- if (cache[2] !== z) {
- cache[2] = z;
- changed = true;
- }
- return changed;
- }
- /** @hidden */
- public _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): boolean {
- var cache = this._valueCache[uniformName];
- if (!cache) {
- cache = [x, y, z, w];
- this._valueCache[uniformName] = cache;
- return true;
- }
- var changed = false;
- if (cache[0] !== x) {
- cache[0] = x;
- changed = true;
- }
- if (cache[1] !== y) {
- cache[1] = y;
- changed = true;
- }
- if (cache[2] !== z) {
- cache[2] = z;
- changed = true;
- }
- if (cache[3] !== w) {
- cache[3] = w;
- changed = true;
- }
- return changed;
- }
- /**
- * Sets an interger value on a uniform variable.
- * @param uniformName Name of the variable.
- * @param value Value to be set.
- */
- public setInt(uniformName: string, value: number): void {
- var cache = this._valueCache[uniformName];
- if (cache !== undefined && cache === value) {
- return;
- }
- this._valueCache[uniformName] = value;
- this.engine.setInt(this._uniforms[uniformName], value);
- }
- /**
- * Sets an int array on a uniform variable.
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setIntArray(uniformName: string, array: Int32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setIntArray(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setIntArray2(uniformName: string, array: Int32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setIntArray2(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setIntArray3(uniformName: string, array: Int32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setIntArray3(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setIntArray4(uniformName: string, array: Int32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setIntArray4(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an float array on a uniform variable.
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setFloatArray(uniformName: string, array: Float32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setFloatArray(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setFloatArray2(uniformName: string, array: Float32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setFloatArray2(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setFloatArray3(uniformName: string, array: Float32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setFloatArray3(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setFloatArray4(uniformName: string, array: Float32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setFloatArray4(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an array on a uniform variable.
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setArray(uniformName: string, array: number[]): void {
- this._valueCache[uniformName] = null;
- this.engine.setArray(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setArray2(uniformName: string, array: number[]): void {
- this._valueCache[uniformName] = null;
- this.engine.setArray2(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- * @returns this effect.
- */
- public setArray3(uniformName: string, array: number[]): void {
- this._valueCache[uniformName] = null;
- this.engine.setArray3(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
- * @param uniformName Name of the variable.
- * @param array array to be set.
- */
- public setArray4(uniformName: string, array: number[]): void {
- this._valueCache[uniformName] = null;
- this.engine.setArray4(this._uniforms[uniformName]!, array);
- }
- /**
- * Sets matrices on a uniform variable.
- * @param uniformName Name of the variable.
- * @param matrices matrices to be set.
- */
- public setMatrices(uniformName: string, matrices: Float32Array): void {
- if (!matrices) {
- return;
- }
- this._valueCache[uniformName] = null;
- this.engine.setMatrices(this._uniforms[uniformName]!, matrices);
- }
- /**
- * Sets matrix on a uniform variable.
- * @param uniformName Name of the variable.
- * @param matrix matrix to be set.
- */
- public setMatrix(uniformName: string, matrix: IMatrixLike): void {
- if (this._cacheMatrix(uniformName, matrix)) {
- this.engine.setMatrices(this._uniforms[uniformName]!, matrix.toArray() as Float32Array);
- }
- }
- /**
- * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
- * @param uniformName Name of the variable.
- * @param matrix matrix to be set.
- */
- public setMatrix3x3(uniformName: string, matrix: Float32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setMatrix3x3(this._uniforms[uniformName]!, matrix);
- }
- /**
- * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
- * @param uniformName Name of the variable.
- * @param matrix matrix to be set.
- */
- public setMatrix2x2(uniformName: string, matrix: Float32Array): void {
- this._valueCache[uniformName] = null;
- this.engine.setMatrix2x2(this._uniforms[uniformName]!, matrix);
- }
- /**
- * Sets a float on a uniform variable.
- * @param uniformName Name of the variable.
- * @param value value to be set.
- * @returns this effect.
- */
- public setFloat(uniformName: string, value: number): void {
- var cache = this._valueCache[uniformName];
- if (cache !== undefined && cache === value) {
- return;
- }
- this._valueCache[uniformName] = value;
- this.engine.setFloat(this._uniforms[uniformName]!, value);
- }
- /**
- * Sets a boolean on a uniform variable.
- * @param uniformName Name of the variable.
- * @param bool value to be set.
- */
- public setBool(uniformName: string, bool: boolean): void {
- var cache = this._valueCache[uniformName];
- if (cache !== undefined && cache === bool) {
- return;
- }
- this._valueCache[uniformName] = bool;
- this.engine.setBool(this._uniforms[uniformName]!, bool ? 1 : 0);
- }
- /**
- * Sets a Vector2 on a uniform variable.
- * @param uniformName Name of the variable.
- * @param vector2 vector2 to be set.
- */
- public setVector2(uniformName: string, vector2: IVector2Like): void {
- if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
- this.engine.setFloat2(this._uniforms[uniformName]!, vector2.x, vector2.y);
- }
- }
- /**
- * Sets a float2 on a uniform variable.
- * @param uniformName Name of the variable.
- * @param x First float in float2.
- * @param y Second float in float2.
- */
- public setFloat2(uniformName: string, x: number, y: number): void {
- if (this._cacheFloat2(uniformName, x, y)) {
- this.engine.setFloat2(this._uniforms[uniformName]!, x, y);
- }
- }
- /**
- * Sets a Vector3 on a uniform variable.
- * @param uniformName Name of the variable.
- * @param vector3 Value to be set.
- */
- public setVector3(uniformName: string, vector3: IVector3Like): void {
- if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
- this.engine.setFloat3(this._uniforms[uniformName]!, vector3.x, vector3.y, vector3.z);
- }
- }
- /**
- * Sets a float3 on a uniform variable.
- * @param uniformName Name of the variable.
- * @param x First float in float3.
- * @param y Second float in float3.
- * @param z Third float in float3.
- */
- public setFloat3(uniformName: string, x: number, y: number, z: number): void {
- if (this._cacheFloat3(uniformName, x, y, z)) {
- this.engine.setFloat3(this._uniforms[uniformName]!, x, y, z);
- }
- }
- /**
- * Sets a Vector4 on a uniform variable.
- * @param uniformName Name of the variable.
- * @param vector4 Value to be set.
- */
- public setVector4(uniformName: string, vector4: IVector4Like): void {
- if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
- this.engine.setFloat4(this._uniforms[uniformName]!, vector4.x, vector4.y, vector4.z, vector4.w);
- }
- }
- /**
- * Sets a float4 on a uniform variable.
- * @param uniformName Name of the variable.
- * @param x First float in float4.
- * @param y Second float in float4.
- * @param z Third float in float4.
- * @param w Fourth float in float4.
- * @returns this effect.
- */
- public setFloat4(uniformName: string, x: number, y: number, z: number, w: number): void {
- if (this._cacheFloat4(uniformName, x, y, z, w)) {
- this.engine.setFloat4(this._uniforms[uniformName]!, x, y, z, w);
- }
- }
- /**
- * Sets a Color3 on a uniform variable.
- * @param uniformName Name of the variable.
- * @param color3 Value to be set.
- */
- public setColor3(uniformName: string, color3: IColor3Like): void {
- if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
- this.engine.setFloat3(this._uniforms[uniformName]!, color3.r, color3.g, color3.b);
- }
- }
- /**
- * Sets a Color4 on a uniform variable.
- * @param uniformName Name of the variable.
- * @param color3 Value to be set.
- * @param alpha Alpha value to be set.
- */
- public setColor4(uniformName: string, color3: IColor3Like, alpha: number): void {
- if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
- this.engine.setFloat4(this._uniforms[uniformName]!, color3.r, color3.g, color3.b, alpha);
- }
- }
- /**
- * Sets a Color4 on a uniform variable
- * @param uniformName defines the name of the variable
- * @param color4 defines the value to be set
- */
- public setDirectColor4(uniformName: string, color4: IColor4Like): void {
- if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
- this.engine.setDirectColor4(this._uniforms[uniformName], color4);
- }
- }
- }
- /**
- * Container for accessors for natively-stored mesh data buffers.
- */
- class NativeDataBuffer extends DataBuffer {
- /**
- * Accessor value used to identify/retrieve a natively-stored index buffer.
- */
- public nativeIndexBuffer?: any;
- /**
- * Accessor value used to identify/retrieve a natively-stored vertex buffer.
- */
- public nativeVertexBuffer?: any;
- }
- // TODO: change this to match bgfx.
- // Must match Filter enum in SpectreEngine.h.
- class NativeFilter {
- public static readonly POINT = 0;
- public static readonly MINPOINT_MAGPOINT_MIPPOINT = NativeFilter.POINT;
- public static readonly BILINEAR = 1;
- public static readonly MINLINEAR_MAGLINEAR_MIPPOINT = NativeFilter.BILINEAR;
- public static readonly TRILINEAR = 2;
- public static readonly MINLINEAR_MAGLINEAR_MIPLINEAR = NativeFilter.TRILINEAR;
- public static readonly ANISOTROPIC = 3;
- public static readonly POINT_COMPARE = 4;
- public static readonly TRILINEAR_COMPARE = 5;
- public static readonly MINBILINEAR_MAGPOINT = 6;
- public static readonly MINLINEAR_MAGPOINT_MIPLINEAR = NativeFilter.MINBILINEAR_MAGPOINT;
- public static readonly MINPOINT_MAGPOINT_MIPLINEAR = 7;
- public static readonly MINPOINT_MAGLINEAR_MIPPOINT = 8;
- public static readonly MINPOINT_MAGLINEAR_MIPLINEAR = 9;
- public static readonly MINLINEAR_MAGPOINT_MIPPOINT = 10;
- }
- // TODO: change this to match bgfx.
- // Must match AddressMode enum in SpectreEngine.h.
- class NativeAddressMode {
- public static readonly WRAP = 0;
- public static readonly MIRROR = 1;
- public static readonly CLAMP = 2;
- public static readonly BORDER = 3;
- public static readonly MIRROR_ONCE = 4;
- }
- class NativeTextureFormat {
- public static readonly RGBA8 = 0;
- public static readonly RGBA32F = 1;
- }
- /** @hidden */
- declare var nativeEngine: INativeEngine;
- /** @hidden */
- export class NativeEngine extends Engine {
- private readonly _native: INativeEngine = nativeEngine;
- public getHardwareScalingLevel(): number {
- return 1.0;
- }
- public constructor() {
- super(null);
- this._webGLVersion = 2;
- this.disableUniformBuffers = true;
- // TODO: Initialize this more correctly based on the hardware capabilities.
- // Init caps
- this._caps = new EngineCapabilities();
- this._caps.maxTexturesImageUnits = 16;
- this._caps.maxVertexTextureImageUnits = 16;
- this._caps.maxTextureSize = 512;
- this._caps.maxCubemapTextureSize = 512;
- this._caps.maxRenderTextureSize = 512;
- this._caps.maxVertexAttribs = 16;
- this._caps.maxVaryingVectors = 16;
- this._caps.maxFragmentUniformVectors = 16;
- this._caps.maxVertexUniformVectors = 16;
- // Extensions
- this._caps.standardDerivatives = true;
- this._caps.astc = null;
- this._caps.s3tc = null;
- this._caps.pvrtc = null;
- this._caps.etc1 = null;
- this._caps.etc2 = null;
- this._caps.maxAnisotropy = 16; // TODO: Retrieve this smartly. Currently set to D3D11 maximum allowable value.
- this._caps.uintIndices = false;
- this._caps.fragmentDepthSupported = false;
- this._caps.highPrecisionShaderSupported = true;
- this._caps.colorBufferFloat = false;
- this._caps.textureFloat = false;
- this._caps.textureFloatLinearFiltering = false;
- this._caps.textureFloatRender = false;
- this._caps.textureHalfFloat = false;
- this._caps.textureHalfFloatLinearFiltering = false;
- this._caps.textureHalfFloatRender = false;
- this._caps.textureLOD = true;
- this._caps.drawBuffersExtension = false;
- this._caps.depthTextureExtension = false;
- this._caps.vertexArrayObject = true;
- this._caps.instancedArrays = false;
- Tools.Log("Babylon Native (v" + Engine.Version + ") launched");
- // Wrappers
- if (typeof URL === "undefined") {
- (window.URL as any) = {
- createObjectURL: function() { },
- revokeObjectURL: function() { }
- };
- }
- if (typeof Blob === "undefined") {
- (window.Blob as any) = function() { };
- }
- // Shader processor
- this._shaderProcessor = new NativeShaderProcessor();
- }
- /**
- * Can be used to override the current requestAnimationFrame requester.
- * @hidden
- */
- protected _queueNewFrame(bindedRenderFunction: any, requester: any): number {
- this._native.requestAnimationFrame(bindedRenderFunction);
- return 0;
- }
- public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
- this._native.clear(color.r, color.g, color.b, color.a, backBuffer, depth, stencil);
- }
- public createIndexBuffer(indices: IndicesArray): NativeDataBuffer {
- const data = this._normalizeIndexData(indices);
- const buffer = new NativeDataBuffer();
- buffer.references = 1;
- buffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
- buffer.nativeIndexBuffer = this._native.createIndexBuffer(data);
- return buffer;
- }
- public createVertexBuffer(data: DataArray): NativeDataBuffer {
- const buffer = new NativeDataBuffer();
- buffer.references = 1;
- buffer.nativeVertexBuffer = this._native.createVertexBuffer(ArrayBuffer.isView(data) ? data : new Float32Array(data));
- return buffer;
- }
- public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<NativeDataBuffer>, effect: Effect): WebGLVertexArrayObject {
- const vertexArray = this._native.createVertexArray();
- if (indexBuffer) {
- this._native.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);
- }
- const attributes = effect.getAttributesNames();
- for (let index = 0; index < attributes.length; index++) {
- const location = effect.getAttributeLocation(index);
- if (location >= 0) {
- const kind = attributes[index];
- const vertexBuffer = vertexBuffers[kind];
- if (vertexBuffer) {
- const buffer = vertexBuffer.getBuffer() as Nullable<NativeDataBuffer>;
- if (buffer) {
- this._native.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized);
- }
- }
- }
- }
- return vertexArray;
- }
- public bindVertexArrayObject(vertexArray: WebGLVertexArrayObject): void {
- this._native.bindVertexArray(vertexArray);
- }
- public releaseVertexArrayObject(vertexArray: WebGLVertexArrayObject) {
- this._native.deleteVertexArray(vertexArray);
- }
- public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
- const nativePipelineContext = pipelineContext as NativePipelineContext;
- return this._native.getAttributes(nativePipelineContext.nativeProgram, attributesNames);
- }
- /**
- * Draw a list of indexed primitives
- * @param fillMode defines the primitive to use
- * @param indexStart defines the starting index
- * @param indexCount defines the number of index to draw
- * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
- */
- public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
- // Apply states
- this._drawCalls.addCount(1, false);
- // TODO: Make this implementation more robust like core Engine version.
- // Render
- //var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
- //var mult = this._uintIndicesCurrentlySet ? 4 : 2;
- // if (instancesCount) {
- // this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
- // } else {
- this._native.drawIndexed(fillMode, indexStart, indexCount);
- // }
- }
- /**
- * Draw a list of unindexed primitives
- * @param fillMode defines the primitive to use
- * @param verticesStart defines the index of first vertex to draw
- * @param verticesCount defines the count of vertices to draw
- * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
- */
- public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
- // Apply states
- this._drawCalls.addCount(1, false);
- // TODO: Make this implementation more robust like core Engine version.
- // if (instancesCount) {
- // this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
- // } else {
- this._native.draw(fillMode, verticesStart, verticesCount);
- // }
- }
- public createPipelineContext(): IPipelineContext {
- return new NativePipelineContext();
- }
- public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean, rebuildRebind: any, defines: Nullable<string>, transformFeedbackVaryings: Nullable<string[]>) {
- const nativePipelineContext = pipelineContext as NativePipelineContext;
- if (createAsRaw) {
- nativePipelineContext.nativeProgram = this.createRawShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
- }
- else {
- nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
- }
- }
- /** @hidden */
- public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
- // TODO: support async shader compilcation
- return true;
- }
- /** @hidden */
- public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
- // TODO: support async shader compilcation
- action();
- }
- public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): any {
- throw new Error("Not Supported");
- }
- public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): any {
- this.onBeforeShaderCompilationObservable.notifyObservers(this);
- const program = this._native.createProgram(
- Engine._concatenateShader(vertexCode, defines),
- Engine._concatenateShader(fragmentCode, defines)
- );
- this.onAfterShaderCompilationObservable.notifyObservers(this);
- return program;
- }
- protected _setProgram(program: WebGLProgram): void {
- if (this._currentProgram !== program) {
- this._native.setProgram(program);
- this._currentProgram = program;
- }
- }
- public _releaseEffect(effect: Effect): void {
- // TODO
- }
- public _deletePipelineContext(pipelineContext: IPipelineContext): void {
- // TODO
- }
- public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): WebGLUniformLocation[] {
- const nativePipelineContext = pipelineContext as NativePipelineContext;
- return this._native.getUniforms(nativePipelineContext.nativeProgram, uniformsNames);
- }
- public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
- // TODO
- throw new Error("Not Implemented");
- }
- public bindSamplers(effect: Effect): void {
- const nativePipelineContext = effect.getPipelineContext() as NativePipelineContext;
- this._setProgram(nativePipelineContext.nativeProgram);
- // TODO: share this with engine?
- var samplers = effect.getSamplers();
- for (var index = 0; index < samplers.length; index++) {
- var uniform = effect.getUniform(samplers[index]);
- if (uniform) {
- this._boundUniforms[index] = uniform;
- }
- }
- this._currentEffect = null;
- }
- public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
- if (!uniform) {
- return;
- }
- this._native.setMatrix(uniform, matrix.toArray() as Float32Array);
- }
- public getRenderWidth(useScreen = false): number {
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget.width;
- }
- return this._native.getRenderWidth();
- }
- public getRenderHeight(useScreen = false): number {
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget.height;
- }
- return this._native.getRenderHeight();
- }
- public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
- // TODO: Implement.
- this._cachedViewport = viewport;
- }
- public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
- this._native.setState(culling, zOffset, reverseSide);
- }
- /**
- * Set the z offset to apply to current rendering
- * @param value defines the offset to apply
- */
- public setZOffset(value: number): void {
- this._native.setZOffset(value);
- }
- /**
- * Gets the current value of the zOffset
- * @returns the current zOffset state
- */
- public getZOffset(): number {
- return this._native.getZOffset();
- }
- /**
- * Enable or disable depth buffering
- * @param enable defines the state to set
- */
- public setDepthBuffer(enable: boolean): void {
- this._native.setDepthTest(enable);
- }
- /**
- * Gets a boolean indicating if depth writing is enabled
- * @returns the current depth writing state
- */
- public getDepthWrite(): boolean {
- return this._native.getDepthWrite();
- }
- /**
- * Enable or disable depth writing
- * @param enable defines the state to set
- */
- public setDepthWrite(enable: boolean): void {
- this._native.setDepthWrite(enable);
- }
- /**
- * Enable or disable color writing
- * @param enable defines the state to set
- */
- public setColorWrite(enable: boolean): void {
- this._native.setColorWrite(enable);
- this._colorWrite = enable;
- }
- /**
- * Gets a boolean indicating if color writing is enabled
- * @returns the current color writing state
- */
- public getColorWrite(): boolean {
- return this._colorWrite;
- }
- /**
- * Sets alpha constants used by some alpha blending modes
- * @param r defines the red component
- * @param g defines the green component
- * @param b defines the blue component
- * @param a defines the alpha component
- */
- public setAlphaConstants(r: number, g: number, b: number, a: number) {
- throw new Error("Setting alpha blend constant color not yet implemented.");
- }
- /**
- * Sets the current alpha mode
- * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
- * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
- * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
- */
- public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
- if (this._alphaMode === mode) {
- return;
- }
- this._native.setBlendMode(mode);
- if (!noDepthWriteChange) {
- this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
- }
- this._alphaMode = mode;
- }
- /**
- * Gets the current alpha mode
- * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
- * @returns the current alpha mode
- */
- public getAlphaMode(): number {
- return this._alphaMode;
- }
- public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setIntArray(uniform, array);
- }
- public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setIntArray2(uniform, array);
- }
- public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setIntArray3(uniform, array);
- }
- public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setIntArray4(uniform, array);
- }
- public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setFloatArray(uniform, array);
- }
- public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setFloatArray2(uniform, array);
- }
- public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setFloatArray3(uniform, array);
- }
- public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setFloatArray4(uniform, array);
- }
- public setArray(uniform: WebGLUniformLocation, array: number[]): void {
- if (!uniform) {
- return;
- }
- this._native.setFloatArray(uniform, array);
- }
- public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
- if (!uniform) {
- return;
- }
- this._native.setFloatArray2(uniform, array);
- }
- public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
- if (!uniform) {
- return;
- }
- this._native.setFloatArray3(uniform, array);
- }
- public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
- if (!uniform) {
- return;
- }
- this._native.setFloatArray4(uniform, array);
- }
- public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setMatrices(uniform, matrices);
- }
- public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setMatrix3x3(uniform, matrix);
- }
- public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
- if (!uniform) {
- return;
- }
- this._native.setMatrix2x2(uniform, matrix);
- }
- public setFloat(uniform: WebGLUniformLocation, value: number): void {
- if (!uniform) {
- return;
- }
- this._native.setFloat(uniform, value);
- }
- public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
- if (!uniform) {
- return;
- }
- this._native.setFloat2(uniform, x, y);
- }
- public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
- if (!uniform) {
- return;
- }
- this._native.setFloat3(uniform, x, y, z);
- }
- public setBool(uniform: WebGLUniformLocation, bool: number): void {
- if (!uniform) {
- return;
- }
- this._native.setBool(uniform, bool);
- }
- public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
- if (!uniform) {
- return;
- }
- this._native.setFloat4(uniform, x, y, z, w);
- }
- public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
- if (!uniform) {
- return;
- }
- this._native.setFloat3(uniform, color3.r, color3.g, color3.b);
- }
- public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
- if (!uniform) {
- return;
- }
- this._native.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);
- }
- public wipeCaches(bruteForce?: boolean): void {
- if (this.preventCacheWipeBetweenFrames) {
- return;
- }
- this.resetTextureCache();
- this._currentEffect = null;
- if (bruteForce) {
- this._currentProgram = null;
- this._stencilState.reset();
- this._depthCullingState.reset();
- this._alphaState.reset();
- }
- this._cachedVertexBuffers = null;
- this._cachedIndexBuffer = null;
- this._cachedEffectForVertexBuffers = null;
- }
- public _createTexture(): WebGLTexture {
- return this._native.createTexture();
- }
- protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
- this._native.deleteTexture(texture);
- }
- // TODO: Refactor to share more logic with babylon.engine.ts version.
- /**
- * Usually called from BABYLON.Texture.ts.
- * Passed information to create a WebGLTexture
- * @param urlArg defines a value which contains one of the following:
- * * A conventional http URL, e.g. 'http://...' or 'file://...'
- * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
- * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
- * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
- * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
- * @param scene needed for loading to the correct scene
- * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
- * @param onLoad optional callback to be called upon successful completion
- * @param onError optional callback to be called upon failure
- * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), or a Blob
- * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
- * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
- * @param forcedExtension defines the extension to use to pick the right loader
- * @returns a InternalTexture for assignment back into BABYLON.Texture
- */
- public createTexture(
- urlArg: Nullable<string>,
- noMipmap: boolean,
- invertY: boolean,
- scene: Nullable<Scene>,
- samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
- onLoad: Nullable<() => void> = null,
- onError: Nullable<(message: string, exception: any) => void> = null,
- buffer: Nullable<string | ArrayBuffer | Blob> = null,
- fallback: Nullable<InternalTexture> = null,
- format: Nullable<number> = null,
- forcedExtension: Nullable<string> = null): InternalTexture {
- var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
- var fromData = url.substr(0, 5) === "data:";
- var fromBlob = url.substr(0, 5) === "blob:";
- var isBase64 = fromData && url.indexOf("base64") !== -1;
- let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
- // establish the file extension, if possible
- var lastDot = url.lastIndexOf('.');
- var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
- // TODO: Add support for compressed texture formats.
- var textureFormatInUse: Nullable<string> = null;
- let loader: Nullable<IInternalTextureLoader> = null;
- for (let availableLoader of Engine._TextureLoaders) {
- if (availableLoader.canLoad(extension, textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
- loader = availableLoader;
- break;
- }
- }
- if (loader) {
- url = loader.transformUrl(url, textureFormatInUse);
- }
- if (scene) {
- scene._addPendingData(texture);
- }
- texture.url = url;
- texture.generateMipMaps = !noMipmap;
- texture.samplingMode = samplingMode;
- texture.invertY = invertY;
- if (!this.doNotHandleContextLost) {
- // Keep a link to the buffer only if we plan to handle context lost
- texture._buffer = buffer;
- }
- let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
- if (onLoad && !fallback) {
- onLoadObserver = texture.onLoadedObservable.add(onLoad);
- }
- if (!fallback) { this._internalTexturesCache.push(texture); }
- let onInternalError = (message?: string, exception?: any) => {
- if (scene) {
- scene._removePendingData(texture);
- }
- let customFallback = false;
- if (loader) {
- const fallbackUrl = loader.getFallbackTextureUrl(url, textureFormatInUse);
- if (fallbackUrl) {
- // Add Back
- customFallback = true;
- this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
- }
- }
- if (!customFallback) {
- if (onLoadObserver) {
- texture.onLoadedObservable.remove(onLoadObserver);
- }
- if (Tools.UseFallbackTexture) {
- this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
- }
- }
- if (onError) {
- onError(message || "Unknown error", exception);
- }
- };
- // processing for non-image formats
- if (loader) {
- throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
- // var callback = (data: string | ArrayBuffer) => {
- // loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void) => {
- // this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, () => {
- // done();
- // return false;
- // },
- // samplingMode);
- // });
- // }
- // if (!buffer) {
- // this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
- // onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
- // });
- // } else {
- // callback(buffer as ArrayBuffer);
- // }
- } else {
- var onload = (data: string | ArrayBuffer | Blob, responseURL?: string) => {
- if (typeof (data) === "string") {
- throw new Error("Loading textures from string data not yet implemented.");
- }
- if (fromBlob && !this.doNotHandleContextLost) {
- // We need to store the image if we need to rebuild the texture
- // in case of a webgl context lost
- texture._buffer = data;
- }
- let webGLTexture = texture._webGLTexture;
- if (!webGLTexture) {
- // this.resetTextureCache();
- if (scene) {
- scene._removePendingData(texture);
- }
- return;
- }
- this._native.loadTexture(webGLTexture, data, !noMipmap);
- if (invertY) {
- throw new Error("Support for textures with inverted Y coordinates not yet implemented.");
- }
- //this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
- texture.baseWidth = this._native.getTextureWidth(webGLTexture);
- texture.baseHeight = this._native.getTextureHeight(webGLTexture);
- texture.width = texture.baseWidth;
- texture.height = texture.baseHeight;
- texture.isReady = true;
- var filter = this._getSamplingFilter(samplingMode);
- this._native.setTextureSampling(webGLTexture, filter);
- // this.resetTextureCache();
- if (scene) {
- scene._removePendingData(texture);
- }
- texture.onLoadedObservable.notifyObservers(texture);
- texture.onLoadedObservable.clear();
- };
- if (buffer instanceof ArrayBuffer) {
- onload(buffer);
- } else if (ArrayBuffer.isView(buffer)) {
- onload(buffer.buffer);
- } else if (buffer instanceof Blob) {
- throw new Error("Loading texture from Blob not yet implemented.");
- } else if (!fromData) {
- let onLoadFileError = (request?: WebRequest, exception?: any) => {
- onInternalError("Failed to retrieve " + url + ".", exception);
- };
- Tools.LoadFile(url, onload, undefined, undefined, /*useArrayBuffer*/true, onLoadFileError);
- } else {
- onload(Tools.DecodeBase64(buffer as string));
- }
- }
- return texture;
- }
- /**
- * Creates a cube texture
- * @param rootUrl defines the url where the files to load is located
- * @param scene defines the current scene
- * @param files defines the list of files to load (1 per face)
- * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
- * @param onLoad defines an optional callback raised when the texture is loaded
- * @param onError defines an optional callback raised if there is an issue to load the texture
- * @param format defines the format of the data
- * @param forcedExtension defines the extension to use to pick the right loader
- * @param createPolynomials if a polynomial sphere should be created for the cube texture
- * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
- * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
- * @param fallback defines texture to use while falling back when (compressed) texture file not found.
- * @returns the cube texture as an InternalTexture
- */
- public createCubeTexture(
- rootUrl: string,
- scene: Nullable<Scene>,
- files: Nullable<string[]>,
- noMipmap?: boolean,
- onLoad: Nullable<(data?: any) => void> = null,
- onError: Nullable<(message?: string, exception?: any) => void> = null,
- format?: number,
- forcedExtension: any = null,
- createPolynomials = false,
- lodScale: number = 0,
- lodOffset: number = 0,
- fallback: Nullable<InternalTexture> = null): InternalTexture
- {
- var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
- texture.isCube = true;
- texture.url = rootUrl;
- texture.generateMipMaps = !noMipmap;
- texture._lodGenerationScale = lodScale;
- texture._lodGenerationOffset = lodOffset;
- if (!this._doNotHandleContextLost) {
- texture._extension = forcedExtension;
- texture._files = files;
- }
- var lastDot = rootUrl.lastIndexOf('.');
- var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
- if (extension === ".env") {
- const onloaddata = (data: any) => {
- data = data as ArrayBuffer;
- var info = EnvironmentTextureTools.GetEnvInfo(data)!;
- texture.width = info.width;
- texture.height = info.width;
- EnvironmentTextureTools.UploadEnvSpherical(texture, info);
- if (info.version !== 1) {
- throw new Error(`Unsupported babylon environment map version "${info.version}"`);
- }
- let specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
- if (!specularInfo) {
- throw new Error(`Nothing else parsed so far`);
- }
- texture._lodGenerationScale = specularInfo.lodGenerationScale;
- const imageData = EnvironmentTextureTools.CreateImageDataArrayBufferViews(data, info);
- texture.format = Engine.TEXTUREFORMAT_RGBA;
- texture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
- texture.generateMipMaps = true;
- texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture);
- texture._isRGBD = true;
- texture.invertY = true;
- this._native.loadCubeTexture(texture._webGLTexture!, imageData, true);
- texture.isReady = true;
- if (onLoad) {
- onLoad();
- }
- };
- if (files && files.length === 6) {
- throw new Error(`Multi-file loading not yet supported.`);
- }
- else {
- let onInternalError = (request?: WebRequest, exception?: any) => {
- if (onError && request) {
- onError(request.status + " " + request.statusText, exception);
- }
- };
- this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
- }
- }
- else {
- throw new Error("Cannot load cubemap: non-ENV format not supported.");
- }
- this._internalTexturesCache.push(texture);
- return texture;
- }
- // Returns a NativeFilter.XXXX value.
- private _getSamplingFilter(samplingMode: number): number {
- switch (samplingMode) {
- case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
- return NativeFilter.MINLINEAR_MAGLINEAR_MIPPOINT;
- case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
- return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
- case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
- return NativeFilter.MINPOINT_MAGPOINT_MIPLINEAR;
- case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
- return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT;
- case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
- return NativeFilter.MINLINEAR_MAGPOINT_MIPPOINT;
- case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
- return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR;
- case Engine.TEXTURE_NEAREST_LINEAR:
- return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR;
- case Engine.TEXTURE_NEAREST_NEAREST:
- return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT;
- case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
- return NativeFilter.MINPOINT_MAGLINEAR_MIPPOINT;
- case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
- return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR;
- case Engine.TEXTURE_LINEAR_LINEAR:
- return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
- case Engine.TEXTURE_LINEAR_NEAREST:
- return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR;
- default:
- throw new Error("Unexpected sampling mode: " + samplingMode + ".");
- }
- }
- private static _GetNativeTextureFormat(format: number, type: number): number {
- if (format == Engine.TEXTUREFORMAT_RGBA && type == Engine.TEXTURETYPE_UNSIGNED_INT) {
- return NativeTextureFormat.RGBA8;
- }
- else if (format == Engine.TEXTUREFORMAT_RGBA && type == Engine.TEXTURETYPE_FLOAT) {
- return NativeTextureFormat.RGBA32F;
- }
- else {
- throw new Error("Unexpected texture format or type: format " + format + ", type " + type + ".");
- }
- }
- public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
- let fullOptions = new RenderTargetCreationOptions();
- if (options !== undefined && typeof options === "object") {
- fullOptions.generateMipMaps = options.generateMipMaps;
- fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
- fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
- fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
- fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
- fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
- } else {
- fullOptions.generateMipMaps = <boolean>options;
- fullOptions.generateDepthBuffer = true;
- fullOptions.generateStencilBuffer = false;
- fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
- fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
- fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
- }
- if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
- // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
- fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
- }
- else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
- // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
- fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
- }
- var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
- var width = (<{ width: number, height: number }>size).width || <number>size;
- var height = (<{ width: number, height: number }>size).height || <number>size;
- if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
- fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
- Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
- }
- var framebuffer = this._native.createFrameBuffer(
- texture._webGLTexture!,
- width,
- height,
- NativeEngine._GetNativeTextureFormat(fullOptions.format, fullOptions.type),
- fullOptions.samplingMode!,
- fullOptions.generateStencilBuffer ? true : false,
- fullOptions.generateDepthBuffer,
- fullOptions.generateMipMaps ? true : false);
- texture._framebuffer = framebuffer;
- texture.baseWidth = width;
- texture.baseHeight = height;
- texture.width = width;
- texture.height = height;
- texture.isReady = true;
- texture.samples = 1;
- texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
- texture.samplingMode = fullOptions.samplingMode;
- texture.type = fullOptions.type;
- texture.format = fullOptions.format;
- texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
- texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
- this._internalTexturesCache.push(texture);
- return texture;
- }
- public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
- if (texture._webGLTexture) {
- var filter = this._getSamplingFilter(samplingMode);
- this._native.setTextureSampling(texture._webGLTexture, filter);
- }
- texture.samplingMode = samplingMode;
- }
- public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
- if (faceIndex) {
- throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
- }
- if (requiredWidth || requiredHeight) {
- throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
- }
- if (forceFullscreenViewport) {
- throw new Error("forceFullscreenViewport for frame buffers not yet supported in NativeEngine.");
- }
- this._native.bindFrameBuffer(texture._framebuffer!);
- }
- public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
- if (disableGenerateMipMaps) {
- Logger.Warn("Disabling mipmap generation not yet supported in NativeEngine. Ignoring.");
- }
- if (onBeforeUnbind) {
- onBeforeUnbind();
- }
- this._native.unbindFrameBuffer(texture._framebuffer!);
- }
- public createDynamicVertexBuffer(data: DataArray): DataBuffer {
- throw new Error("createDynamicVertexBuffer not yet implemented.");
- }
- public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
- throw new Error("updateDynamicIndexBuffer not yet implemented.");
- }
- /**
- * Updates a dynamic vertex buffer.
- * @param vertexBuffer the vertex buffer to update
- * @param data the data used to update the vertex buffer
- * @param byteOffset the byte offset of the data (optional)
- * @param byteLength the byte length of the data (optional)
- */
- public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
- throw new Error("updateDynamicVertexBuffer not yet implemented.");
- }
- // TODO: Refactor to share more logic with base Engine implementation.
- protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
- let uniform = this._boundUniforms[channel];
- if (!uniform) {
- return false;
- }
- // Not ready?
- if (!texture) {
- if (this._boundTexturesCache[channel] != null) {
- this._activeChannel = channel;
- this._native.setTexture(uniform, null);
- }
- return false;
- }
- // Video
- if ((<VideoTexture>texture).video) {
- this._activeChannel = channel;
- (<VideoTexture>texture).update();
- } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
- texture.delayLoad();
- return false;
- }
- let internalTexture: InternalTexture;
- if (depthStencilTexture) {
- internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
- } else if (texture.isReady()) {
- internalTexture = <InternalTexture>texture.getInternalTexture();
- } else if (texture.isCube) {
- internalTexture = this.emptyCubeTexture;
- } else if (texture.is3D) {
- internalTexture = this.emptyTexture3D;
- } else {
- internalTexture = this.emptyTexture;
- }
- this._activeChannel = channel;
- if (!internalTexture ||
- !internalTexture._webGLTexture) {
- return false;
- }
- this._native.setTextureWrapMode(
- internalTexture._webGLTexture,
- this._getAddressMode(texture.wrapU),
- this._getAddressMode(texture.wrapV),
- this._getAddressMode(texture.wrapR));
- this._updateAnisotropicLevel(texture);
- this._native.setTexture(uniform, internalTexture._webGLTexture);
- return true;
- }
- // TODO: Share more of this logic with the base implementation.
- // TODO: Rename to match naming in base implementation once refactoring allows different parameters.
- private _updateAnisotropicLevel(texture: BaseTexture) {
- var internalTexture = texture.getInternalTexture();
- var value = texture.anisotropicFilteringLevel;
- if (!internalTexture || !internalTexture._webGLTexture) {
- return;
- }
- if (internalTexture._cachedAnisotropicFilteringLevel !== value) {
- this._native.setTextureAnisotropicLevel(internalTexture._webGLTexture, value);
- internalTexture._cachedAnisotropicFilteringLevel = value;
- }
- }
- // Returns a NativeAddressMode.XXX value.
- private _getAddressMode(wrapMode: number): number {
- switch (wrapMode) {
- case Engine.TEXTURE_WRAP_ADDRESSMODE:
- return NativeAddressMode.WRAP;
- case Engine.TEXTURE_CLAMP_ADDRESSMODE:
- return NativeAddressMode.CLAMP;
- case Engine.TEXTURE_MIRROR_ADDRESSMODE:
- return NativeAddressMode.MIRROR;
- default:
- throw new Error("Unexpected wrap mode: " + wrapMode + ".");
- }
- }
- /** @hidden */
- public _bindTexture(channel: number, texture: InternalTexture): void {
- throw new Error("_bindTexture not implemented.");
- }
- protected _deleteBuffer(buffer: NativeDataBuffer): void {
- if (buffer.nativeIndexBuffer) {
- this._native.deleteIndexBuffer(buffer.nativeIndexBuffer);
- delete buffer.nativeIndexBuffer;
- }
- if (buffer.nativeVertexBuffer) {
- this._native.deleteVertexBuffer(buffer.nativeVertexBuffer);
- delete buffer.nativeVertexBuffer;
- }
- }
- public releaseEffects() {
- // TODO
- }
- /** @hidden */
- public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
- throw new Error("_uploadCompressedDataToTextureDirectly not implemented.");
- }
- /** @hidden */
- public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
- throw new Error("_uploadDataToTextureDirectly not implemented.");
- }
- /** @hidden */
- public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
- throw new Error("_uploadArrayBufferViewToTexture not implemented.");
- }
- /** @hidden */
- public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
- throw new Error("_uploadArrayBufferViewToTexture not implemented.");
- }
- }
|