babylon.engine.ts 171 KB

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