nativeEngine.ts 58 KB

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