nativeEngine.ts 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. import { Nullable, IndicesArray, DataArray } from "../types";
  2. import { Engine, EngineCapabilities } from "../Engines/engine";
  3. import { VertexBuffer } from "../Meshes/buffer";
  4. import { InternalTexture } from "../Materials/Textures/internalTexture";
  5. import { IInternalTextureLoader } from "../Materials/Textures/internalTextureLoader";
  6. import { Texture } from "../Materials/Textures/texture";
  7. import { BaseTexture } from "../Materials/Textures/baseTexture";
  8. import { VideoTexture } from "../Materials/Textures/videoTexture";
  9. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  10. import { Effect } from "../Materials/effect";
  11. import { DataBuffer } from '../Meshes/dataBuffer';
  12. import { Tools } from "../Misc/tools";
  13. import { Observer } from "../Misc/observable";
  14. import { EnvironmentTextureTools, EnvironmentTextureSpecularInfoV1 } from "../Misc/environmentTextureTools";
  15. import { Color4, Matrix, Viewport, Color3 } from "../Maths/math";
  16. import { Scene } from "../scene";
  17. import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
  18. import { IPipelineContext } from './IPipelineContext';
  19. import { WebRequest } from '../Misc/webRequest';
  20. import { NativeShaderProcessor } from './Native/nativeShaderProcessor';
  21. import { Logger } from "../Misc/logger";
  22. interface INativeEngine {
  23. requestAnimationFrame(callback: () => void): void;
  24. createVertexArray(): any;
  25. deleteVertexArray(vertexArray: any): void;
  26. bindVertexArray(vertexArray: any): void;
  27. createIndexBuffer(data: ArrayBufferView): any;
  28. deleteIndexBuffer(buffer: any): void;
  29. recordIndexBuffer(vertexArray: any, buffer: any): void;
  30. createVertexBuffer(data: ArrayBufferView): any;
  31. deleteVertexBuffer(buffer: any): void;
  32. recordVertexBuffer(vertexArray: any, buffer: any, location: number, byteOffset: number, byteStride: number, numElements: number, type: number, normalized: boolean): void;
  33. createProgram(vertexShader: string, fragmentShader: string): any;
  34. getUniforms(shaderProgram: any, uniformsNames: string[]): WebGLUniformLocation[];
  35. getAttributes(shaderProgram: any, attributeNames: string[]): number[];
  36. setProgram(program: any): void;
  37. setState(culling: boolean, zOffset: number, reverseSide: boolean): void;
  38. setZOffset(zOffset: number): void;
  39. getZOffset(): number;
  40. setDepthTest(enable: boolean): void;
  41. getDepthWrite(): boolean;
  42. setDepthWrite(enable: boolean): void;
  43. setColorWrite(enable: boolean): void;
  44. setBlendMode(blendMode: number): void;
  45. setMatrix(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  46. setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void;
  47. setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void;
  48. setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void;
  49. setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void;
  50. setFloatArray(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  51. setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  52. setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  53. setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  54. setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void;
  55. setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  56. setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  57. setFloat(uniform: WebGLUniformLocation, value: number): void;
  58. setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void;
  59. setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void;
  60. setBool(uniform: WebGLUniformLocation, bool: number): void;
  61. setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void;
  62. createTexture(): WebGLTexture;
  63. loadTexture(texture: WebGLTexture, buffer: ArrayBuffer | ArrayBufferView | Blob, mipMap: boolean): void;
  64. loadCubeTexture(texture: WebGLTexture, data: Array<Array<ArrayBufferView>>, flipY : boolean): void;
  65. getTextureWidth(texture: WebGLTexture): number;
  66. getTextureHeight(texture: WebGLTexture): number;
  67. setTextureSampling(texture: WebGLTexture, filter: number): void; // filter is a NativeFilter.XXXX value.
  68. setTextureWrapMode(texture: WebGLTexture, addressModeU: number, addressModeV: number, addressModeW: number): void; // addressModes are NativeAddressMode.XXXX values.
  69. setTextureAnisotropicLevel(texture: WebGLTexture, value: number): void;
  70. setTexture(uniform: WebGLUniformLocation, texture: Nullable<WebGLTexture>): void;
  71. deleteTexture(texture: Nullable<WebGLTexture>): void;
  72. createFrameBuffer(texture: WebGLTexture, width: number, height: number, format: number, samplingMode: number, generateStencilBuffer: boolean, generateDepthBuffer: boolean, generateMipMaps: boolean): WebGLFramebuffer;
  73. bindFrameBuffer(frameBuffer: WebGLFramebuffer): void;
  74. unbindFrameBuffer(frameBuffer: WebGLFramebuffer): void;
  75. drawIndexed(fillMode: number, indexStart: number, indexCount: number): void;
  76. draw(fillMode: number, vertexStart: number, vertexCount: number): void;
  77. clear(r: number, g: number, b: number, a: number, backBuffer: boolean, depth: boolean, stencil: boolean): void;
  78. getRenderWidth(): number;
  79. getRenderHeight(): number;
  80. }
  81. class NativePipelineContext implements IPipelineContext {
  82. // TODO: async should be true?
  83. public isAsync = false;
  84. public isReady = false;
  85. // TODO: what should this do?
  86. public _handlesSpectorRebuildCallback(onCompiled: (compiledObject: any) => void): void {
  87. throw new Error("Not implemented");
  88. }
  89. public nativeProgram: any;
  90. }
  91. /**
  92. * Container for accessors for natively-stored mesh data buffers.
  93. */
  94. class NativeDataBuffer extends DataBuffer {
  95. /**
  96. * Accessor value used to identify/retrieve a natively-stored index buffer.
  97. */
  98. public nativeIndexBuffer?: any;
  99. /**
  100. * Accessor value used to identify/retrieve a natively-stored vertex buffer.
  101. */
  102. public nativeVertexBuffer?: any;
  103. }
  104. // TODO: change this to match bgfx.
  105. // Must match Filter enum in SpectreEngine.h.
  106. class NativeFilter {
  107. public static readonly POINT = 0;
  108. public static readonly MINPOINT_MAGPOINT_MIPPOINT = NativeFilter.POINT;
  109. public static readonly BILINEAR = 1;
  110. public static readonly MINLINEAR_MAGLINEAR_MIPPOINT = NativeFilter.BILINEAR;
  111. public static readonly TRILINEAR = 2;
  112. public static readonly MINLINEAR_MAGLINEAR_MIPLINEAR = NativeFilter.TRILINEAR;
  113. public static readonly ANISOTROPIC = 3;
  114. public static readonly POINT_COMPARE = 4;
  115. public static readonly TRILINEAR_COMPARE = 5;
  116. public static readonly MINBILINEAR_MAGPOINT = 6;
  117. public static readonly MINLINEAR_MAGPOINT_MIPLINEAR = NativeFilter.MINBILINEAR_MAGPOINT;
  118. public static readonly MINPOINT_MAGPOINT_MIPLINEAR = 7;
  119. public static readonly MINPOINT_MAGLINEAR_MIPPOINT = 8;
  120. public static readonly MINPOINT_MAGLINEAR_MIPLINEAR = 9;
  121. public static readonly MINLINEAR_MAGPOINT_MIPPOINT = 10;
  122. }
  123. // TODO: change this to match bgfx.
  124. // Must match AddressMode enum in SpectreEngine.h.
  125. class NativeAddressMode {
  126. public static readonly WRAP = 0;
  127. public static readonly MIRROR = 1;
  128. public static readonly CLAMP = 2;
  129. public static readonly BORDER = 3;
  130. public static readonly MIRROR_ONCE = 4;
  131. }
  132. class NativeTextureFormat {
  133. public static readonly RGBA8 = 0;
  134. public static readonly RGBA32F = 1;
  135. }
  136. /** @hidden */
  137. declare var nativeEngine: INativeEngine;
  138. /** @hidden */
  139. export class NativeEngine extends Engine {
  140. private readonly _native: INativeEngine = nativeEngine;
  141. public getHardwareScalingLevel(): number {
  142. return 1.0;
  143. }
  144. public constructor() {
  145. super(null);
  146. this._webGLVersion = 2;
  147. this.disableUniformBuffers = true;
  148. // TODO: Initialize this more correctly based on the hardware capabilities.
  149. // Init caps
  150. this._caps = new EngineCapabilities();
  151. this._caps.maxTexturesImageUnits = 16;
  152. this._caps.maxVertexTextureImageUnits = 16;
  153. this._caps.maxTextureSize = 512;
  154. this._caps.maxCubemapTextureSize = 512;
  155. this._caps.maxRenderTextureSize = 512;
  156. this._caps.maxVertexAttribs = 16;
  157. this._caps.maxVaryingVectors = 16;
  158. this._caps.maxFragmentUniformVectors = 16;
  159. this._caps.maxVertexUniformVectors = 16;
  160. // Extensions
  161. this._caps.standardDerivatives = true;
  162. this._caps.astc = null;
  163. this._caps.s3tc = null;
  164. this._caps.pvrtc = null;
  165. this._caps.etc1 = null;
  166. this._caps.etc2 = null;
  167. this._caps.maxAnisotropy = 16; // TODO: Retrieve this smartly. Currently set to D3D11 maximum allowable value.
  168. this._caps.uintIndices = false;
  169. this._caps.fragmentDepthSupported = false;
  170. this._caps.highPrecisionShaderSupported = true;
  171. this._caps.colorBufferFloat = false;
  172. this._caps.textureFloat = false;
  173. this._caps.textureFloatLinearFiltering = false;
  174. this._caps.textureFloatRender = false;
  175. this._caps.textureHalfFloat = false;
  176. this._caps.textureHalfFloatLinearFiltering = false;
  177. this._caps.textureHalfFloatRender = false;
  178. this._caps.textureLOD = true;
  179. this._caps.drawBuffersExtension = false;
  180. this._caps.depthTextureExtension = false;
  181. this._caps.vertexArrayObject = true;
  182. this._caps.instancedArrays = false;
  183. Tools.Log("Babylon Native (v" + Engine.Version + ") launched");
  184. // Wrappers
  185. if (typeof URL === "undefined") {
  186. (window.URL as any) = {
  187. createObjectURL: function() { },
  188. revokeObjectURL: function() { }
  189. };
  190. }
  191. if (typeof Blob === "undefined") {
  192. (window.Blob as any) = function() { };
  193. }
  194. // Shader processor
  195. this._shaderProcessor = new NativeShaderProcessor();
  196. }
  197. /**
  198. * Can be used to override the current requestAnimationFrame requester.
  199. * @hidden
  200. */
  201. protected _queueNewFrame(bindedRenderFunction: any, requester: any): number {
  202. this._native.requestAnimationFrame(bindedRenderFunction);
  203. return 0;
  204. }
  205. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  206. this._native.clear(color.r, color.g, color.b, color.a, backBuffer, depth, stencil);
  207. }
  208. public createIndexBuffer(indices: IndicesArray): NativeDataBuffer {
  209. const data = this._normalizeIndexData(indices);
  210. const buffer = new NativeDataBuffer();
  211. buffer.references = 1;
  212. buffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
  213. buffer.nativeIndexBuffer = this._native.createIndexBuffer(data);
  214. return buffer;
  215. }
  216. public createVertexBuffer(data: DataArray): NativeDataBuffer {
  217. const buffer = new NativeDataBuffer();
  218. buffer.references = 1;
  219. buffer.nativeVertexBuffer = this._native.createVertexBuffer(ArrayBuffer.isView(data) ? data : new Float32Array(data));
  220. return buffer;
  221. }
  222. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<NativeDataBuffer>, effect: Effect): WebGLVertexArrayObject {
  223. const vertexArray = this._native.createVertexArray();
  224. if (indexBuffer) {
  225. this._native.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);
  226. }
  227. const attributes = effect.getAttributesNames();
  228. for (let index = 0; index < attributes.length; index++) {
  229. const location = effect.getAttributeLocation(index);
  230. if (location >= 0) {
  231. const kind = attributes[index];
  232. const vertexBuffer = vertexBuffers[kind];
  233. if (vertexBuffer) {
  234. const buffer = vertexBuffer.getBuffer() as Nullable<NativeDataBuffer>;
  235. if (buffer) {
  236. this._native.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized);
  237. }
  238. }
  239. }
  240. }
  241. return vertexArray;
  242. }
  243. public bindVertexArrayObject(vertexArray: WebGLVertexArrayObject): void {
  244. this._native.bindVertexArray(vertexArray);
  245. }
  246. public releaseVertexArrayObject(vertexArray: WebGLVertexArrayObject) {
  247. this._native.deleteVertexArray(vertexArray);
  248. }
  249. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  250. const nativePipelineContext = pipelineContext as NativePipelineContext;
  251. return this._native.getAttributes(nativePipelineContext.nativeProgram, attributesNames);
  252. }
  253. /**
  254. * Draw a list of indexed primitives
  255. * @param fillMode defines the primitive to use
  256. * @param indexStart defines the starting index
  257. * @param indexCount defines the number of index to draw
  258. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  259. */
  260. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  261. // Apply states
  262. this._drawCalls.addCount(1, false);
  263. // TODO: Make this implementation more robust like core Engine version.
  264. // Render
  265. //var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  266. //var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  267. // if (instancesCount) {
  268. // this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  269. // } else {
  270. this._native.drawIndexed(fillMode, indexStart, indexCount);
  271. // }
  272. }
  273. /**
  274. * Draw a list of unindexed primitives
  275. * @param fillMode defines the primitive to use
  276. * @param verticesStart defines the index of first vertex to draw
  277. * @param verticesCount defines the count of vertices to draw
  278. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  279. */
  280. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  281. // Apply states
  282. this._drawCalls.addCount(1, false);
  283. // TODO: Make this implementation more robust like core Engine version.
  284. // if (instancesCount) {
  285. // this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  286. // } else {
  287. this._native.draw(fillMode, verticesStart, verticesCount);
  288. // }
  289. }
  290. public createPipelineContext(): IPipelineContext {
  291. return new NativePipelineContext();
  292. }
  293. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean, rebuildRebind: any, defines: Nullable<string>, transformFeedbackVaryings: Nullable<string[]>) {
  294. const nativePipelineContext = pipelineContext as NativePipelineContext;
  295. if (createAsRaw) {
  296. nativePipelineContext.nativeProgram = this.createRawShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
  297. }
  298. else {
  299. nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
  300. }
  301. }
  302. /** @hidden */
  303. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  304. // TODO: support async shader compilcation
  305. return true;
  306. }
  307. /** @hidden */
  308. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  309. // TODO: support async shader compilcation
  310. action();
  311. }
  312. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): any {
  313. throw new Error("Not Supported");
  314. }
  315. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): any {
  316. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  317. const program = this._native.createProgram(
  318. Engine._concatenateShader(vertexCode, defines),
  319. Engine._concatenateShader(fragmentCode, defines)
  320. );
  321. this.onAfterShaderCompilationObservable.notifyObservers(this);
  322. return program;
  323. }
  324. protected _setProgram(program: WebGLProgram): void {
  325. if (this._currentProgram !== program) {
  326. this._native.setProgram(program);
  327. this._currentProgram = program;
  328. }
  329. }
  330. public _releaseEffect(effect: Effect): void {
  331. // TODO
  332. }
  333. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  334. // TODO
  335. }
  336. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): WebGLUniformLocation[] {
  337. const nativePipelineContext = pipelineContext as NativePipelineContext;
  338. return this._native.getUniforms(nativePipelineContext.nativeProgram, uniformsNames);
  339. }
  340. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  341. // TODO
  342. throw new Error("Not Implemented");
  343. }
  344. public bindSamplers(effect: Effect): void {
  345. const nativePipelineContext = effect.getPipelineContext() as NativePipelineContext;
  346. this._setProgram(nativePipelineContext.nativeProgram);
  347. // TODO: share this with engine?
  348. var samplers = effect.getSamplers();
  349. for (var index = 0; index < samplers.length; index++) {
  350. var uniform = effect.getUniform(samplers[index]);
  351. if (uniform) {
  352. this._boundUniforms[index] = uniform;
  353. }
  354. }
  355. this._currentEffect = null;
  356. }
  357. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  358. if (!uniform) {
  359. return;
  360. }
  361. this._native.setMatrix(uniform, matrix.toArray() as Float32Array);
  362. }
  363. public getRenderWidth(useScreen = false): number {
  364. if (!useScreen && this._currentRenderTarget) {
  365. return this._currentRenderTarget.width;
  366. }
  367. return this._native.getRenderWidth();
  368. }
  369. public getRenderHeight(useScreen = false): number {
  370. if (!useScreen && this._currentRenderTarget) {
  371. return this._currentRenderTarget.height;
  372. }
  373. return this._native.getRenderHeight();
  374. }
  375. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  376. // TODO: Implement.
  377. this._cachedViewport = viewport;
  378. }
  379. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  380. this._native.setState(culling, zOffset, reverseSide);
  381. }
  382. /**
  383. * Set the z offset to apply to current rendering
  384. * @param value defines the offset to apply
  385. */
  386. public setZOffset(value: number): void {
  387. this._native.setZOffset(value);
  388. }
  389. /**
  390. * Gets the current value of the zOffset
  391. * @returns the current zOffset state
  392. */
  393. public getZOffset(): number {
  394. return this._native.getZOffset();
  395. }
  396. /**
  397. * Enable or disable depth buffering
  398. * @param enable defines the state to set
  399. */
  400. public setDepthBuffer(enable: boolean): void {
  401. this._native.setDepthTest(enable);
  402. }
  403. /**
  404. * Gets a boolean indicating if depth writing is enabled
  405. * @returns the current depth writing state
  406. */
  407. public getDepthWrite(): boolean {
  408. return this._native.getDepthWrite();
  409. }
  410. /**
  411. * Enable or disable depth writing
  412. * @param enable defines the state to set
  413. */
  414. public setDepthWrite(enable: boolean): void {
  415. this._native.setDepthWrite(enable);
  416. }
  417. /**
  418. * Enable or disable color writing
  419. * @param enable defines the state to set
  420. */
  421. public setColorWrite(enable: boolean): void {
  422. this._native.setColorWrite(enable);
  423. this._colorWrite = enable;
  424. }
  425. /**
  426. * Gets a boolean indicating if color writing is enabled
  427. * @returns the current color writing state
  428. */
  429. public getColorWrite(): boolean {
  430. return this._colorWrite;
  431. }
  432. /**
  433. * Sets alpha constants used by some alpha blending modes
  434. * @param r defines the red component
  435. * @param g defines the green component
  436. * @param b defines the blue component
  437. * @param a defines the alpha component
  438. */
  439. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  440. throw new Error("Setting alpha blend constant color not yet implemented.");
  441. }
  442. /**
  443. * Sets the current alpha mode
  444. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  445. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  446. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  447. */
  448. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  449. if (this._alphaMode === mode) {
  450. return;
  451. }
  452. this._native.setBlendMode(mode);
  453. if (!noDepthWriteChange) {
  454. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  455. }
  456. this._alphaMode = mode;
  457. }
  458. /**
  459. * Gets the current alpha mode
  460. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  461. * @returns the current alpha mode
  462. */
  463. public getAlphaMode(): number {
  464. return this._alphaMode;
  465. }
  466. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  467. if (!uniform) {
  468. return;
  469. }
  470. this._native.setIntArray(uniform, array);
  471. }
  472. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  473. if (!uniform) {
  474. return;
  475. }
  476. this._native.setIntArray2(uniform, array);
  477. }
  478. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  479. if (!uniform) {
  480. return;
  481. }
  482. this._native.setIntArray3(uniform, array);
  483. }
  484. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  485. if (!uniform) {
  486. return;
  487. }
  488. this._native.setIntArray4(uniform, array);
  489. }
  490. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  491. if (!uniform) {
  492. return;
  493. }
  494. this._native.setFloatArray(uniform, array);
  495. }
  496. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  497. if (!uniform) {
  498. return;
  499. }
  500. this._native.setFloatArray2(uniform, array);
  501. }
  502. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  503. if (!uniform) {
  504. return;
  505. }
  506. this._native.setFloatArray3(uniform, array);
  507. }
  508. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  509. if (!uniform) {
  510. return;
  511. }
  512. this._native.setFloatArray4(uniform, array);
  513. }
  514. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  515. if (!uniform) {
  516. return;
  517. }
  518. this._native.setFloatArray(uniform, array);
  519. }
  520. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  521. if (!uniform) {
  522. return;
  523. }
  524. this._native.setFloatArray2(uniform, array);
  525. }
  526. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  527. if (!uniform) {
  528. return;
  529. }
  530. this._native.setFloatArray3(uniform, array);
  531. }
  532. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  533. if (!uniform) {
  534. return;
  535. }
  536. this._native.setFloatArray4(uniform, array);
  537. }
  538. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  539. if (!uniform) {
  540. return;
  541. }
  542. this._native.setMatrices(uniform, matrices);
  543. }
  544. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  545. if (!uniform) {
  546. return;
  547. }
  548. this._native.setMatrix3x3(uniform, matrix);
  549. }
  550. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  551. if (!uniform) {
  552. return;
  553. }
  554. this._native.setMatrix2x2(uniform, matrix);
  555. }
  556. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  557. if (!uniform) {
  558. return;
  559. }
  560. this._native.setFloat(uniform, value);
  561. }
  562. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  563. if (!uniform) {
  564. return;
  565. }
  566. this._native.setFloat2(uniform, x, y);
  567. }
  568. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  569. if (!uniform) {
  570. return;
  571. }
  572. this._native.setFloat3(uniform, x, y, z);
  573. }
  574. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  575. if (!uniform) {
  576. return;
  577. }
  578. this._native.setBool(uniform, bool);
  579. }
  580. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  581. if (!uniform) {
  582. return;
  583. }
  584. this._native.setFloat4(uniform, x, y, z, w);
  585. }
  586. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  587. if (!uniform) {
  588. return;
  589. }
  590. this._native.setFloat3(uniform, color3.r, color3.g, color3.b);
  591. }
  592. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  593. if (!uniform) {
  594. return;
  595. }
  596. this._native.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);
  597. }
  598. public wipeCaches(bruteForce?: boolean): void {
  599. if (this.preventCacheWipeBetweenFrames) {
  600. return;
  601. }
  602. this.resetTextureCache();
  603. this._currentEffect = null;
  604. if (bruteForce) {
  605. this._currentProgram = null;
  606. this._stencilState.reset();
  607. this._depthCullingState.reset();
  608. this._alphaState.reset();
  609. }
  610. this._cachedVertexBuffers = null;
  611. this._cachedIndexBuffer = null;
  612. this._cachedEffectForVertexBuffers = null;
  613. }
  614. public _createTexture(): WebGLTexture {
  615. return this._native.createTexture();
  616. }
  617. protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
  618. this._native.deleteTexture(texture);
  619. }
  620. // TODO: Refactor to share more logic with babylon.engine.ts version.
  621. /**
  622. * Usually called from BABYLON.Texture.ts.
  623. * Passed information to create a WebGLTexture
  624. * @param urlArg defines a value which contains one of the following:
  625. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  626. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  627. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  628. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  629. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  630. * @param scene needed for loading to the correct scene
  631. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  632. * @param onLoad optional callback to be called upon successful completion
  633. * @param onError optional callback to be called upon failure
  634. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), or a Blob
  635. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  636. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  637. * @param forcedExtension defines the extension to use to pick the right loader
  638. * @returns a InternalTexture for assignment back into BABYLON.Texture
  639. */
  640. public createTexture(
  641. urlArg: Nullable<string>,
  642. noMipmap: boolean,
  643. invertY: boolean,
  644. scene: Nullable<Scene>,
  645. samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  646. onLoad: Nullable<() => void> = null,
  647. onError: Nullable<(message: string, exception: any) => void> = null,
  648. buffer: Nullable<string | ArrayBuffer | Blob> = null,
  649. fallback: Nullable<InternalTexture> = null,
  650. format: Nullable<number> = null,
  651. forcedExtension: Nullable<string> = null): InternalTexture {
  652. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  653. var fromData = url.substr(0, 5) === "data:";
  654. var fromBlob = url.substr(0, 5) === "blob:";
  655. var isBase64 = fromData && url.indexOf("base64") !== -1;
  656. let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  657. // establish the file extension, if possible
  658. var lastDot = url.lastIndexOf('.');
  659. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  660. // TODO: Add support for compressed texture formats.
  661. var textureFormatInUse: Nullable<string> = null;
  662. let loader: Nullable<IInternalTextureLoader> = null;
  663. for (let availableLoader of Engine._TextureLoaders) {
  664. if (availableLoader.canLoad(extension, textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  665. loader = availableLoader;
  666. break;
  667. }
  668. }
  669. if (loader) {
  670. url = loader.transformUrl(url, textureFormatInUse);
  671. }
  672. if (scene) {
  673. scene._addPendingData(texture);
  674. }
  675. texture.url = url;
  676. texture.generateMipMaps = !noMipmap;
  677. texture.samplingMode = samplingMode;
  678. texture.invertY = invertY;
  679. if (!this.doNotHandleContextLost) {
  680. // Keep a link to the buffer only if we plan to handle context lost
  681. texture._buffer = buffer;
  682. }
  683. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  684. if (onLoad && !fallback) {
  685. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  686. }
  687. if (!fallback) { this._internalTexturesCache.push(texture); }
  688. let onInternalError = (message?: string, exception?: any) => {
  689. if (scene) {
  690. scene._removePendingData(texture);
  691. }
  692. let customFallback = false;
  693. if (loader) {
  694. const fallbackUrl = loader.getFallbackTextureUrl(url, textureFormatInUse);
  695. if (fallbackUrl) {
  696. // Add Back
  697. customFallback = true;
  698. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  699. }
  700. }
  701. if (!customFallback) {
  702. if (onLoadObserver) {
  703. texture.onLoadedObservable.remove(onLoadObserver);
  704. }
  705. if (Tools.UseFallbackTexture) {
  706. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  707. }
  708. }
  709. if (onError) {
  710. onError(message || "Unknown error", exception);
  711. }
  712. };
  713. // processing for non-image formats
  714. if (loader) {
  715. throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
  716. // var callback = (data: string | ArrayBuffer) => {
  717. // loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void) => {
  718. // this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, () => {
  719. // done();
  720. // return false;
  721. // },
  722. // samplingMode);
  723. // });
  724. // }
  725. // if (!buffer) {
  726. // this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  727. // onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  728. // });
  729. // } else {
  730. // callback(buffer as ArrayBuffer);
  731. // }
  732. } else {
  733. var onload = (data: string | ArrayBuffer | Blob, responseURL?: string) => {
  734. if (typeof (data) === "string") {
  735. throw new Error("Loading textures from string data not yet implemented.");
  736. }
  737. if (fromBlob && !this.doNotHandleContextLost) {
  738. // We need to store the image if we need to rebuild the texture
  739. // in case of a webgl context lost
  740. texture._buffer = data;
  741. }
  742. let webGLTexture = texture._webGLTexture;
  743. if (!webGLTexture) {
  744. // this.resetTextureCache();
  745. if (scene) {
  746. scene._removePendingData(texture);
  747. }
  748. return;
  749. }
  750. this._native.loadTexture(webGLTexture, data, !noMipmap);
  751. if (invertY) {
  752. throw new Error("Support for textures with inverted Y coordinates not yet implemented.");
  753. }
  754. //this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  755. texture.baseWidth = this._native.getTextureWidth(webGLTexture);
  756. texture.baseHeight = this._native.getTextureHeight(webGLTexture);
  757. texture.width = texture.baseWidth;
  758. texture.height = texture.baseHeight;
  759. texture.isReady = true;
  760. var filter = this._getSamplingFilter(samplingMode);
  761. this._native.setTextureSampling(webGLTexture, filter);
  762. // this.resetTextureCache();
  763. if (scene) {
  764. scene._removePendingData(texture);
  765. }
  766. texture.onLoadedObservable.notifyObservers(texture);
  767. texture.onLoadedObservable.clear();
  768. };
  769. if (buffer instanceof ArrayBuffer) {
  770. onload(buffer);
  771. } else if (ArrayBuffer.isView(buffer)) {
  772. onload(buffer.buffer);
  773. } else if (buffer instanceof Blob) {
  774. throw new Error("Loading texture from Blob not yet implemented.");
  775. } else if (!fromData) {
  776. let onLoadFileError = (request?: WebRequest, exception?: any) => {
  777. onInternalError("Failed to retrieve " + url + ".", exception);
  778. };
  779. Tools.LoadFile(url, onload, undefined, undefined, /*useArrayBuffer*/true, onLoadFileError);
  780. } else {
  781. onload(Tools.DecodeBase64(buffer as string));
  782. }
  783. }
  784. return texture;
  785. }
  786. /**
  787. * Creates a cube texture
  788. * @param rootUrl defines the url where the files to load is located
  789. * @param scene defines the current scene
  790. * @param files defines the list of files to load (1 per face)
  791. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  792. * @param onLoad defines an optional callback raised when the texture is loaded
  793. * @param onError defines an optional callback raised if there is an issue to load the texture
  794. * @param format defines the format of the data
  795. * @param forcedExtension defines the extension to use to pick the right loader
  796. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  797. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  798. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  799. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  800. * @returns the cube texture as an InternalTexture
  801. */
  802. public createCubeTexture(
  803. rootUrl: string,
  804. scene: Nullable<Scene>,
  805. files: Nullable<string[]>,
  806. noMipmap?: boolean,
  807. onLoad: Nullable<(data?: any) => void> = null,
  808. onError: Nullable<(message?: string, exception?: any) => void> = null,
  809. format?: number,
  810. forcedExtension: any = null,
  811. createPolynomials = false,
  812. lodScale: number = 0,
  813. lodOffset: number = 0,
  814. fallback: Nullable<InternalTexture> = null): InternalTexture
  815. {
  816. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  817. texture.isCube = true;
  818. texture.url = rootUrl;
  819. texture.generateMipMaps = !noMipmap;
  820. texture._lodGenerationScale = lodScale;
  821. texture._lodGenerationOffset = lodOffset;
  822. if (!this._doNotHandleContextLost) {
  823. texture._extension = forcedExtension;
  824. texture._files = files;
  825. }
  826. var lastDot = rootUrl.lastIndexOf('.');
  827. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  828. if (extension === ".env") {
  829. const onloaddata = (data: any) => {
  830. data = data as ArrayBuffer;
  831. var info = EnvironmentTextureTools.GetEnvInfo(data)!;
  832. texture.width = info.width;
  833. texture.height = info.width;
  834. EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  835. if (info.version !== 1) {
  836. throw new Error(`Unsupported babylon environment map version "${info.version}"`);
  837. }
  838. let specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
  839. if (!specularInfo) {
  840. throw new Error(`Nothing else parsed so far`);
  841. }
  842. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  843. const imageData = EnvironmentTextureTools.CreateImageDataArrayBufferViews(data, info);
  844. texture.format = Engine.TEXTUREFORMAT_RGBA;
  845. texture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  846. texture.generateMipMaps = true;
  847. texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture);
  848. texture._isRGBD = true;
  849. texture.invertY = true;
  850. this._native.loadCubeTexture(texture._webGLTexture!, imageData, true);
  851. texture.isReady = true;
  852. if (onLoad) {
  853. onLoad();
  854. }
  855. };
  856. if (files && files.length === 6) {
  857. throw new Error(`Multi-file loading not yet supported.`);
  858. }
  859. else {
  860. let onInternalError = (request?: WebRequest, exception?: any) => {
  861. if (onError && request) {
  862. onError(request.status + " " + request.statusText, exception);
  863. }
  864. };
  865. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  866. }
  867. }
  868. else {
  869. throw new Error("Cannot load cubemap: non-ENV format not supported.");
  870. }
  871. this._internalTexturesCache.push(texture);
  872. return texture;
  873. }
  874. // Returns a NativeFilter.XXXX value.
  875. private _getSamplingFilter(samplingMode: number): number {
  876. switch (samplingMode) {
  877. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  878. return NativeFilter.MINLINEAR_MAGLINEAR_MIPPOINT;
  879. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  880. return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
  881. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  882. return NativeFilter.MINPOINT_MAGPOINT_MIPLINEAR;
  883. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  884. return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT;
  885. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  886. return NativeFilter.MINLINEAR_MAGPOINT_MIPPOINT;
  887. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  888. return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR;
  889. case Engine.TEXTURE_NEAREST_LINEAR:
  890. return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR;
  891. case Engine.TEXTURE_NEAREST_NEAREST:
  892. return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT;
  893. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  894. return NativeFilter.MINPOINT_MAGLINEAR_MIPPOINT;
  895. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  896. return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR;
  897. case Engine.TEXTURE_LINEAR_LINEAR:
  898. return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
  899. case Engine.TEXTURE_LINEAR_NEAREST:
  900. return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR;
  901. default:
  902. throw new Error("Unexpected sampling mode: " + samplingMode + ".");
  903. }
  904. }
  905. private static _GetNativeTextureFormat(format: number, type: number): number {
  906. if (format == Engine.TEXTUREFORMAT_RGBA && type == Engine.TEXTURETYPE_UNSIGNED_INT) {
  907. return NativeTextureFormat.RGBA8;
  908. }
  909. else if (format == Engine.TEXTUREFORMAT_RGBA && type == Engine.TEXTURETYPE_FLOAT) {
  910. return NativeTextureFormat.RGBA32F;
  911. }
  912. else {
  913. throw new Error("Unexpected texture format or type: format " + format + ", type " + type + ".");
  914. }
  915. }
  916. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  917. let fullOptions = new RenderTargetCreationOptions();
  918. if (options !== undefined && typeof options === "object") {
  919. fullOptions.generateMipMaps = options.generateMipMaps;
  920. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  921. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  922. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  923. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  924. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  925. } else {
  926. fullOptions.generateMipMaps = <boolean>options;
  927. fullOptions.generateDepthBuffer = true;
  928. fullOptions.generateStencilBuffer = false;
  929. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  930. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  931. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  932. }
  933. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  934. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  935. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  936. }
  937. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  938. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  939. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  940. }
  941. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  942. var width = (<{ width: number, height: number }>size).width || <number>size;
  943. var height = (<{ width: number, height: number }>size).height || <number>size;
  944. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  945. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  946. Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  947. }
  948. var framebuffer = this._native.createFrameBuffer(
  949. texture._webGLTexture!,
  950. width,
  951. height,
  952. NativeEngine._GetNativeTextureFormat(fullOptions.format, fullOptions.type),
  953. fullOptions.samplingMode!,
  954. fullOptions.generateStencilBuffer ? true : false,
  955. fullOptions.generateDepthBuffer,
  956. fullOptions.generateMipMaps ? true : false);
  957. texture._framebuffer = framebuffer;
  958. texture.baseWidth = width;
  959. texture.baseHeight = height;
  960. texture.width = width;
  961. texture.height = height;
  962. texture.isReady = true;
  963. texture.samples = 1;
  964. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  965. texture.samplingMode = fullOptions.samplingMode;
  966. texture.type = fullOptions.type;
  967. texture.format = fullOptions.format;
  968. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  969. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  970. this._internalTexturesCache.push(texture);
  971. return texture;
  972. }
  973. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  974. if (texture._webGLTexture) {
  975. var filter = this._getSamplingFilter(samplingMode);
  976. this._native.setTextureSampling(texture._webGLTexture, filter);
  977. }
  978. texture.samplingMode = samplingMode;
  979. }
  980. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  981. if (faceIndex) {
  982. throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
  983. }
  984. if (requiredWidth || requiredHeight) {
  985. throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
  986. }
  987. if (forceFullscreenViewport) {
  988. throw new Error("forceFullscreenViewport for frame buffers not yet supported in NativeEngine.");
  989. }
  990. this._native.bindFrameBuffer(texture._framebuffer!);
  991. }
  992. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  993. if (disableGenerateMipMaps) {
  994. Logger.Warn("Disabling mipmap generation not yet supported in NativeEngine. Ignoring.");
  995. }
  996. if (onBeforeUnbind) {
  997. onBeforeUnbind();
  998. }
  999. this._native.unbindFrameBuffer(texture._framebuffer!);
  1000. }
  1001. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  1002. throw new Error("createDynamicVertexBuffer not yet implemented.");
  1003. }
  1004. public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
  1005. throw new Error("updateDynamicIndexBuffer not yet implemented.");
  1006. }
  1007. /**
  1008. * Updates a dynamic vertex buffer.
  1009. * @param vertexBuffer the vertex buffer to update
  1010. * @param data the data used to update the vertex buffer
  1011. * @param byteOffset the byte offset of the data (optional)
  1012. * @param byteLength the byte length of the data (optional)
  1013. */
  1014. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  1015. throw new Error("updateDynamicVertexBuffer not yet implemented.");
  1016. }
  1017. // TODO: Refactor to share more logic with base Engine implementation.
  1018. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  1019. let uniform = this._boundUniforms[channel];
  1020. if (!uniform) {
  1021. return false;
  1022. }
  1023. // Not ready?
  1024. if (!texture) {
  1025. if (this._boundTexturesCache[channel] != null) {
  1026. this._activeChannel = channel;
  1027. this._native.setTexture(uniform, null);
  1028. }
  1029. return false;
  1030. }
  1031. // Video
  1032. if ((<VideoTexture>texture).video) {
  1033. this._activeChannel = channel;
  1034. (<VideoTexture>texture).update();
  1035. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1036. texture.delayLoad();
  1037. return false;
  1038. }
  1039. let internalTexture: InternalTexture;
  1040. if (depthStencilTexture) {
  1041. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  1042. } else if (texture.isReady()) {
  1043. internalTexture = <InternalTexture>texture.getInternalTexture();
  1044. } else if (texture.isCube) {
  1045. internalTexture = this.emptyCubeTexture;
  1046. } else if (texture.is3D) {
  1047. internalTexture = this.emptyTexture3D;
  1048. } else {
  1049. internalTexture = this.emptyTexture;
  1050. }
  1051. this._activeChannel = channel;
  1052. if (!internalTexture ||
  1053. !internalTexture._webGLTexture) {
  1054. return false;
  1055. }
  1056. this._native.setTextureWrapMode(
  1057. internalTexture._webGLTexture,
  1058. this._getAddressMode(texture.wrapU),
  1059. this._getAddressMode(texture.wrapV),
  1060. this._getAddressMode(texture.wrapR));
  1061. this._updateAnisotropicLevel(texture);
  1062. this._native.setTexture(uniform, internalTexture._webGLTexture);
  1063. return true;
  1064. }
  1065. // TODO: Share more of this logic with the base implementation.
  1066. // TODO: Rename to match naming in base implementation once refactoring allows different parameters.
  1067. private _updateAnisotropicLevel(texture: BaseTexture) {
  1068. var internalTexture = texture.getInternalTexture();
  1069. var value = texture.anisotropicFilteringLevel;
  1070. if (!internalTexture || !internalTexture._webGLTexture) {
  1071. return;
  1072. }
  1073. if (internalTexture._cachedAnisotropicFilteringLevel !== value) {
  1074. this._native.setTextureAnisotropicLevel(internalTexture._webGLTexture, value);
  1075. internalTexture._cachedAnisotropicFilteringLevel = value;
  1076. }
  1077. }
  1078. // Returns a NativeAddressMode.XXX value.
  1079. private _getAddressMode(wrapMode: number): number {
  1080. switch (wrapMode) {
  1081. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  1082. return NativeAddressMode.WRAP;
  1083. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  1084. return NativeAddressMode.CLAMP;
  1085. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  1086. return NativeAddressMode.MIRROR;
  1087. default:
  1088. throw new Error("Unexpected wrap mode: " + wrapMode + ".");
  1089. }
  1090. }
  1091. /** @hidden */
  1092. public _bindTexture(channel: number, texture: InternalTexture): void {
  1093. throw new Error("_bindTexture not implemented.");
  1094. }
  1095. protected _deleteBuffer(buffer: NativeDataBuffer): void {
  1096. if (buffer.nativeIndexBuffer) {
  1097. this._native.deleteIndexBuffer(buffer.nativeIndexBuffer);
  1098. delete buffer.nativeIndexBuffer;
  1099. }
  1100. if (buffer.nativeVertexBuffer) {
  1101. this._native.deleteVertexBuffer(buffer.nativeVertexBuffer);
  1102. delete buffer.nativeVertexBuffer;
  1103. }
  1104. }
  1105. public releaseEffects() {
  1106. // TODO
  1107. }
  1108. /** @hidden */
  1109. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  1110. throw new Error("_uploadCompressedDataToTextureDirectly not implemented.");
  1111. }
  1112. /** @hidden */
  1113. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1114. throw new Error("_uploadDataToTextureDirectly not implemented.");
  1115. }
  1116. /** @hidden */
  1117. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1118. throw new Error("_uploadArrayBufferViewToTexture not implemented.");
  1119. }
  1120. /** @hidden */
  1121. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  1122. throw new Error("_uploadArrayBufferViewToTexture not implemented.");
  1123. }
  1124. }