babylon.engine.ts 167 KB

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