babylon.engine.ts 133 KB

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