nativeEngine.ts 54 KB

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