nativeEngine.ts 55 KB

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