babylon.engine.ts 147 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string, shaderVersion: string): WebGLShader => {
  3. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  5. gl.compileShader(shader);
  6. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7. throw new Error(gl.getShaderInfoLog(shader));
  8. }
  9. return shader;
  10. };
  11. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  12. var magFilter = gl.NEAREST;
  13. var minFilter = gl.NEAREST;
  14. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  15. magFilter = gl.LINEAR;
  16. if (generateMipMaps) {
  17. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  18. } else {
  19. minFilter = gl.LINEAR;
  20. }
  21. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  22. magFilter = gl.LINEAR;
  23. if (generateMipMaps) {
  24. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  25. } else {
  26. minFilter = gl.LINEAR;
  27. }
  28. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  29. magFilter = gl.NEAREST;
  30. if (generateMipMaps) {
  31. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  32. } else {
  33. minFilter = gl.NEAREST;
  34. }
  35. }
  36. return {
  37. min: minFilter,
  38. mag: magFilter
  39. }
  40. }
  41. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  42. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  43. var engine = scene.getEngine();
  44. if (!engine) {
  45. return;
  46. }
  47. var potWidth = Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  48. var potHeight = Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  49. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  50. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  51. texture._baseWidth = width;
  52. texture._baseHeight = height;
  53. texture._width = potWidth;
  54. texture._height = potHeight;
  55. texture.isReady = true;
  56. processFunction(potWidth, potHeight);
  57. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  58. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  59. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  60. if (!noMipmap && !isCompressed) {
  61. gl.generateMipmap(gl.TEXTURE_2D);
  62. }
  63. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  64. engine.resetTextureCache();
  65. scene._removePendingData(texture);
  66. texture.onLoadedCallbacks.forEach(callback => {
  67. callback();
  68. });
  69. texture.onLoadedCallbacks = [];
  70. };
  71. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  72. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
  73. var img: HTMLImageElement;
  74. var onload = () => {
  75. loadedImages[index] = img;
  76. loadedImages._internalCount++;
  77. scene._removePendingData(img);
  78. if (loadedImages._internalCount === 6) {
  79. onfinish(loadedImages);
  80. }
  81. };
  82. var onerror = () => {
  83. scene._removePendingData(img);
  84. if (onErrorCallBack) {
  85. onErrorCallBack();
  86. }
  87. };
  88. img = Tools.LoadImage(url, onload, onerror, scene.database);
  89. scene._addPendingData(img);
  90. }
  91. var cascadeLoad = (rootUrl: string, scene,
  92. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
  93. var loadedImages: any = [];
  94. loadedImages._internalCount = 0;
  95. for (var index = 0; index < 6; index++) {
  96. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  97. }
  98. };
  99. export class InstancingAttributeInfo {
  100. /**
  101. * Index/offset of the attribute in the vertex shader
  102. */
  103. index: number;
  104. /**
  105. * size of the attribute, 1, 2, 3 or 4
  106. */
  107. attributeSize: number;
  108. /**
  109. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  110. * default is FLOAT
  111. */
  112. attribyteType: number;
  113. /**
  114. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  115. */
  116. normalized: boolean;
  117. /**
  118. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  119. */
  120. offset: number;
  121. /**
  122. * Name of the GLSL attribute, for debugging purpose only
  123. */
  124. attributeName: string;
  125. }
  126. export class EngineCapabilities {
  127. public maxTexturesImageUnits: number;
  128. public maxVertexTextureImageUnits: number;
  129. public maxTextureSize: number;
  130. public maxCubemapTextureSize: number;
  131. public maxRenderTextureSize: number;
  132. public maxVertexAttribs: number;
  133. public maxVaryingVectors: number;
  134. public maxVertexUniformVectors: number;
  135. public maxFragmentUniformVectors: number;
  136. public standardDerivatives: boolean;
  137. public s3tc: WEBGL_compressed_texture_s3tc;
  138. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  139. public etc1: any; //WEBGL_compressed_texture_etc1;
  140. public etc2: any; //WEBGL_compressed_texture_etc;
  141. public astc: any; //WEBGL_compressed_texture_astc;
  142. public textureFloat: boolean;
  143. public vertexArrayObject: boolean;
  144. public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
  145. public maxAnisotropy: number;
  146. public instancedArrays: boolean;
  147. public uintIndices: boolean;
  148. public highPrecisionShaderSupported: boolean;
  149. public fragmentDepthSupported: boolean;
  150. public textureFloatLinearFiltering: boolean;
  151. public textureFloatRender: boolean;
  152. public textureHalfFloat: boolean;
  153. public textureHalfFloatLinearFiltering: boolean;
  154. public textureHalfFloatRender: boolean;
  155. public textureLOD: boolean;
  156. public drawBuffersExtension;
  157. public colorBufferFloat: boolean;
  158. }
  159. export interface EngineOptions extends WebGLContextAttributes {
  160. limitDeviceRatio?: number;
  161. autoEnableWebVR?: boolean;
  162. disableWebGL2Support?: boolean;
  163. audioEngine?: boolean;
  164. }
  165. /**
  166. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  167. */
  168. export class Engine {
  169. public static Instances = new Array<Engine>();
  170. public static get LastCreatedEngine(): Engine {
  171. if (Engine.Instances.length === 0) {
  172. return null;
  173. }
  174. return Engine.Instances[Engine.Instances.length - 1];
  175. }
  176. public static get LastCreatedScene(): Scene {
  177. var lastCreatedEngine = Engine.LastCreatedEngine;
  178. if (!lastCreatedEngine) {
  179. return null;
  180. }
  181. if (lastCreatedEngine.scenes.length === 0) {
  182. return null;
  183. }
  184. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  185. }
  186. /**
  187. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  188. */
  189. public static MarkAllMaterialsAsDirty(flag:number, predicate?: (mat: Material) => boolean): void {
  190. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  191. var engine = Engine.Instances[engineIndex];
  192. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  193. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  194. }
  195. }
  196. }
  197. // Const statics
  198. private static _ALPHA_DISABLE = 0;
  199. private static _ALPHA_ADD = 1;
  200. private static _ALPHA_COMBINE = 2;
  201. private static _ALPHA_SUBTRACT = 3;
  202. private static _ALPHA_MULTIPLY = 4;
  203. private static _ALPHA_MAXIMIZED = 5;
  204. private static _ALPHA_ONEONE = 6;
  205. private static _ALPHA_PREMULTIPLIED = 7;
  206. private static _DELAYLOADSTATE_NONE = 0;
  207. private static _DELAYLOADSTATE_LOADED = 1;
  208. private static _DELAYLOADSTATE_LOADING = 2;
  209. private static _DELAYLOADSTATE_NOTLOADED = 4;
  210. private static _TEXTUREFORMAT_ALPHA = 0;
  211. private static _TEXTUREFORMAT_LUMINANCE = 1;
  212. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  213. private static _TEXTUREFORMAT_RGB = 4;
  214. private static _TEXTUREFORMAT_RGBA = 5;
  215. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  216. private static _TEXTURETYPE_FLOAT = 1;
  217. private static _TEXTURETYPE_HALF_FLOAT = 2;
  218. // Depht or Stencil test Constants.
  219. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  220. private static _ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  221. private static _LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  222. private static _EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  223. private static _LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  224. private static _GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  225. private static _GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  226. private static _NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  227. private static HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  228. private static RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  229. private static RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  230. public static get NEVER(): number {
  231. return Engine._NEVER;
  232. }
  233. public static get ALWAYS(): number {
  234. return Engine._ALWAYS;
  235. }
  236. public static get LESS(): number {
  237. return Engine._LESS;
  238. }
  239. public static get EQUAL(): number {
  240. return Engine._EQUAL;
  241. }
  242. public static get LEQUAL(): number {
  243. return Engine._LEQUAL;
  244. }
  245. public static get GREATER(): number {
  246. return Engine._GREATER;
  247. }
  248. public static get GEQUAL(): number {
  249. return Engine._GEQUAL;
  250. }
  251. public static get NOTEQUAL(): number {
  252. return Engine._NOTEQUAL;
  253. }
  254. // Stencil Actions Constants.
  255. private static _KEEP = 0x1E00;
  256. private static _REPLACE = 0x1E01;
  257. private static _INCR = 0x1E02;
  258. private static _DECR = 0x1E03;
  259. private static _INVERT = 0x150A;
  260. private static _INCR_WRAP = 0x8507;
  261. private static _DECR_WRAP = 0x8508;
  262. public static get KEEP(): number {
  263. return Engine._KEEP;
  264. }
  265. public static get REPLACE(): number {
  266. return Engine._REPLACE;
  267. }
  268. public static get INCR(): number {
  269. return Engine._INCR;
  270. }
  271. public static get DECR(): number {
  272. return Engine._DECR;
  273. }
  274. public static get INVERT(): number {
  275. return Engine._INVERT;
  276. }
  277. public static get INCR_WRAP(): number {
  278. return Engine._INCR_WRAP;
  279. }
  280. public static get DECR_WRAP(): number {
  281. return Engine._DECR_WRAP;
  282. }
  283. public static get ALPHA_DISABLE(): number {
  284. return Engine._ALPHA_DISABLE;
  285. }
  286. public static get ALPHA_ONEONE(): number {
  287. return Engine._ALPHA_ONEONE;
  288. }
  289. public static get ALPHA_ADD(): number {
  290. return Engine._ALPHA_ADD;
  291. }
  292. public static get ALPHA_COMBINE(): number {
  293. return Engine._ALPHA_COMBINE;
  294. }
  295. public static get ALPHA_SUBTRACT(): number {
  296. return Engine._ALPHA_SUBTRACT;
  297. }
  298. public static get ALPHA_MULTIPLY(): number {
  299. return Engine._ALPHA_MULTIPLY;
  300. }
  301. public static get ALPHA_MAXIMIZED(): number {
  302. return Engine._ALPHA_MAXIMIZED;
  303. }
  304. public static get ALPHA_PREMULTIPLIED(): number {
  305. return Engine._ALPHA_PREMULTIPLIED;
  306. }
  307. public static get DELAYLOADSTATE_NONE(): number {
  308. return Engine._DELAYLOADSTATE_NONE;
  309. }
  310. public static get DELAYLOADSTATE_LOADED(): number {
  311. return Engine._DELAYLOADSTATE_LOADED;
  312. }
  313. public static get DELAYLOADSTATE_LOADING(): number {
  314. return Engine._DELAYLOADSTATE_LOADING;
  315. }
  316. public static get DELAYLOADSTATE_NOTLOADED(): number {
  317. return Engine._DELAYLOADSTATE_NOTLOADED;
  318. }
  319. public static get TEXTUREFORMAT_ALPHA(): number {
  320. return Engine._TEXTUREFORMAT_ALPHA;
  321. }
  322. public static get TEXTUREFORMAT_LUMINANCE(): number {
  323. return Engine._TEXTUREFORMAT_LUMINANCE;
  324. }
  325. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  326. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  327. }
  328. public static get TEXTUREFORMAT_RGB(): number {
  329. return Engine._TEXTUREFORMAT_RGB;
  330. }
  331. public static get TEXTUREFORMAT_RGBA(): number {
  332. return Engine._TEXTUREFORMAT_RGBA;
  333. }
  334. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  335. return Engine._TEXTURETYPE_UNSIGNED_INT;
  336. }
  337. public static get TEXTURETYPE_FLOAT(): number {
  338. return Engine._TEXTURETYPE_FLOAT;
  339. }
  340. public static get TEXTURETYPE_HALF_FLOAT(): number {
  341. return Engine._TEXTURETYPE_HALF_FLOAT;
  342. }
  343. public static get Version(): string {
  344. return "3.0-alpha";
  345. }
  346. // Updatable statics so stick with vars here
  347. public static CollisionsEpsilon = 0.001;
  348. public static CodeRepository = "src/";
  349. public static ShadersRepository = "src/Shaders/";
  350. // Public members
  351. public isFullscreen = false;
  352. public isPointerLock = false;
  353. public cullBackFaces = true;
  354. public renderEvenInBackground = true;
  355. public preventCacheWipeBetweenFrames = false;
  356. // To enable/disable IDB support and avoid XHR on .manifest
  357. public enableOfflineSupport = true;
  358. public scenes = new Array<Scene>();
  359. //WebVR
  360. //The new WebVR uses promises.
  361. //this promise resolves with the current devices available.
  362. public vrDisplaysPromise;
  363. private _vrDisplays;
  364. private _vrDisplayEnabled;
  365. private _oldSize: BABYLON.Size;
  366. private _oldHardwareScaleFactor: number;
  367. private _vrAnimationFrameHandler: number;
  368. // Private Members
  369. public _gl: WebGLRenderingContext;
  370. private _renderingCanvas: HTMLCanvasElement;
  371. private _windowIsBackground = false;
  372. private _webGLVersion = 1.0;
  373. private _badOS = false;
  374. public static audioEngine: AudioEngine;
  375. private _onBlur: () => void;
  376. private _onFocus: () => void;
  377. private _onFullscreenChange: () => void;
  378. private _onPointerLockChange: () => void;
  379. private _hardwareScalingLevel: number;
  380. private _caps: EngineCapabilities;
  381. private _pointerLockRequested: boolean;
  382. private _alphaTest: boolean;
  383. private _isStencilEnable: boolean;
  384. private _loadingScreen: ILoadingScreen;
  385. public _drawCalls = new PerfCounter();
  386. private _glVersion: string;
  387. private _glRenderer: string;
  388. private _glVendor: string;
  389. private _videoTextureSupported: boolean;
  390. private _renderingQueueLaunched = false;
  391. private _activeRenderLoops = [];
  392. // FPS
  393. private fpsRange = 60;
  394. private previousFramesDuration = [];
  395. private fps = 60;
  396. private deltaTime = 0;
  397. // States
  398. private _depthCullingState = new Internals._DepthCullingState();
  399. private _stencilState = new Internals._StencilState();
  400. private _alphaState = new Internals._AlphaState();
  401. private _alphaMode = Engine.ALPHA_DISABLE;
  402. // Cache
  403. private _loadedTexturesCache = new Array<WebGLTexture>();
  404. private _maxTextureChannels = 16;
  405. private _activeTexture: number;
  406. private _activeTexturesCache = new Array<WebGLTexture>(this._maxTextureChannels);
  407. private _currentEffect: Effect;
  408. private _currentProgram: WebGLProgram;
  409. private _compiledEffects = {};
  410. private _vertexAttribArraysEnabled: boolean[] = [];
  411. private _cachedViewport: Viewport;
  412. private _cachedVertexArrayObject: WebGLVertexArrayObject;
  413. private _cachedVertexBuffers: any;
  414. private _cachedIndexBuffer: WebGLBuffer;
  415. private _cachedEffectForVertexBuffers: Effect;
  416. private _currentRenderTarget: WebGLTexture;
  417. private _uintIndicesCurrentlySet = false;
  418. private _currentBoundBuffer = new Array<WebGLBuffer>();
  419. private _currentFramebuffer: WebGLFramebuffer;
  420. private _currentBufferPointers: Array<{ indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number, buffer: WebGLBuffer }> = [];
  421. private _currentInstanceLocations = new Array<number>();
  422. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  423. private _textureUnits: Int32Array;
  424. private _workingCanvas: HTMLCanvasElement;
  425. private _workingContext: CanvasRenderingContext2D;
  426. private _externalData: StringDictionary<Object>;
  427. private _bindedRenderFunction: any;
  428. private _vaoRecordInProgress = false;
  429. private _mustWipeVertexAttributes = false;
  430. // Hardware supported Compressed Textures
  431. private _texturesSupported = new Array<string>();
  432. private _textureFormatInUse: string;
  433. public get texturesSupported(): Array<string> {
  434. return this._texturesSupported;
  435. }
  436. public get textureFormatInUse(): string {
  437. return this._textureFormatInUse;
  438. }
  439. /**
  440. * @constructor
  441. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  442. * @param {boolean} [antialias] - enable antialias
  443. * @param options - further options to be sent to the getContext function
  444. */
  445. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
  446. this._renderingCanvas = canvas;
  447. Engine.Instances.push(this);
  448. this._externalData = new StringDictionary<Object>();
  449. options = options || {};
  450. if (antialias != null) {
  451. options.antialias = antialias;
  452. }
  453. if (options.preserveDrawingBuffer === undefined) {
  454. options.preserveDrawingBuffer = false;
  455. }
  456. if (options.audioEngine === undefined) {
  457. options.audioEngine = true;
  458. }
  459. if (options.stencil === undefined) {
  460. options.stencil = true;
  461. }
  462. // GL
  463. if (!options.disableWebGL2Support) {
  464. try {
  465. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  466. if (this._gl) {
  467. this._webGLVersion = 2.0;
  468. }
  469. } catch (e) {
  470. // Do nothing
  471. }
  472. }
  473. if (!this._gl) {
  474. if (!canvas) {
  475. throw new Error("The provided canvas is null or undefined.");
  476. }
  477. try {
  478. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  479. } catch (e) {
  480. throw new Error("WebGL not supported");
  481. }
  482. }
  483. if (!this._gl) {
  484. throw new Error("WebGL not supported");
  485. }
  486. this._onBlur = () => {
  487. this._windowIsBackground = true;
  488. };
  489. this._onFocus = () => {
  490. this._windowIsBackground = false;
  491. };
  492. window.addEventListener("blur", this._onBlur);
  493. window.addEventListener("focus", this._onFocus);
  494. // Viewport
  495. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  496. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  497. this.resize();
  498. // Caps
  499. this._isStencilEnable = options.stencil;
  500. this._caps = new EngineCapabilities();
  501. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  502. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  503. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  504. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  505. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  506. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  507. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  508. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  509. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  510. // Infos
  511. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  512. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  513. if (rendererInfo != null) {
  514. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  515. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  516. }
  517. if (!this._glVendor) {
  518. this._glVendor = "Unknown vendor";
  519. }
  520. if (!this._glRenderer) {
  521. this._glRenderer = "Unknown renderer";
  522. }
  523. // Extensions
  524. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  525. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  526. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  527. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  528. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1' );
  529. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc' ) ||
  530. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  531. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  532. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  533. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  534. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  535. this._caps.highPrecisionShaderSupported = true;
  536. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  537. // Checks if some of the format renders first to allow the use of webgl inspector.
  538. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float')
  539. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  540. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  541. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  542. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  543. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  544. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  545. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  546. // Vertex array object
  547. if (this._webGLVersion > 1) {
  548. this._caps.vertexArrayObject = true;
  549. } else {
  550. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  551. if (vertexArrayObjectExtension != null) {
  552. this._caps.vertexArrayObject = true;
  553. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  554. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  555. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  556. } else {
  557. this._caps.vertexArrayObject = false;
  558. }
  559. }
  560. // Instances count
  561. if (this._webGLVersion > 1) {
  562. this._caps.instancedArrays = true;
  563. } else {
  564. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  565. if (instanceExtension != null) {
  566. this._caps.instancedArrays = true;
  567. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  568. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  569. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  570. } else {
  571. this._caps.instancedArrays = false;
  572. }
  573. }
  574. // Intelligently add supported compressed formats in order to check for.
  575. // Check for ASTC support first as it is most powerful and to be very cross platform.
  576. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  577. // Likely no hardware which supports both PVR & DXT, so order matters little.
  578. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  579. if (this._caps.astc ) this.texturesSupported.push('-astc.ktx');
  580. if (this._caps.s3tc ) this.texturesSupported.push('-dxt.ktx');
  581. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  582. if (this._caps.etc2 ) this.texturesSupported.push('-etc2.ktx');
  583. if (this._caps.etc1 ) this.texturesSupported.push('-etc1.ktx');
  584. if (this._gl.getShaderPrecisionFormat) {
  585. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  586. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  587. }
  588. // Depth buffer
  589. this.setDepthBuffer(true);
  590. this.setDepthFunctionToLessOrEqual();
  591. this.setDepthWrite(true);
  592. // Fullscreen
  593. this._onFullscreenChange = () => {
  594. if (document.fullscreen !== undefined) {
  595. this.isFullscreen = document.fullscreen;
  596. } else if (document.mozFullScreen !== undefined) {
  597. this.isFullscreen = document.mozFullScreen;
  598. } else if (document.webkitIsFullScreen !== undefined) {
  599. this.isFullscreen = document.webkitIsFullScreen;
  600. } else if (document.msIsFullScreen !== undefined) {
  601. this.isFullscreen = document.msIsFullScreen;
  602. }
  603. // Pointer lock
  604. if (this.isFullscreen && this._pointerLockRequested) {
  605. canvas.requestPointerLock = canvas.requestPointerLock ||
  606. canvas.msRequestPointerLock ||
  607. canvas.mozRequestPointerLock ||
  608. canvas.webkitRequestPointerLock;
  609. if (canvas.requestPointerLock) {
  610. canvas.requestPointerLock();
  611. }
  612. }
  613. };
  614. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  615. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  616. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  617. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  618. // Pointer lock
  619. this._onPointerLockChange = () => {
  620. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  621. document.webkitPointerLockElement === canvas ||
  622. document.msPointerLockElement === canvas ||
  623. document.pointerLockElement === canvas
  624. );
  625. };
  626. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  627. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  628. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  629. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  630. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  631. Engine.audioEngine = new AudioEngine();
  632. }
  633. //Load WebVR Devices
  634. if (options.autoEnableWebVR) {
  635. this.initWebVR();
  636. }
  637. //Detect if we are running on a faulty buggy OS.
  638. var regexp = /AppleWebKit.*10.[\d] Mobile/
  639. //ua sniffing is the tool of the devil.
  640. this._badOS = regexp.test(navigator.userAgent);
  641. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  642. }
  643. public get webGLVersion(): number {
  644. return this._webGLVersion;
  645. }
  646. /**
  647. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  648. */
  649. public get isStencilEnable(): boolean {
  650. return this._isStencilEnable;
  651. }
  652. private _prepareWorkingCanvas(): void {
  653. if (this._workingCanvas) {
  654. return;
  655. }
  656. this._workingCanvas = document.createElement("canvas");
  657. this._workingContext = this._workingCanvas.getContext("2d");
  658. }
  659. public resetTextureCache() {
  660. for (var index = 0; index < this._maxTextureChannels; index++) {
  661. this._activeTexturesCache[index] = null;
  662. }
  663. }
  664. public getGlInfo() {
  665. return {
  666. vendor: this._glVendor,
  667. renderer: this._glRenderer,
  668. version: this._glVersion
  669. }
  670. }
  671. public getAspectRatio(camera: Camera, useScreen = false): number {
  672. var viewport = camera.viewport;
  673. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  674. }
  675. public getRenderWidth(useScreen = false): number {
  676. if (!useScreen && this._currentRenderTarget) {
  677. return this._currentRenderTarget._width;
  678. }
  679. return this._renderingCanvas.width;
  680. }
  681. public getRenderHeight(useScreen = false): number {
  682. if (!useScreen && this._currentRenderTarget) {
  683. return this._currentRenderTarget._height;
  684. }
  685. return this._renderingCanvas.height;
  686. }
  687. public getRenderingCanvas(): HTMLCanvasElement {
  688. return this._renderingCanvas;
  689. }
  690. public getRenderingCanvasClientRect(): ClientRect {
  691. return this._renderingCanvas.getBoundingClientRect();
  692. }
  693. public setHardwareScalingLevel(level: number): void {
  694. this._hardwareScalingLevel = level;
  695. this.resize();
  696. }
  697. public getHardwareScalingLevel(): number {
  698. return this._hardwareScalingLevel;
  699. }
  700. public getLoadedTexturesCache(): WebGLTexture[] {
  701. return this._loadedTexturesCache;
  702. }
  703. public getCaps(): EngineCapabilities {
  704. return this._caps;
  705. }
  706. public get drawCalls(): number {
  707. return this._drawCalls.current;
  708. }
  709. public get drawCallsPerfCounter(): PerfCounter {
  710. return this._drawCalls;
  711. }
  712. public getDepthFunction(): number {
  713. return this._depthCullingState.depthFunc;
  714. }
  715. public setDepthFunction(depthFunc: number) {
  716. this._depthCullingState.depthFunc = depthFunc;
  717. }
  718. public setDepthFunctionToGreater(): void {
  719. this._depthCullingState.depthFunc = this._gl.GREATER;
  720. }
  721. public setDepthFunctionToGreaterOrEqual(): void {
  722. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  723. }
  724. public setDepthFunctionToLess(): void {
  725. this._depthCullingState.depthFunc = this._gl.LESS;
  726. }
  727. public setDepthFunctionToLessOrEqual(): void {
  728. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  729. }
  730. public getStencilBuffer(): boolean {
  731. return this._stencilState.stencilTest;
  732. }
  733. public setStencilBuffer(enable: boolean): void {
  734. this._stencilState.stencilTest = enable;
  735. }
  736. public getStencilMask(): number {
  737. return this._stencilState.stencilMask;
  738. }
  739. public setStencilMask(mask: number): void {
  740. this._stencilState.stencilMask = mask;
  741. }
  742. public getStencilFunction(): number {
  743. return this._stencilState.stencilFunc;
  744. }
  745. public getStencilFunctionReference(): number {
  746. return this._stencilState.stencilFuncRef;
  747. }
  748. public getStencilFunctionMask(): number {
  749. return this._stencilState.stencilFuncMask;
  750. }
  751. public setStencilFunction(stencilFunc: number) {
  752. this._stencilState.stencilFunc = stencilFunc;
  753. }
  754. public setStencilFunctionReference(reference: number) {
  755. this._stencilState.stencilFuncRef = reference;
  756. }
  757. public setStencilFunctionMask(mask: number) {
  758. this._stencilState.stencilFuncMask = mask;
  759. }
  760. public getStencilOperationFail(): number {
  761. return this._stencilState.stencilOpStencilFail;
  762. }
  763. public getStencilOperationDepthFail(): number {
  764. return this._stencilState.stencilOpDepthFail;
  765. }
  766. public getStencilOperationPass(): number {
  767. return this._stencilState.stencilOpStencilDepthPass;
  768. }
  769. public setStencilOperationFail(operation: number): void {
  770. this._stencilState.stencilOpStencilFail = operation;
  771. }
  772. public setStencilOperationDepthFail(operation: number): void {
  773. this._stencilState.stencilOpDepthFail = operation;
  774. }
  775. public setStencilOperationPass(operation: number): void {
  776. this._stencilState.stencilOpStencilDepthPass = operation;
  777. }
  778. /**
  779. * stop executing a render loop function and remove it from the execution array
  780. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  781. */
  782. public stopRenderLoop(renderFunction?: () => void): void {
  783. if (!renderFunction) {
  784. this._activeRenderLoops = [];
  785. return;
  786. }
  787. var index = this._activeRenderLoops.indexOf(renderFunction);
  788. if (index >= 0) {
  789. this._activeRenderLoops.splice(index, 1);
  790. }
  791. }
  792. public _renderLoop(): void {
  793. var shouldRender = true;
  794. if (!this.renderEvenInBackground && this._windowIsBackground) {
  795. shouldRender = false;
  796. }
  797. if (shouldRender) {
  798. // Start new frame
  799. this.beginFrame();
  800. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  801. var renderFunction = this._activeRenderLoops[index];
  802. renderFunction();
  803. }
  804. // Present
  805. this.endFrame();
  806. }
  807. if (this._activeRenderLoops.length > 0) {
  808. // Register new frame
  809. Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  810. } else {
  811. this._renderingQueueLaunched = false;
  812. }
  813. }
  814. /**
  815. * Register and execute a render loop. The engine can have more than one render function.
  816. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  817. * @example
  818. * engine.runRenderLoop(function () {
  819. * scene.render()
  820. * })
  821. */
  822. public runRenderLoop(renderFunction: () => void): void {
  823. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  824. return;
  825. }
  826. this._activeRenderLoops.push(renderFunction);
  827. if (!this._renderingQueueLaunched) {
  828. this._renderingQueueLaunched = true;
  829. this._bindedRenderFunction = this._renderLoop.bind(this);
  830. Tools.QueueNewFrame(this._bindedRenderFunction);
  831. }
  832. }
  833. /**
  834. * Toggle full screen mode.
  835. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  836. * @param {any} options - an options object to be sent to the requestFullscreen function
  837. */
  838. public switchFullscreen(requestPointerLock: boolean): void {
  839. if (this.isFullscreen) {
  840. Tools.ExitFullscreen();
  841. } else {
  842. this._pointerLockRequested = requestPointerLock;
  843. Tools.RequestFullscreen(this._renderingCanvas);
  844. }
  845. }
  846. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  847. this.applyStates();
  848. var mode = 0;
  849. if (backBuffer && color) {
  850. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  851. mode |= this._gl.COLOR_BUFFER_BIT;
  852. }
  853. if (depth) {
  854. this._gl.clearDepth(1.0);
  855. mode |= this._gl.DEPTH_BUFFER_BIT;
  856. }
  857. if (stencil) {
  858. this._gl.clearStencil(0);
  859. mode |= this._gl.STENCIL_BUFFER_BIT;
  860. }
  861. this._gl.clear(mode);
  862. }
  863. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  864. let gl = this._gl;
  865. // Save state
  866. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  867. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  868. // Change state
  869. gl.enable(gl.SCISSOR_TEST);
  870. gl.scissor(x, y, width, height);
  871. // Clear
  872. this.clear(clearColor, true, true, true);
  873. // Restore state
  874. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  875. if (curScissor === true) {
  876. gl.enable(gl.SCISSOR_TEST);
  877. } else {
  878. gl.disable(gl.SCISSOR_TEST);
  879. }
  880. }
  881. /**
  882. * Set the WebGL's viewport
  883. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  884. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  885. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  886. */
  887. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  888. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  889. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  890. var x = viewport.x || 0;
  891. var y = viewport.y || 0;
  892. this._cachedViewport = viewport;
  893. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  894. }
  895. /**
  896. * Directly set the WebGL Viewport
  897. * The x, y, width & height are directly passed to the WebGL call
  898. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  899. */
  900. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  901. let currentViewport = this._cachedViewport;
  902. this._cachedViewport = null;
  903. this._gl.viewport(x, y, width, height);
  904. return currentViewport;
  905. }
  906. public beginFrame(): void {
  907. this._measureFps();
  908. }
  909. public endFrame(): void {
  910. //force a flush in case we are using a bad OS.
  911. if (this._badOS) {
  912. this.flushFramebuffer();
  913. }
  914. //submit frame to the vr device, if enabled
  915. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  916. this._vrDisplayEnabled.submitFrame()
  917. }
  918. }
  919. /**
  920. * resize the view according to the canvas' size.
  921. * @example
  922. * window.addEventListener("resize", function () {
  923. * engine.resize();
  924. * });
  925. */
  926. public resize(): void {
  927. // We're not resizing the size of the canvas while in VR mode & presenting
  928. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  929. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  930. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  931. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  932. }
  933. }
  934. /**
  935. * force a specific size of the canvas
  936. * @param {number} width - the new canvas' width
  937. * @param {number} height - the new canvas' height
  938. */
  939. public setSize(width: number, height: number): void {
  940. this._renderingCanvas.width = width;
  941. this._renderingCanvas.height = height;
  942. for (var index = 0; index < this.scenes.length; index++) {
  943. var scene = this.scenes[index];
  944. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  945. var cam = scene.cameras[camIndex];
  946. cam._currentRenderId = 0;
  947. }
  948. }
  949. }
  950. //WebVR functions
  951. public initWebVR() {
  952. if (!this.vrDisplaysPromise) {
  953. this._getVRDisplays();
  954. }
  955. }
  956. public enableVR(vrDevice) {
  957. this._vrDisplayEnabled = vrDevice;
  958. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  959. }
  960. public disableVR() {
  961. if (this._vrDisplayEnabled) {
  962. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  963. }
  964. }
  965. private _onVRFullScreenTriggered = () => {
  966. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  967. //get the old size before we change
  968. this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
  969. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  970. //get the width and height, change the render size
  971. var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
  972. var width, height;
  973. this.setHardwareScalingLevel(1);
  974. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  975. } else {
  976. //When the specs are implemented, need to uncomment this.
  977. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  978. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  979. this.setSize(this._oldSize.width, this._oldSize.height);
  980. this._vrDisplayEnabled = undefined;
  981. }
  982. }
  983. private _getVRDisplays() {
  984. var getWebVRDevices = (devices: Array<any>) => {
  985. var size = devices.length;
  986. var i = 0;
  987. this._vrDisplays = devices.filter(function (device) {
  988. return devices[i] instanceof VRDisplay;
  989. });
  990. return this._vrDisplays;
  991. }
  992. //using a key due to typescript
  993. if (navigator.getVRDisplays) {
  994. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  995. }
  996. }
  997. public bindFramebuffer(texture: WebGLTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number): void {
  998. this._currentRenderTarget = texture;
  999. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1000. var gl = this._gl;
  1001. if (texture.isCube) {
  1002. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  1003. }
  1004. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  1005. this.wipeCaches();
  1006. }
  1007. private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
  1008. if (this._currentFramebuffer !== framebuffer) {
  1009. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1010. this._currentFramebuffer = framebuffer;
  1011. }
  1012. }
  1013. public unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1014. this._currentRenderTarget = null;
  1015. // If MSAA, we need to bitblt back to main texture
  1016. var gl = this._gl;
  1017. if (texture._MSAAFramebuffer) {
  1018. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1019. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1020. gl.blitFramebuffer(0, 0, texture._width, texture._height,
  1021. 0, 0, texture._width, texture._height,
  1022. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1023. }
  1024. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  1025. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1026. gl.generateMipmap(gl.TEXTURE_2D);
  1027. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1028. }
  1029. if (onBeforeUnbind) {
  1030. if (texture._MSAAFramebuffer) {
  1031. // Bind the correct framebuffer
  1032. this.bindUnboundFramebuffer(texture._framebuffer);
  1033. }
  1034. onBeforeUnbind();
  1035. }
  1036. this.bindUnboundFramebuffer(null);
  1037. }
  1038. public generateMipMapsForCubemap(texture: WebGLTexture) {
  1039. if (texture.generateMipMaps) {
  1040. var gl = this._gl;
  1041. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1042. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1043. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1044. }
  1045. }
  1046. public flushFramebuffer(): void {
  1047. this._gl.flush();
  1048. }
  1049. public restoreDefaultFramebuffer(): void {
  1050. this._currentRenderTarget = null;
  1051. this.bindUnboundFramebuffer(null);
  1052. this.setViewport(this._cachedViewport);
  1053. this.wipeCaches();
  1054. }
  1055. // VBOs
  1056. private _resetVertexBufferBinding(): void {
  1057. this.bindArrayBuffer(null);
  1058. this._cachedVertexBuffers = null;
  1059. }
  1060. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1061. var vbo = this._gl.createBuffer();
  1062. this.bindArrayBuffer(vbo);
  1063. if (vertices instanceof Float32Array) {
  1064. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1065. } else {
  1066. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1067. }
  1068. this._resetVertexBufferBinding();
  1069. vbo.references = 1;
  1070. return vbo;
  1071. }
  1072. public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1073. var vbo = this._gl.createBuffer();
  1074. this.bindArrayBuffer(vbo);
  1075. if (vertices instanceof Float32Array) {
  1076. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1077. } else {
  1078. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1079. }
  1080. this._resetVertexBufferBinding();
  1081. vbo.references = 1;
  1082. return vbo;
  1083. }
  1084. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
  1085. this.bindArrayBuffer(vertexBuffer);
  1086. if (offset === undefined) {
  1087. offset = 0;
  1088. }
  1089. if (count === undefined) {
  1090. if (vertices instanceof Float32Array) {
  1091. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1092. } else {
  1093. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1094. }
  1095. } else {
  1096. if (vertices instanceof Float32Array) {
  1097. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1098. } else {
  1099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1100. }
  1101. }
  1102. this._resetVertexBufferBinding();
  1103. }
  1104. private _resetIndexBufferBinding(): void {
  1105. this.bindIndexBuffer(null);
  1106. this._cachedIndexBuffer = null;
  1107. }
  1108. public createIndexBuffer(indices: IndicesArray): WebGLBuffer {
  1109. var vbo = this._gl.createBuffer();
  1110. this.bindIndexBuffer(vbo);
  1111. // Check for 32 bits indices
  1112. var arrayBuffer;
  1113. var need32Bits = false;
  1114. if (indices instanceof Uint16Array) {
  1115. arrayBuffer = indices;
  1116. } else {
  1117. //check 32 bit support
  1118. if (this._caps.uintIndices) {
  1119. if (indices instanceof Uint32Array) {
  1120. arrayBuffer = indices;
  1121. need32Bits = true;
  1122. } else {
  1123. //number[] or Int32Array, check if 32 bit is necessary
  1124. for (var index = 0; index < indices.length; index++) {
  1125. if (indices[index] > 65535) {
  1126. need32Bits = true;
  1127. break;
  1128. }
  1129. }
  1130. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1131. }
  1132. } else {
  1133. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1134. arrayBuffer = new Uint16Array(indices);
  1135. }
  1136. }
  1137. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  1138. this._resetIndexBufferBinding();
  1139. vbo.references = 1;
  1140. vbo.is32Bits = need32Bits;
  1141. return vbo;
  1142. }
  1143. public bindArrayBuffer(buffer: WebGLBuffer): void {
  1144. if (!this._vaoRecordInProgress) {
  1145. this._unBindVertexArrayObject();
  1146. }
  1147. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1148. }
  1149. private bindIndexBuffer(buffer: WebGLBuffer): void {
  1150. if (!this._vaoRecordInProgress) {
  1151. this._unBindVertexArrayObject();
  1152. }
  1153. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1154. }
  1155. private bindBuffer(buffer: WebGLBuffer, target: number): void {
  1156. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1157. this._gl.bindBuffer(target, buffer);
  1158. this._currentBoundBuffer[target] = buffer;
  1159. }
  1160. }
  1161. public updateArrayBuffer(data: Float32Array): void {
  1162. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1163. }
  1164. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1165. var pointer = this._currentBufferPointers[indx];
  1166. var changed = false;
  1167. if (!pointer) {
  1168. changed = true;
  1169. this._currentBufferPointers[indx] = { indx, size, type, normalized, stride, offset, buffer: buffer };
  1170. } else {
  1171. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1172. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1173. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1174. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1175. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1176. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1177. }
  1178. if (changed || this._vaoRecordInProgress) {
  1179. this.bindArrayBuffer(buffer);
  1180. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1181. }
  1182. }
  1183. private _bindIndexBufferWithCache(indexBuffer: WebGLBuffer): void {
  1184. if (indexBuffer == null) {
  1185. return;
  1186. }
  1187. if (this._cachedIndexBuffer !== indexBuffer) {
  1188. this._cachedIndexBuffer = indexBuffer;
  1189. this.bindIndexBuffer(indexBuffer);
  1190. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1191. }
  1192. }
  1193. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: VertexBuffer; }, effect: Effect) {
  1194. var attributes = effect.getAttributesNames();
  1195. if (!this._vaoRecordInProgress) {
  1196. this._unBindVertexArrayObject();
  1197. }
  1198. this.unbindAllAttributes();
  1199. for (var index = 0; index < attributes.length; index++) {
  1200. var order = effect.getAttributeLocation(index);
  1201. if (order >= 0) {
  1202. var vertexBuffer = vertexBuffers[attributes[index]];
  1203. if (!vertexBuffer) {
  1204. continue;
  1205. }
  1206. this._gl.enableVertexAttribArray(order);
  1207. if (!this._vaoRecordInProgress) {
  1208. this._vertexAttribArraysEnabled[order] = true;
  1209. }
  1210. var buffer = vertexBuffer.getBuffer();
  1211. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1212. if (vertexBuffer.getIsInstanced()) {
  1213. this._gl.vertexAttribDivisor(order, 1);
  1214. if (!this._vaoRecordInProgress) {
  1215. this._currentInstanceLocations.push(order);
  1216. this._currentInstanceBuffers.push(buffer);
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): WebGLVertexArrayObject {
  1223. var vao = this._gl.createVertexArray();
  1224. this._vaoRecordInProgress = true;
  1225. this._gl.bindVertexArray(vao);
  1226. this._mustWipeVertexAttributes = true;
  1227. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1228. this.bindIndexBuffer(indexBuffer);
  1229. this._vaoRecordInProgress = false;
  1230. this._gl.bindVertexArray(null);
  1231. return vao;
  1232. }
  1233. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: WebGLBuffer): void {
  1234. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1235. this._cachedVertexArrayObject = vertexArrayObject;
  1236. this._gl.bindVertexArray(vertexArrayObject);
  1237. this._cachedVertexBuffers = null;
  1238. this._cachedIndexBuffer = null;
  1239. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1240. this._mustWipeVertexAttributes = true;
  1241. }
  1242. }
  1243. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1244. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1245. this._cachedVertexBuffers = vertexBuffer;
  1246. this._cachedEffectForVertexBuffers = effect;
  1247. let attributesCount = effect.getAttributesCount();
  1248. this._unBindVertexArrayObject();
  1249. this.unbindAllAttributes();
  1250. var offset = 0;
  1251. for (var index = 0; index < attributesCount; index++) {
  1252. if (index < vertexDeclaration.length) {
  1253. var order = effect.getAttributeLocation(index);
  1254. if (order >= 0) {
  1255. this._gl.enableVertexAttribArray(order);
  1256. this._vertexAttribArraysEnabled[order] = true;
  1257. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1258. }
  1259. offset += vertexDeclaration[index] * 4;
  1260. }
  1261. }
  1262. }
  1263. this._bindIndexBufferWithCache(indexBuffer);
  1264. }
  1265. private _unBindVertexArrayObject(): void {
  1266. if (!this._cachedVertexArrayObject) {
  1267. return;
  1268. }
  1269. this._cachedVertexArrayObject = null;
  1270. this._gl.bindVertexArray(null);
  1271. }
  1272. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
  1273. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1274. this._cachedVertexBuffers = vertexBuffers;
  1275. this._cachedEffectForVertexBuffers = effect;
  1276. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1277. }
  1278. this._bindIndexBufferWithCache(indexBuffer);
  1279. }
  1280. public unbindInstanceAttributes() {
  1281. var boundBuffer;
  1282. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1283. var instancesBuffer = this._currentInstanceBuffers[i];
  1284. if (boundBuffer != instancesBuffer) {
  1285. boundBuffer = instancesBuffer;
  1286. this.bindArrayBuffer(instancesBuffer);
  1287. }
  1288. var offsetLocation = this._currentInstanceLocations[i];
  1289. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1290. }
  1291. this._currentInstanceBuffers.length = 0;
  1292. this._currentInstanceLocations.length = 0;
  1293. }
  1294. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1295. this._gl.deleteVertexArray(vao);
  1296. }
  1297. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1298. buffer.references--;
  1299. if (buffer.references === 0) {
  1300. this._gl.deleteBuffer(buffer);
  1301. return true;
  1302. }
  1303. return false;
  1304. }
  1305. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1306. var buffer = this._gl.createBuffer();
  1307. buffer.capacity = capacity;
  1308. this.bindArrayBuffer(buffer);
  1309. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1310. return buffer;
  1311. }
  1312. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1313. this._gl.deleteBuffer(buffer);
  1314. }
  1315. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1316. this.bindArrayBuffer(instancesBuffer);
  1317. if (data) {
  1318. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1319. }
  1320. if ((<any>offsetLocations[0]).index !== undefined) {
  1321. let stride = 0;
  1322. for (let i = 0; i < offsetLocations.length; i++) {
  1323. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1324. stride += ai.attributeSize * 4;
  1325. }
  1326. for (let i = 0; i < offsetLocations.length; i++) {
  1327. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1328. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1329. this._gl.enableVertexAttribArray(ai.index);
  1330. this._vertexAttribArraysEnabled[ai.index] = true;
  1331. }
  1332. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1333. this._gl.vertexAttribDivisor(ai.index, 1);
  1334. this._currentInstanceLocations.push(ai.index);
  1335. this._currentInstanceBuffers.push(instancesBuffer);
  1336. }
  1337. } else {
  1338. for (let index = 0; index < 4; index++) {
  1339. let offsetLocation = <number>offsetLocations[index];
  1340. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1341. this._gl.enableVertexAttribArray(offsetLocation);
  1342. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1343. }
  1344. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1345. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1346. this._currentInstanceLocations.push(offsetLocation);
  1347. this._currentInstanceBuffers.push(instancesBuffer);
  1348. }
  1349. }
  1350. }
  1351. public applyStates() {
  1352. this._depthCullingState.apply(this._gl);
  1353. this._stencilState.apply(this._gl);
  1354. this._alphaState.apply(this._gl);
  1355. }
  1356. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1357. // Apply states
  1358. this.applyStates();
  1359. this._drawCalls.addCount(1, false);
  1360. // Render
  1361. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1362. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1363. if (instancesCount) {
  1364. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1365. return;
  1366. }
  1367. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1368. }
  1369. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1370. // Apply states
  1371. this.applyStates();
  1372. this._drawCalls.addCount(1, false);
  1373. if (instancesCount) {
  1374. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1375. return;
  1376. }
  1377. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1378. }
  1379. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1380. // Apply states
  1381. this.applyStates();
  1382. this._drawCalls.addCount(1, false);
  1383. if (instancesCount) {
  1384. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1385. return;
  1386. }
  1387. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1388. }
  1389. // Shaders
  1390. public _releaseEffect(effect: Effect): void {
  1391. if (this._compiledEffects[effect._key]) {
  1392. delete this._compiledEffects[effect._key];
  1393. if (effect.getProgram()) {
  1394. this._gl.deleteProgram(effect.getProgram());
  1395. }
  1396. }
  1397. }
  1398. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  1399. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  1400. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1401. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1402. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  1403. if (this._compiledEffects[name]) {
  1404. return this._compiledEffects[name];
  1405. }
  1406. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1407. effect._key = name;
  1408. this._compiledEffects[name] = effect;
  1409. return effect;
  1410. }
  1411. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  1412. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  1413. return this.createEffect(
  1414. {
  1415. vertex: "particles",
  1416. fragmentElement: fragmentName
  1417. },
  1418. ["position", "color", "options"],
  1419. ["view", "projection"].concat(uniformsNames),
  1420. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1421. }
  1422. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
  1423. context = context || this._gl;
  1424. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  1425. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  1426. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  1427. var shaderProgram = context.createProgram();
  1428. context.attachShader(shaderProgram, vertexShader);
  1429. context.attachShader(shaderProgram, fragmentShader);
  1430. context.linkProgram(shaderProgram);
  1431. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1432. if (!linked) {
  1433. var error = context.getProgramInfoLog(shaderProgram);
  1434. if (error) {
  1435. throw new Error(error);
  1436. }
  1437. }
  1438. context.deleteShader(vertexShader);
  1439. context.deleteShader(fragmentShader);
  1440. return shaderProgram;
  1441. }
  1442. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  1443. var results = [];
  1444. for (var index = 0; index < uniformsNames.length; index++) {
  1445. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1446. }
  1447. return results;
  1448. }
  1449. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  1450. var results = [];
  1451. for (var index = 0; index < attributesNames.length; index++) {
  1452. try {
  1453. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1454. } catch (e) {
  1455. results.push(-1);
  1456. }
  1457. }
  1458. return results;
  1459. }
  1460. public enableEffect(effect: Effect): void {
  1461. // Use program
  1462. this.setProgram(effect.getProgram());
  1463. this._currentEffect = effect;
  1464. if (effect.onBind) {
  1465. effect.onBind(effect);
  1466. }
  1467. }
  1468. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  1469. if (!uniform)
  1470. return;
  1471. this._gl.uniform1iv(uniform, array);
  1472. }
  1473. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  1474. if (!uniform || array.length % 2 !== 0)
  1475. return;
  1476. this._gl.uniform2iv(uniform, array);
  1477. }
  1478. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  1479. if (!uniform || array.length % 3 !== 0)
  1480. return;
  1481. this._gl.uniform3iv(uniform, array);
  1482. }
  1483. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  1484. if (!uniform || array.length % 4 !== 0)
  1485. return;
  1486. this._gl.uniform4iv(uniform, array);
  1487. }
  1488. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  1489. if (!uniform)
  1490. return;
  1491. this._gl.uniform1fv(uniform, array);
  1492. }
  1493. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  1494. if (!uniform || array.length % 2 !== 0)
  1495. return;
  1496. this._gl.uniform2fv(uniform, array);
  1497. }
  1498. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  1499. if (!uniform || array.length % 3 !== 0)
  1500. return;
  1501. this._gl.uniform3fv(uniform, array);
  1502. }
  1503. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  1504. if (!uniform || array.length % 4 !== 0)
  1505. return;
  1506. this._gl.uniform4fv(uniform, array);
  1507. }
  1508. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  1509. if (!uniform)
  1510. return;
  1511. this._gl.uniform1fv(uniform, <any>array);
  1512. }
  1513. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1514. if (!uniform || array.length % 2 !== 0)
  1515. return;
  1516. this._gl.uniform2fv(uniform, <any>array);
  1517. }
  1518. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1519. if (!uniform || array.length % 3 !== 0)
  1520. return;
  1521. this._gl.uniform3fv(uniform, <any>array);
  1522. }
  1523. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1524. if (!uniform || array.length % 4 !== 0)
  1525. return;
  1526. this._gl.uniform4fv(uniform, <any>array);
  1527. }
  1528. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1529. if (!uniform)
  1530. return;
  1531. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1532. }
  1533. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1534. if (!uniform)
  1535. return;
  1536. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1537. }
  1538. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1539. if (!uniform)
  1540. return;
  1541. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1542. }
  1543. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1544. if (!uniform)
  1545. return;
  1546. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1547. }
  1548. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1549. if (!uniform)
  1550. return;
  1551. this._gl.uniform1f(uniform, value);
  1552. }
  1553. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1554. if (!uniform)
  1555. return;
  1556. this._gl.uniform2f(uniform, x, y);
  1557. }
  1558. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1559. if (!uniform)
  1560. return;
  1561. this._gl.uniform3f(uniform, x, y, z);
  1562. }
  1563. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1564. if (!uniform)
  1565. return;
  1566. this._gl.uniform1i(uniform, bool);
  1567. }
  1568. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1569. if (!uniform)
  1570. return;
  1571. this._gl.uniform4f(uniform, x, y, z, w);
  1572. }
  1573. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1574. if (!uniform)
  1575. return;
  1576. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1577. }
  1578. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1579. if (!uniform)
  1580. return;
  1581. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1582. }
  1583. // States
  1584. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1585. // Culling
  1586. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1587. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1588. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1589. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1590. if (culling) {
  1591. this._depthCullingState.cullFace = cullFace;
  1592. this._depthCullingState.cull = true;
  1593. } else {
  1594. this._depthCullingState.cull = false;
  1595. }
  1596. }
  1597. // Z offset
  1598. this._depthCullingState.zOffset = zOffset;
  1599. }
  1600. public setDepthBuffer(enable: boolean): void {
  1601. this._depthCullingState.depthTest = enable;
  1602. }
  1603. public getDepthWrite(): boolean {
  1604. return this._depthCullingState.depthMask;
  1605. }
  1606. public setDepthWrite(enable: boolean): void {
  1607. this._depthCullingState.depthMask = enable;
  1608. }
  1609. public setColorWrite(enable: boolean): void {
  1610. this._gl.colorMask(enable, enable, enable, enable);
  1611. }
  1612. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1613. if (this._alphaMode === mode) {
  1614. return;
  1615. }
  1616. switch (mode) {
  1617. case Engine.ALPHA_DISABLE:
  1618. this._alphaState.alphaBlend = false;
  1619. break;
  1620. case Engine.ALPHA_PREMULTIPLIED:
  1621. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1622. this._alphaState.alphaBlend = true;
  1623. break;
  1624. case Engine.ALPHA_COMBINE:
  1625. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1626. this._alphaState.alphaBlend = true;
  1627. break;
  1628. case Engine.ALPHA_ONEONE:
  1629. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1630. this._alphaState.alphaBlend = true;
  1631. break;
  1632. case Engine.ALPHA_ADD:
  1633. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1634. this._alphaState.alphaBlend = true;
  1635. break;
  1636. case Engine.ALPHA_SUBTRACT:
  1637. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1638. this._alphaState.alphaBlend = true;
  1639. break;
  1640. case Engine.ALPHA_MULTIPLY:
  1641. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1642. this._alphaState.alphaBlend = true;
  1643. break;
  1644. case Engine.ALPHA_MAXIMIZED:
  1645. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1646. this._alphaState.alphaBlend = true;
  1647. break;
  1648. }
  1649. if (!noDepthWriteChange) {
  1650. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1651. }
  1652. this._alphaMode = mode;
  1653. }
  1654. public getAlphaMode(): number {
  1655. return this._alphaMode;
  1656. }
  1657. public setAlphaTesting(enable: boolean): void {
  1658. this._alphaTest = enable;
  1659. }
  1660. public getAlphaTesting(): boolean {
  1661. return !!this._alphaTest;
  1662. }
  1663. // Textures
  1664. public wipeCaches(): void {
  1665. if (this.preventCacheWipeBetweenFrames) {
  1666. return;
  1667. }
  1668. this.resetTextureCache();
  1669. this._currentEffect = null;
  1670. this._stencilState.reset();
  1671. this._depthCullingState.reset();
  1672. this.setDepthFunctionToLessOrEqual();
  1673. this._alphaState.reset();
  1674. this._cachedVertexBuffers = null;
  1675. this._cachedIndexBuffer = null;
  1676. this._cachedEffectForVertexBuffers = null;
  1677. this._unBindVertexArrayObject();
  1678. this.bindIndexBuffer(null);
  1679. this.bindArrayBuffer(null);
  1680. }
  1681. /**
  1682. * Set the compressed texture format to use, based on the formats you have, and the formats
  1683. * supported by the hardware / browser.
  1684. *
  1685. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  1686. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  1687. * to API arguments needed to compressed textures. This puts the burden on the container
  1688. * generator to house the arcane code for determining these for current & future formats.
  1689. *
  1690. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  1691. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  1692. *
  1693. * Note: The result of this call is not taken into account when a texture is base64.
  1694. *
  1695. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  1696. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  1697. *
  1698. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  1699. * @returns The extension selected.
  1700. */
  1701. public setTextureFormatToUse(formatsAvailable: Array<string>): string {
  1702. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  1703. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  1704. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  1705. return this._textureFormatInUse = this._texturesSupported[i];
  1706. }
  1707. }
  1708. }
  1709. // actively set format to nothing, to allow this to be called more than once
  1710. // and possibly fail the 2nd time
  1711. return this._textureFormatInUse = null;
  1712. }
  1713. /**
  1714. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  1715. * @param {string} urlArg- This contains one of the following:
  1716. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  1717. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  1718. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  1719. *
  1720. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  1721. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  1722. * @param {Scene} scene- Needed for loading to the correct scene.
  1723. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  1724. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  1725. * @param {callback} onError- Optional callback to be called upon failure.
  1726. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  1727. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  1728. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  1729. *
  1730. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  1731. */
  1732. public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: ArrayBuffer | HTMLImageElement = null, fallBack?: WebGLTexture, format?: number): WebGLTexture {
  1733. var texture = fallBack ? fallBack : this._gl.createTexture();
  1734. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  1735. var fromData = url.substr(0, 5) === "data:";
  1736. var isBase64 = fromData && url.indexOf("base64") !== -1;
  1737. // establish the file extension, if possible
  1738. var lastDot = url.lastIndexOf('.');
  1739. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  1740. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1741. if (isDDS) {
  1742. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  1743. }
  1744. var isTGA = (extension === ".tga");
  1745. // determine if a ktx file should be substituted
  1746. var isKTX = false;
  1747. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  1748. url = url.substring(0, lastDot) + this._textureFormatInUse;
  1749. isKTX = true;
  1750. }
  1751. scene._addPendingData(texture);
  1752. texture.url = url;
  1753. texture.noMipmap = noMipmap;
  1754. texture.references = 1;
  1755. texture.samplingMode = samplingMode;
  1756. texture.onLoadedCallbacks = [];
  1757. if (onLoad) {
  1758. texture.onLoadedCallbacks.push(onLoad);
  1759. }
  1760. if (!fallBack) this._loadedTexturesCache.push(texture);
  1761. var onerror = () => {
  1762. scene._removePendingData(texture);
  1763. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  1764. if (isKTX) {
  1765. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  1766. } else if (onError) {
  1767. onError();
  1768. }
  1769. };
  1770. var callback: (arrayBuffer: any) => void;
  1771. // processing for non-image formats
  1772. if (isKTX || isTGA || isDDS) {
  1773. if (isKTX) {
  1774. callback = (data) => {
  1775. var ktx = new Internals.KhronosTextureContainer(data, 1);
  1776. prepareWebGLTexture(texture, this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  1777. ktx.uploadLevels(this._gl, !noMipmap);
  1778. }, samplingMode);
  1779. };
  1780. } else if (isTGA) {
  1781. callback = (arrayBuffer) => {
  1782. var data = new Uint8Array(arrayBuffer);
  1783. var header = Internals.TGATools.GetTGAHeader(data);
  1784. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1785. Internals.TGATools.UploadContent(this._gl, data);
  1786. }, samplingMode);
  1787. };
  1788. } else if (isDDS) {
  1789. callback = (data) => {
  1790. var info = Internals.DDSTools.GetDDSInfo(data);
  1791. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1792. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1793. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1794. }, samplingMode);
  1795. };
  1796. }
  1797. if (!buffer) {
  1798. Tools.LoadFile(url, data => {
  1799. callback(data);
  1800. }, null, scene.database, true, onerror);
  1801. } else {
  1802. callback(buffer);
  1803. }
  1804. // image format processing
  1805. } else {
  1806. var onload = (img) => {
  1807. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1808. var isPot = (img.width === potWidth && img.height === potHeight);
  1809. if (!isPot) {
  1810. this._prepareWorkingCanvas();
  1811. this._workingCanvas.width = potWidth;
  1812. this._workingCanvas.height = potHeight;
  1813. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1814. this._workingContext.imageSmoothingEnabled = false;
  1815. this._workingContext.mozImageSmoothingEnabled = false;
  1816. this._workingContext.oImageSmoothingEnabled = false;
  1817. this._workingContext.webkitImageSmoothingEnabled = false;
  1818. this._workingContext.msImageSmoothingEnabled = false;
  1819. }
  1820. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1821. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1822. this._workingContext.imageSmoothingEnabled = true;
  1823. this._workingContext.mozImageSmoothingEnabled = true;
  1824. this._workingContext.oImageSmoothingEnabled = true;
  1825. this._workingContext.webkitImageSmoothingEnabled = true;
  1826. this._workingContext.msImageSmoothingEnabled = true;
  1827. }
  1828. }
  1829. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? this._gl.RGB :this._gl.RGBA);
  1830. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1831. }, samplingMode);
  1832. };
  1833. if (!fromData || isBase64)
  1834. Tools.LoadImage(url, onload, onerror, scene.database);
  1835. else if (buffer instanceof Array || typeof buffer === "string")
  1836. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1837. else
  1838. onload(buffer);
  1839. }
  1840. return texture;
  1841. }
  1842. private _getInternalFormat(format: number): number {
  1843. var internalFormat = this._gl.RGBA;
  1844. switch (format) {
  1845. case Engine.TEXTUREFORMAT_ALPHA:
  1846. internalFormat = this._gl.ALPHA;
  1847. break;
  1848. case Engine.TEXTUREFORMAT_LUMINANCE:
  1849. internalFormat = this._gl.LUMINANCE;
  1850. break;
  1851. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1852. internalFormat = this._gl.LUMINANCE_ALPHA;
  1853. break;
  1854. case Engine.TEXTUREFORMAT_RGB:
  1855. internalFormat = this._gl.RGB;
  1856. break;
  1857. case Engine.TEXTUREFORMAT_RGBA:
  1858. internalFormat = this._gl.RGBA;
  1859. break;
  1860. }
  1861. return internalFormat;
  1862. }
  1863. public updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  1864. var internalFormat = this._getInternalFormat(format);
  1865. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1866. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1867. if (texture._width % 4 !== 0) {
  1868. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  1869. }
  1870. if (compression) {
  1871. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1872. } else {
  1873. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1874. }
  1875. if (texture.generateMipMaps) {
  1876. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1877. }
  1878. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1879. this.resetTextureCache();
  1880. texture.isReady = true;
  1881. }
  1882. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
  1883. var texture = this._gl.createTexture();
  1884. texture._baseWidth = width;
  1885. texture._baseHeight = height;
  1886. texture._width = width;
  1887. texture._height = height;
  1888. texture.references = 1;
  1889. this.updateRawTexture(texture, data, format, invertY, compression);
  1890. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1891. // Filters
  1892. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1893. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1894. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1895. if (generateMipMaps) {
  1896. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1897. }
  1898. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1899. texture.samplingMode = samplingMode;
  1900. this._loadedTexturesCache.push(texture);
  1901. return texture;
  1902. }
  1903. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1904. var texture = this._gl.createTexture();
  1905. texture._baseWidth = width;
  1906. texture._baseHeight = height;
  1907. if (generateMipMaps) {
  1908. width = Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1909. height = Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1910. }
  1911. this.resetTextureCache();
  1912. texture._width = width;
  1913. texture._height = height;
  1914. texture.isReady = false;
  1915. texture.generateMipMaps = generateMipMaps;
  1916. texture.references = 1;
  1917. texture.samplingMode = samplingMode;
  1918. this.updateTextureSamplingMode(samplingMode, texture);
  1919. this._loadedTexturesCache.push(texture);
  1920. return texture;
  1921. }
  1922. public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
  1923. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1924. if (texture.isCube) {
  1925. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  1926. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1927. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1928. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  1929. } else {
  1930. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1931. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1933. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1934. }
  1935. texture.samplingMode = samplingMode;
  1936. }
  1937. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  1938. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1939. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1940. if (premulAlpha) {
  1941. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  1942. }
  1943. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  1944. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  1945. if (texture.generateMipMaps) {
  1946. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1947. }
  1948. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1949. if (premulAlpha) {
  1950. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  1951. }
  1952. this.resetTextureCache();
  1953. texture.isReady = true;
  1954. }
  1955. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1956. if (texture._isDisabled) {
  1957. return;
  1958. }
  1959. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1960. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1961. try {
  1962. // Testing video texture support
  1963. if (this._videoTextureSupported === undefined) {
  1964. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1965. if (this._gl.getError() !== 0) {
  1966. this._videoTextureSupported = false;
  1967. } else {
  1968. this._videoTextureSupported = true;
  1969. }
  1970. }
  1971. // Copy video through the current working canvas if video texture is not supported
  1972. if (!this._videoTextureSupported) {
  1973. if (!texture._workingCanvas) {
  1974. texture._workingCanvas = document.createElement("canvas");
  1975. texture._workingContext = texture._workingCanvas.getContext("2d");
  1976. texture._workingCanvas.width = texture._width;
  1977. texture._workingCanvas.height = texture._height;
  1978. }
  1979. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1980. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1981. } else {
  1982. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1983. }
  1984. if (texture.generateMipMaps) {
  1985. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1986. }
  1987. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1988. this.resetTextureCache();
  1989. texture.isReady = true;
  1990. } catch (ex) {
  1991. // Something unexpected
  1992. // Let's disable the texture
  1993. texture._isDisabled = true;
  1994. }
  1995. }
  1996. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1997. // old version had a "generateMipMaps" arg instead of options.
  1998. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1999. // in the same way, generateDepthBuffer is defaulted to true
  2000. var generateMipMaps = false;
  2001. var generateDepthBuffer = true;
  2002. var generateStencilBuffer = false;
  2003. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2004. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2005. if (options !== undefined) {
  2006. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  2007. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2008. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2009. type = options.type === undefined ? type : options.type;
  2010. if (options.samplingMode !== undefined) {
  2011. samplingMode = options.samplingMode;
  2012. }
  2013. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2014. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2015. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2016. }
  2017. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2018. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2019. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2020. }
  2021. }
  2022. var gl = this._gl;
  2023. var texture = gl.createTexture();
  2024. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2025. var width = size.width || size;
  2026. var height = size.height || size;
  2027. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2028. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2029. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2030. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2031. }
  2032. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2033. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2034. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2035. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2036. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2037. // Create the framebuffer
  2038. var framebuffer = gl.createFramebuffer();
  2039. this.bindUnboundFramebuffer(framebuffer);
  2040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  2041. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2042. if (generateMipMaps) {
  2043. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2044. }
  2045. // Unbind
  2046. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2047. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2048. this.bindUnboundFramebuffer(null);
  2049. texture._framebuffer = framebuffer;
  2050. texture._baseWidth = width;
  2051. texture._baseHeight = height;
  2052. texture._width = width;
  2053. texture._height = height;
  2054. texture.isReady = true;
  2055. texture.samples = 1;
  2056. texture.generateMipMaps = generateMipMaps;
  2057. texture.references = 1;
  2058. texture.samplingMode = samplingMode;
  2059. texture.type = type;
  2060. texture._generateDepthBuffer = generateDepthBuffer;
  2061. texture._generateStencilBuffer = generateStencilBuffer;
  2062. this.resetTextureCache();
  2063. this._loadedTexturesCache.push(texture);
  2064. return texture;
  2065. }
  2066. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): WebGLRenderbuffer {
  2067. var depthStencilBuffer: WebGLRenderbuffer = null;
  2068. var gl = this._gl;
  2069. // Create the depth/stencil buffer
  2070. if (generateStencilBuffer) {
  2071. depthStencilBuffer = gl.createRenderbuffer();
  2072. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2073. if (samples > 1) {
  2074. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  2075. } else {
  2076. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  2077. }
  2078. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2079. }
  2080. else if (generateDepthBuffer) {
  2081. depthStencilBuffer = gl.createRenderbuffer();
  2082. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2083. if (samples > 1) {
  2084. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  2085. } else {
  2086. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  2087. }
  2088. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2089. }
  2090. return depthStencilBuffer;
  2091. }
  2092. public updateRenderTargetTextureSampleCount(texture: WebGLTexture, samples: number): number {
  2093. if (this.webGLVersion < 2) {
  2094. return 1;
  2095. }
  2096. if (texture.samples === samples) {
  2097. return samples;
  2098. }
  2099. var gl = this._gl;
  2100. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  2101. // Dispose previous render buffers
  2102. if (texture._depthStencilBuffer) {
  2103. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2104. }
  2105. if (texture._MSAAFramebuffer) {
  2106. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2107. }
  2108. if (texture._MSAARenderBuffer) {
  2109. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2110. }
  2111. if (samples > 1) {
  2112. texture._MSAAFramebuffer = gl.createFramebuffer();
  2113. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  2114. var colorRenderbuffer = gl.createRenderbuffer();
  2115. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  2116. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  2117. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  2118. texture._MSAARenderBuffer = colorRenderbuffer;
  2119. } else {
  2120. this.bindUnboundFramebuffer(texture._framebuffer);
  2121. }
  2122. texture.samples = samples;
  2123. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  2124. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2125. this.bindUnboundFramebuffer(null);
  2126. return samples;
  2127. }
  2128. public createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture {
  2129. var gl = this._gl;
  2130. var texture = gl.createTexture();
  2131. var generateMipMaps = true;
  2132. var generateDepthBuffer = true;
  2133. var generateStencilBuffer = false;
  2134. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2135. if (options !== undefined) {
  2136. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  2137. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2138. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2139. if (options.samplingMode !== undefined) {
  2140. samplingMode = options.samplingMode;
  2141. }
  2142. }
  2143. texture.isCube = true;
  2144. texture.references = 1;
  2145. texture.generateMipMaps = generateMipMaps;
  2146. texture.references = 1;
  2147. texture.samples = 1;
  2148. texture.samplingMode = samplingMode;
  2149. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2150. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2151. for (var face = 0; face < 6; face++) {
  2152. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  2153. }
  2154. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  2155. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  2156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2158. // Create the framebuffer
  2159. var framebuffer = gl.createFramebuffer();
  2160. this.bindUnboundFramebuffer(framebuffer);
  2161. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  2162. // Mipmaps
  2163. if (texture.generateMipMaps) {
  2164. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2165. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2166. }
  2167. // Unbind
  2168. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2169. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2170. this.bindUnboundFramebuffer(null);
  2171. texture._framebuffer = framebuffer;
  2172. texture._width = size;
  2173. texture._height = size;
  2174. texture.isReady = true;
  2175. this.resetTextureCache();
  2176. this._loadedTexturesCache.push(texture);
  2177. return texture;
  2178. }
  2179. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: () => void = null, onError: () => void = null, format?: number): WebGLTexture {
  2180. var gl = this._gl;
  2181. var texture = gl.createTexture();
  2182. texture.isCube = true;
  2183. texture.url = rootUrl;
  2184. texture.references = 1;
  2185. texture.onLoadedCallbacks = [];
  2186. var isKTX = false;
  2187. var lastDot = rootUrl.lastIndexOf('.');
  2188. var extension = rootUrl.substring(lastDot).toLowerCase();
  2189. if (this._textureFormatInUse) {
  2190. extension = this._textureFormatInUse;
  2191. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  2192. isKTX = true;
  2193. }
  2194. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  2195. if (isDDS) {
  2196. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  2197. }
  2198. if (isKTX) {
  2199. Tools.LoadFile(rootUrl, data => {
  2200. var ktx = new Internals.KhronosTextureContainer(data, 6);
  2201. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  2202. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2203. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2204. ktx.uploadLevels(this._gl, !noMipmap);
  2205. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2206. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2207. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2208. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2209. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2210. this.resetTextureCache();
  2211. texture._width = ktx.pixelWidth;
  2212. texture._height = ktx.pixelHeight;
  2213. texture.isReady = true;
  2214. }, null, null, true, onError);
  2215. } else if (isDDS) {
  2216. Tools.LoadFile(rootUrl, data => {
  2217. var info = Internals.DDSTools.GetDDSInfo(data);
  2218. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  2219. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2220. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2221. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  2222. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  2223. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2224. }
  2225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2229. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2230. this.resetTextureCache();
  2231. texture._width = info.width;
  2232. texture._height = info.height;
  2233. texture.isReady = true;
  2234. }, null, null, true, onError);
  2235. } else {
  2236. cascadeLoad(rootUrl, scene, imgs => {
  2237. var width = Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  2238. var height = width;
  2239. this._prepareWorkingCanvas();
  2240. this._workingCanvas.width = width;
  2241. this._workingCanvas.height = height;
  2242. var faces = [
  2243. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2244. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2245. ];
  2246. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2247. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2248. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2249. for (var index = 0; index < faces.length; index++) {
  2250. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  2251. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2252. }
  2253. if (!noMipmap) {
  2254. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2255. }
  2256. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2257. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2260. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2261. this.resetTextureCache();
  2262. texture._width = width;
  2263. texture._height = height;
  2264. texture.isReady = true;
  2265. texture.onLoadedCallbacks.forEach(callback => {
  2266. callback();
  2267. });
  2268. if (onLoad) {
  2269. onLoad();
  2270. }
  2271. }, files, onError);
  2272. }
  2273. this._loadedTexturesCache.push(texture);
  2274. return texture;
  2275. }
  2276. public updateTextureSize(texture: WebGLTexture, width: number, height: number) {
  2277. texture._width = width;
  2278. texture._height = height;
  2279. texture._size = width * height;
  2280. texture._baseWidth = width;
  2281. texture._baseHeight = height;
  2282. }
  2283. public createRawCubeTexture(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  2284. callback: (ArrayBuffer: ArrayBuffer) => ArrayBufferView[],
  2285. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][]), onLoad: () => void = null, onError: () => void = null): WebGLTexture {
  2286. var gl = this._gl;
  2287. var texture = gl.createTexture();
  2288. scene._addPendingData(texture);
  2289. texture.isCube = true;
  2290. texture.references = 1;
  2291. texture.url = url;
  2292. var textureType = gl.UNSIGNED_BYTE;
  2293. if (type === Engine.TEXTURETYPE_FLOAT) {
  2294. textureType = gl.FLOAT;
  2295. }
  2296. var internalFormat = this._getInternalFormat(format);
  2297. var needConversion = false;
  2298. if (internalFormat === gl.RGB) {
  2299. internalFormat = gl.RGBA;
  2300. needConversion = true;
  2301. }
  2302. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2303. var width = size;
  2304. var height = width;
  2305. var isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  2306. texture._width = width;
  2307. texture._height = height;
  2308. var onerror = () => {
  2309. scene._removePendingData(texture);
  2310. if (onError) {
  2311. onError();
  2312. }
  2313. };
  2314. var internalCallback = (data) => {
  2315. var rgbeDataArrays = callback(data);
  2316. var facesIndex = [
  2317. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2318. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2319. ];
  2320. width = texture._width;
  2321. height = texture._height;
  2322. isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  2323. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2324. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2325. if (mipmmapGenerator) {
  2326. var arrayTemp: ArrayBufferView[] = [];
  2327. // Data are known to be in +X +Y +Z -X -Y -Z
  2328. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  2329. arrayTemp.push(rgbeDataArrays[0]); // +X
  2330. arrayTemp.push(rgbeDataArrays[3]); // -X
  2331. arrayTemp.push(rgbeDataArrays[1]); // +Y
  2332. arrayTemp.push(rgbeDataArrays[4]); // -Y
  2333. arrayTemp.push(rgbeDataArrays[2]); // +Z
  2334. arrayTemp.push(rgbeDataArrays[5]); // -Z
  2335. var mipData = mipmmapGenerator(arrayTemp);
  2336. // mipData is order in +X -X +Y -Y +Z -Z
  2337. var mipFaces = [0, 2, 4, 1, 3, 5];
  2338. for (var level = 0; level < mipData.length; level++) {
  2339. var mipSize = width >> level;
  2340. for (let mipIndex in mipFaces) {
  2341. let mipFaceData = mipData[level][mipFaces[mipIndex]];
  2342. if (needConversion) {
  2343. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  2344. }
  2345. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  2346. }
  2347. }
  2348. }
  2349. else {
  2350. // Data are known to be in +X +Y +Z -X -Y -Z
  2351. for (let index = 0; index < facesIndex.length; index++) {
  2352. let faceData = rgbeDataArrays[index];
  2353. if (needConversion) {
  2354. faceData = this._convertRGBtoRGBATextureData(faceData, width, height, type);
  2355. }
  2356. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  2357. }
  2358. if (!noMipmap && isPot) {
  2359. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2360. }
  2361. else {
  2362. noMipmap = true;
  2363. }
  2364. }
  2365. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  2366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2368. }
  2369. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  2370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2372. }
  2373. else {
  2374. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2375. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2376. }
  2377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2378. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2379. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2380. texture.isReady = true;
  2381. this.resetTextureCache();
  2382. scene._removePendingData(texture);
  2383. if (onLoad) {
  2384. onLoad();
  2385. }
  2386. };
  2387. Tools.LoadFile(url, data => {
  2388. internalCallback(data);
  2389. }, onerror, scene.database, true);
  2390. return texture;
  2391. };
  2392. private _convertRGBtoRGBATextureData(rgbData: ArrayBufferView, width: number, height: number, textureType: number): ArrayBufferView {
  2393. // Create new RGBA data container.
  2394. var rgbaData: ArrayBufferView;
  2395. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  2396. rgbaData = new Float32Array(width * height * 4);
  2397. }
  2398. else {
  2399. rgbaData = new Uint32Array(width * height * 4);
  2400. }
  2401. // Convert each pixel.
  2402. for (let x = 0; x < width; x++) {
  2403. for (let y = 0; y < height; y++) {
  2404. let index = (y * width + x) * 3;
  2405. let newIndex = (y * width + x) * 4;
  2406. // Map Old Value to new value.
  2407. rgbaData[newIndex + 0] = rgbData[index + 0];
  2408. rgbaData[newIndex + 1] = rgbData[index + 1];
  2409. rgbaData[newIndex + 2] = rgbData[index + 2];
  2410. // Add fully opaque alpha channel.
  2411. rgbaData[newIndex + 3] = 1;
  2412. }
  2413. }
  2414. return rgbaData;
  2415. }
  2416. public _releaseTexture(texture: WebGLTexture): void {
  2417. var gl = this._gl;
  2418. if (texture._framebuffer) {
  2419. gl.deleteFramebuffer(texture._framebuffer);
  2420. }
  2421. if (texture._depthStencilBuffer) {
  2422. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2423. }
  2424. if (texture._MSAAFramebuffer) {
  2425. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2426. }
  2427. if (texture._MSAARenderBuffer) {
  2428. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2429. }
  2430. gl.deleteTexture(texture);
  2431. // Unbind channels
  2432. this.unbindAllTextures();
  2433. var index = this._loadedTexturesCache.indexOf(texture);
  2434. if (index !== -1) {
  2435. this._loadedTexturesCache.splice(index, 1);
  2436. }
  2437. }
  2438. private setProgram(program: WebGLProgram): void {
  2439. if (this._currentProgram !== program) {
  2440. this._gl.useProgram(program);
  2441. this._currentProgram = program;
  2442. }
  2443. }
  2444. public bindSamplers(effect: Effect): void {
  2445. this.setProgram(effect.getProgram());
  2446. var samplers = effect.getSamplers();
  2447. for (var index = 0; index < samplers.length; index++) {
  2448. var uniform = effect.getUniform(samplers[index]);
  2449. this._gl.uniform1i(uniform, index);
  2450. }
  2451. this._currentEffect = null;
  2452. }
  2453. private activateTexture(texture: number): void {
  2454. if (this._activeTexture !== texture) {
  2455. this._gl.activeTexture(texture);
  2456. this._activeTexture = texture;
  2457. }
  2458. }
  2459. public _bindTextureDirectly(target: number, texture: WebGLTexture): void {
  2460. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  2461. this._gl.bindTexture(target, texture);
  2462. this._activeTexturesCache[this._activeTexture] = texture;
  2463. }
  2464. }
  2465. public _bindTexture(channel: number, texture: WebGLTexture): void {
  2466. if (channel < 0) {
  2467. return;
  2468. }
  2469. this.activateTexture(this._gl.TEXTURE0 + channel);
  2470. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2471. }
  2472. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  2473. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  2474. }
  2475. public unbindAllTextures(): void {
  2476. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  2477. this.activateTexture(this._gl["TEXTURE" + channel]);
  2478. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2479. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2480. }
  2481. }
  2482. public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
  2483. if (channel < 0) {
  2484. return;
  2485. }
  2486. this._gl.uniform1i(uniform, channel);
  2487. this._setTexture(channel, texture);
  2488. }
  2489. private _setTexture(channel: number, texture: BaseTexture): void {
  2490. // Not ready?
  2491. if (!texture || !texture.isReady()) {
  2492. if (this._activeTexturesCache[channel] != null) {
  2493. this.activateTexture(this._gl["TEXTURE" + channel]);
  2494. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2495. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2496. }
  2497. return;
  2498. }
  2499. // Video
  2500. var alreadyActivated = false;
  2501. if (texture instanceof VideoTexture) {
  2502. this.activateTexture(this._gl["TEXTURE" + channel]);
  2503. alreadyActivated = true;
  2504. texture.update();
  2505. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  2506. texture.delayLoad();
  2507. return;
  2508. }
  2509. var internalTexture = texture.getInternalTexture();
  2510. if (this._activeTexturesCache[channel] === internalTexture) {
  2511. return;
  2512. }
  2513. if (!alreadyActivated) {
  2514. this.activateTexture(this._gl["TEXTURE" + channel]);
  2515. }
  2516. if (internalTexture.isCube) {
  2517. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  2518. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  2519. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  2520. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  2521. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  2522. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  2523. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  2524. }
  2525. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  2526. } else {
  2527. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  2528. if (internalTexture._cachedWrapU !== texture.wrapU) {
  2529. internalTexture._cachedWrapU = texture.wrapU;
  2530. switch (texture.wrapU) {
  2531. case Texture.WRAP_ADDRESSMODE:
  2532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  2533. break;
  2534. case Texture.CLAMP_ADDRESSMODE:
  2535. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  2536. break;
  2537. case Texture.MIRROR_ADDRESSMODE:
  2538. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  2539. break;
  2540. }
  2541. }
  2542. if (internalTexture._cachedWrapV !== texture.wrapV) {
  2543. internalTexture._cachedWrapV = texture.wrapV;
  2544. switch (texture.wrapV) {
  2545. case Texture.WRAP_ADDRESSMODE:
  2546. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  2547. break;
  2548. case Texture.CLAMP_ADDRESSMODE:
  2549. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  2550. break;
  2551. case Texture.MIRROR_ADDRESSMODE:
  2552. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  2553. break;
  2554. }
  2555. }
  2556. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  2557. }
  2558. }
  2559. public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
  2560. if (channel < 0) {
  2561. return;
  2562. }
  2563. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  2564. this._textureUnits = new Int32Array(textures.length);
  2565. }
  2566. for (let i = 0; i < textures.length; i++) {
  2567. this._textureUnits[i] = channel + i;
  2568. }
  2569. this._gl.uniform1iv(uniform, this._textureUnits);
  2570. for (var index = 0; index < textures.length; index++) {
  2571. this._setTexture(channel + index, textures[index]);
  2572. }
  2573. }
  2574. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  2575. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  2576. var value = texture.anisotropicFilteringLevel;
  2577. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  2578. value = 1;
  2579. }
  2580. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  2581. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  2582. texture._cachedAnisotropicFilteringLevel = value;
  2583. }
  2584. }
  2585. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  2586. var data = new Uint8Array(height * width * 4);
  2587. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  2588. return data;
  2589. }
  2590. /**
  2591. * Add an externaly attached data from its key.
  2592. * This method call will fail and return false, if such key already exists.
  2593. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2594. * @param key the unique key that identifies the data
  2595. * @param data the data object to associate to the key for this Engine instance
  2596. * @return true if no such key were already present and the data was added successfully, false otherwise
  2597. */
  2598. public addExternalData<T>(key: string, data: T): boolean {
  2599. return this._externalData.add(key, data);
  2600. }
  2601. /**
  2602. * Get an externaly attached data from its key
  2603. * @param key the unique key that identifies the data
  2604. * @return the associated data, if present (can be null), or undefined if not present
  2605. */
  2606. public getExternalData<T>(key: string): T {
  2607. return <T>this._externalData.get(key);
  2608. }
  2609. /**
  2610. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2611. * @param key the unique key that identifies the data
  2612. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2613. * @return the associated data, can be null if the factory returned null.
  2614. */
  2615. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2616. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2617. }
  2618. /**
  2619. * Remove an externaly attached data from the Engine instance
  2620. * @param key the unique key that identifies the data
  2621. * @return true if the data was successfully removed, false if it doesn't exist
  2622. */
  2623. public removeExternalData(key): boolean {
  2624. return this._externalData.remove(key);
  2625. }
  2626. public releaseInternalTexture(texture: WebGLTexture): void {
  2627. if (!texture) {
  2628. return;
  2629. }
  2630. texture.references--;
  2631. // Final reference ?
  2632. if (texture.references === 0) {
  2633. var texturesCache = this.getLoadedTexturesCache();
  2634. var index = texturesCache.indexOf(texture);
  2635. if (index > -1) {
  2636. texturesCache.splice(index, 1);
  2637. }
  2638. this._releaseTexture(texture);
  2639. }
  2640. }
  2641. public unbindAllAttributes() {
  2642. if (this._mustWipeVertexAttributes) {
  2643. this._mustWipeVertexAttributes = false;
  2644. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  2645. this._gl.disableVertexAttribArray(i);
  2646. this._vertexAttribArraysEnabled[i] = false;
  2647. this._currentBufferPointers[i] = null;
  2648. }
  2649. return;
  2650. }
  2651. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  2652. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  2653. continue;
  2654. }
  2655. this._gl.disableVertexAttribArray(i);
  2656. this._vertexAttribArraysEnabled[i] = false;
  2657. this._currentBufferPointers[i] = null;
  2658. }
  2659. }
  2660. // Dispose
  2661. public dispose(): void {
  2662. this.hideLoadingUI();
  2663. this.stopRenderLoop();
  2664. // Release scenes
  2665. while (this.scenes.length) {
  2666. this.scenes[0].dispose();
  2667. }
  2668. // Release audio engine
  2669. Engine.audioEngine.dispose();
  2670. // Release effects
  2671. for (var name in this._compiledEffects) {
  2672. this._gl.deleteProgram(this._compiledEffects[name]._program);
  2673. }
  2674. // Unbind
  2675. this.unbindAllAttributes();
  2676. this._gl = null;
  2677. //WebVR
  2678. this.disableVR();
  2679. // Events
  2680. window.removeEventListener("blur", this._onBlur);
  2681. window.removeEventListener("focus", this._onFocus);
  2682. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  2683. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  2684. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  2685. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  2686. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  2687. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  2688. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  2689. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  2690. // Remove from Instances
  2691. var index = Engine.Instances.indexOf(this);
  2692. if (index >= 0) {
  2693. Engine.Instances.splice(index, 1);
  2694. }
  2695. }
  2696. // Loading screen
  2697. public displayLoadingUI(): void {
  2698. this.loadingScreen.displayLoadingUI();
  2699. }
  2700. public hideLoadingUI(): void {
  2701. this.loadingScreen.hideLoadingUI();
  2702. }
  2703. public get loadingScreen(): ILoadingScreen {
  2704. if (!this._loadingScreen) this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  2705. return this._loadingScreen;
  2706. }
  2707. public set loadingScreen(loadingScreen: ILoadingScreen) {
  2708. this._loadingScreen = loadingScreen;
  2709. }
  2710. public set loadingUIText(text: string) {
  2711. this.loadingScreen.loadingUIText = text;
  2712. }
  2713. public set loadingUIBackgroundColor(color: string) {
  2714. this.loadingScreen.loadingUIBackgroundColor = color;
  2715. }
  2716. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  2717. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  2718. }
  2719. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  2720. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  2721. }
  2722. public getVertexShaderSource(program: WebGLProgram): string {
  2723. var shaders = this._gl.getAttachedShaders(program);
  2724. return this._gl.getShaderSource(shaders[0]);
  2725. }
  2726. public getFragmentShaderSource(program: WebGLProgram): string {
  2727. var shaders = this._gl.getAttachedShaders(program);
  2728. return this._gl.getShaderSource(shaders[1]);
  2729. }
  2730. // FPS
  2731. public getFps(): number {
  2732. return this.fps;
  2733. }
  2734. public getDeltaTime(): number {
  2735. return this.deltaTime;
  2736. }
  2737. private _measureFps(): void {
  2738. this.previousFramesDuration.push(Tools.Now);
  2739. var length = this.previousFramesDuration.length;
  2740. if (length >= 2) {
  2741. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  2742. }
  2743. if (length >= this.fpsRange) {
  2744. if (length > this.fpsRange) {
  2745. this.previousFramesDuration.splice(0, 1);
  2746. length = this.previousFramesDuration.length;
  2747. }
  2748. var sum = 0;
  2749. for (var id = 0; id < length - 1; id++) {
  2750. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  2751. }
  2752. this.fps = 1000.0 / (sum / (length - 1));
  2753. }
  2754. }
  2755. private _canRenderToFloatFramebuffer(): boolean {
  2756. if (this._webGLVersion > 1) {
  2757. return this._caps.colorBufferFloat;
  2758. }
  2759. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  2760. }
  2761. private _canRenderToHalfFloatFramebuffer(): boolean {
  2762. if (this._webGLVersion > 1) {
  2763. return this._caps.colorBufferFloat;
  2764. }
  2765. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  2766. }
  2767. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  2768. private _canRenderToFramebuffer(type: number): boolean {
  2769. let gl = this._gl;
  2770. //clear existing errors
  2771. while (gl.getError() !== gl.NO_ERROR) { }
  2772. let successful = true;
  2773. let texture = gl.createTexture();
  2774. gl.bindTexture(gl.TEXTURE_2D, texture);
  2775. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2776. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2778. let fb = gl.createFramebuffer();
  2779. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  2780. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  2781. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  2782. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  2783. successful = successful && (gl.getError() === gl.NO_ERROR);
  2784. //try render by clearing frame buffer's color buffer
  2785. if (successful) {
  2786. gl.clear(gl.COLOR_BUFFER_BIT);
  2787. successful = successful && (gl.getError() === gl.NO_ERROR);
  2788. }
  2789. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  2790. if (successful) {
  2791. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  2792. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2793. let readFormat = gl.RGBA;
  2794. let readType = gl.UNSIGNED_BYTE;
  2795. let buffer = new Uint8Array(4);
  2796. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  2797. successful = successful && (gl.getError() === gl.NO_ERROR);
  2798. }
  2799. //clean up
  2800. gl.deleteTexture(texture);
  2801. gl.deleteFramebuffer(fb);
  2802. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2803. //clear accumulated errors
  2804. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  2805. return successful;
  2806. }
  2807. private _getWebGLTextureType(type: number): number {
  2808. if (type === Engine.TEXTURETYPE_FLOAT) {
  2809. return this._gl.FLOAT;
  2810. }
  2811. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  2812. // Add Half Float Constant.
  2813. return Engine.HALF_FLOAT_OES;
  2814. }
  2815. return this._gl.UNSIGNED_BYTE;
  2816. };
  2817. private _getRGBABufferInternalSizedFormat(type: number): number {
  2818. if (this._webGLVersion === 1) {
  2819. return this._gl.RGBA;
  2820. }
  2821. if (type === Engine.TEXTURETYPE_FLOAT) {
  2822. return Engine.RGBA32F;
  2823. }
  2824. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  2825. return Engine.RGBA16F;
  2826. }
  2827. return this._gl.RGBA;
  2828. };
  2829. // Statics
  2830. public static isSupported(): boolean {
  2831. try {
  2832. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  2833. if (navigator.isCocoonJS) {
  2834. return true;
  2835. }
  2836. var tempcanvas = document.createElement("canvas");
  2837. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  2838. return gl != null && !!window.WebGLRenderingContext;
  2839. } catch (e) {
  2840. return false;
  2841. }
  2842. }
  2843. }
  2844. }