nativeEngine.ts 54 KB

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