babylon.engine.ts 168 KB

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