thinEngine.ts 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326
  1. import { EngineStore } from './engineStore';
  2. import { IInternalTextureLoader } from '../Materials/Textures/internalTextureLoader';
  3. import { Effect, EffectCreationOptions } from '../Materials/effect';
  4. import { _DevTools } from '../Misc/devTools';
  5. import { IShaderProcessor } from './Processors/iShaderProcessor';
  6. import { UniformBuffer } from '../Materials/uniformBuffer';
  7. import { Nullable, DataArray, IndicesArray } from '../types';
  8. import { EngineCapabilities } from './engineCapabilities';
  9. import { Observable } from '../Misc/observable';
  10. import { DepthCullingState } from '../States/depthCullingState';
  11. import { StencilState } from '../States/stencilState';
  12. import { AlphaState } from '../States/alphaCullingState';
  13. import { Constants } from './constants';
  14. import { InternalTexture, InternalTextureSource } from '../Materials/Textures/internalTexture';
  15. import { IViewportLike, IColor4Like } from '../Maths/math.like';
  16. import { DataBuffer } from '../Meshes/dataBuffer';
  17. import { IFileRequest } from '../Misc/fileRequest';
  18. import { Logger } from '../Misc/logger';
  19. import { DomManagement } from '../Misc/domManagement';
  20. import { WebGL2ShaderProcessor } from './WebGL/webGL2ShaderProcessors';
  21. import { WebGLDataBuffer } from '../Meshes/WebGL/webGLDataBuffer';
  22. import { IPipelineContext } from './IPipelineContext';
  23. import { WebGLPipelineContext } from './WebGL/webGLPipelineContext';
  24. import { VertexBuffer } from '../Meshes/buffer';
  25. import { InstancingAttributeInfo } from './instancingAttributeInfo';
  26. import { FileTools } from '../Misc/fileTools';
  27. import { DepthTextureCreationOptions } from './depthTextureCreationOptions';
  28. import { BaseTexture } from '../Materials/Textures/baseTexture';
  29. import { IOfflineProvider } from '../Offline/IOfflineProvider';
  30. import { IEffectFallbacks } from '../Materials/iEffectFallbacks';
  31. import { IWebRequest } from '../Misc/interfaces/iWebRequest';
  32. declare type Observer<T> = import("../Misc/observable").Observer<T>;
  33. declare type VideoTexture = import("../Materials/Textures/videoTexture").VideoTexture;
  34. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  35. /**
  36. * Defines the interface used by objects working like Scene
  37. * @hidden
  38. */
  39. interface ISceneLike {
  40. _addPendingData(data: any): void;
  41. _removePendingData(data: any): void;
  42. offlineProvider: IOfflineProvider;
  43. }
  44. /**
  45. * Keeps track of all the buffer info used in engine.
  46. */
  47. class BufferPointer {
  48. public active: boolean;
  49. public index: number;
  50. public size: number;
  51. public type: number;
  52. public normalized: boolean;
  53. public stride: number;
  54. public offset: number;
  55. public buffer: WebGLBuffer;
  56. }
  57. /** Interface defining initialization parameters for Engine class */
  58. export interface EngineOptions extends WebGLContextAttributes {
  59. /**
  60. * Defines if the engine should no exceed a specified device ratio
  61. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  62. */
  63. limitDeviceRatio?: number;
  64. /**
  65. * Defines if webvr should be enabled automatically
  66. * @see http://doc.babylonjs.com/how_to/webvr_camera
  67. */
  68. autoEnableWebVR?: boolean;
  69. /**
  70. * Defines if webgl2 should be turned off even if supported
  71. * @see http://doc.babylonjs.com/features/webgl2
  72. */
  73. disableWebGL2Support?: boolean;
  74. /**
  75. * Defines if webaudio should be initialized as well
  76. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  77. */
  78. audioEngine?: boolean;
  79. /**
  80. * Defines if animations should run using a deterministic lock step
  81. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  82. */
  83. deterministicLockstep?: boolean;
  84. /** Defines the maximum steps to use with deterministic lock step mode */
  85. lockstepMaxSteps?: number;
  86. /**
  87. * Defines that engine should ignore context lost events
  88. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  89. */
  90. doNotHandleContextLost?: boolean;
  91. /**
  92. * Defines that engine should ignore modifying touch action attribute and style
  93. * If not handle, you might need to set it up on your side for expected touch devices behavior.
  94. */
  95. doNotHandleTouchAction?: boolean;
  96. /**
  97. * Defines that engine should compile shaders with high precision floats (if supported). True by default
  98. */
  99. useHighPrecisionFloats?: boolean;
  100. }
  101. /**
  102. * The base engine class (root of all engines)
  103. */
  104. export class ThinEngine {
  105. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  106. public static ExceptionList = [
  107. { key: "Chrome\/63\.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  108. { key: "Firefox\/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  109. { key: "Firefox\/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  110. { key: "Chrome\/72.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  111. { key: "Chrome\/73.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  112. { key: "Chrome\/74.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  113. { key: "Mac OS.+Chrome\/71", capture: null, captureConstraint: null, targets: ["vao"] },
  114. { key: "Mac OS.+Chrome\/72", capture: null, captureConstraint: null, targets: ["vao"] }
  115. ];
  116. /** @hidden */
  117. public static _TextureLoaders: IInternalTextureLoader[] = [];
  118. /**
  119. * Returns the current npm package of the sdk
  120. */
  121. // Not mixed with Version for tooling purpose.
  122. public static get NpmPackage(): string {
  123. return "babylonjs@4.1.0-alpha.22";
  124. }
  125. /**
  126. * Returns the current version of the framework
  127. */
  128. public static get Version(): string {
  129. return "4.1.0-alpha.22";
  130. }
  131. /**
  132. * Returns a string describing the current engine
  133. */
  134. public get description(): string {
  135. let description = "WebGL" + this.webGLVersion;
  136. if (this._caps.parallelShaderCompile) {
  137. description += " - Parallel shader compilation";
  138. }
  139. return description;
  140. }
  141. // Updatable statics so stick with vars here
  142. /**
  143. * Gets or sets the epsilon value used by collision engine
  144. */
  145. public static CollisionsEpsilon = 0.001;
  146. /**
  147. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  148. */
  149. public static get ShadersRepository(): string {
  150. return Effect.ShadersRepository;
  151. }
  152. public static set ShadersRepository(value: string) {
  153. Effect.ShadersRepository = value;
  154. }
  155. // Public members
  156. /** @hidden */
  157. public _shaderProcessor: IShaderProcessor;
  158. /**
  159. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  160. */
  161. public forcePOTTextures = false;
  162. /**
  163. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  164. */
  165. public isFullscreen = false;
  166. /**
  167. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  168. */
  169. public cullBackFaces = true;
  170. /**
  171. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  172. */
  173. public renderEvenInBackground = true;
  174. /**
  175. * Gets or sets a boolean indicating that cache can be kept between frames
  176. */
  177. public preventCacheWipeBetweenFrames = false;
  178. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  179. public validateShaderPrograms = false;
  180. // Uniform buffers list
  181. /**
  182. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  183. */
  184. public disableUniformBuffers = false;
  185. /** @hidden */
  186. public _uniformBuffers = new Array<UniformBuffer>();
  187. /**
  188. * Gets a boolean indicating that the engine supports uniform buffers
  189. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  190. */
  191. public get supportsUniformBuffers(): boolean {
  192. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  193. }
  194. // Private Members
  195. /** @hidden */
  196. public _gl: WebGLRenderingContext;
  197. protected _renderingCanvas: Nullable<HTMLCanvasElement>;
  198. protected _windowIsBackground = false;
  199. protected _webGLVersion = 1.0;
  200. protected _highPrecisionShadersAllowed = true;
  201. /** @hidden */
  202. public get _shouldUseHighPrecisionShader(): boolean {
  203. return this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed;
  204. }
  205. /**
  206. * Gets a boolean indicating that only power of 2 textures are supported
  207. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  208. */
  209. public get needPOTTextures(): boolean {
  210. return this._webGLVersion < 2 || this.forcePOTTextures;
  211. }
  212. /** @hidden */
  213. public _badOS = false;
  214. /** @hidden */
  215. public _badDesktopOS = false;
  216. private _hardwareScalingLevel: number;
  217. /** @hidden */
  218. public _caps: EngineCapabilities;
  219. private _isStencilEnable: boolean;
  220. protected _colorWrite = true;
  221. private _glVersion: string;
  222. private _glRenderer: string;
  223. private _glVendor: string;
  224. /** @hidden */
  225. public _videoTextureSupported: boolean;
  226. protected _renderingQueueLaunched = false;
  227. protected _activeRenderLoops = new Array<() => void>();
  228. // Lost context
  229. /**
  230. * Observable signaled when a context lost event is raised
  231. */
  232. public onContextLostObservable = new Observable<ThinEngine>();
  233. /**
  234. * Observable signaled when a context restored event is raised
  235. */
  236. public onContextRestoredObservable = new Observable<ThinEngine>();
  237. private _onContextLost: (evt: Event) => void;
  238. private _onContextRestored: (evt: Event) => void;
  239. protected _contextWasLost = false;
  240. /** @hidden */
  241. public _doNotHandleContextLost = false;
  242. /**
  243. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  244. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  245. */
  246. public get doNotHandleContextLost(): boolean {
  247. return this._doNotHandleContextLost;
  248. }
  249. public set doNotHandleContextLost(value: boolean) {
  250. this._doNotHandleContextLost = value;
  251. }
  252. /**
  253. * Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported
  254. */
  255. public disableVertexArrayObjects = false;
  256. // States
  257. /** @hidden */
  258. protected _depthCullingState = new DepthCullingState();
  259. /** @hidden */
  260. protected _stencilState = new StencilState();
  261. /** @hidden */
  262. protected _alphaState = new AlphaState();
  263. // Cache
  264. /** @hidden */
  265. public _internalTexturesCache = new Array<InternalTexture>();
  266. /** @hidden */
  267. protected _activeChannel = 0;
  268. private _currentTextureChannel = -1;
  269. /** @hidden */
  270. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  271. /** @hidden */
  272. protected _currentEffect: Nullable<Effect>;
  273. /** @hidden */
  274. protected _currentProgram: Nullable<WebGLProgram>;
  275. private _compiledEffects: { [key: string]: Effect } = {};
  276. private _vertexAttribArraysEnabled: boolean[] = [];
  277. /** @hidden */
  278. protected _cachedViewport: Nullable<IViewportLike>;
  279. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  280. /** @hidden */
  281. protected _cachedVertexBuffers: any;
  282. /** @hidden */
  283. protected _cachedIndexBuffer: Nullable<DataBuffer>;
  284. /** @hidden */
  285. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  286. /** @hidden */
  287. public _currentRenderTarget: Nullable<InternalTexture>;
  288. private _uintIndicesCurrentlySet = false;
  289. protected _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  290. /** @hidden */
  291. protected _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
  292. private _currentBufferPointers = new Array<BufferPointer>();
  293. private _currentInstanceLocations = new Array<number>();
  294. private _currentInstanceBuffers = new Array<DataBuffer>();
  295. private _textureUnits: Int32Array;
  296. /** @hidden */
  297. public _workingCanvas: Nullable<HTMLCanvasElement>;
  298. /** @hidden */
  299. public _workingContext: Nullable<CanvasRenderingContext2D>;
  300. /** @hidden */
  301. public _bindedRenderFunction: any;
  302. private _vaoRecordInProgress = false;
  303. private _mustWipeVertexAttributes = false;
  304. private _emptyTexture: Nullable<InternalTexture>;
  305. private _emptyCubeTexture: Nullable<InternalTexture>;
  306. private _emptyTexture3D: Nullable<InternalTexture>;
  307. /** @hidden */
  308. public _frameHandler: number;
  309. private _nextFreeTextureSlots = new Array<number>();
  310. private _maxSimultaneousTextures = 0;
  311. private _activeRequests = new Array<IFileRequest>();
  312. // Hardware supported Compressed Textures
  313. protected _texturesSupported = new Array<string>();
  314. /** @hidden */
  315. public _textureFormatInUse: Nullable<string>;
  316. protected get _supportsHardwareTextureRescaling() {
  317. return false;
  318. }
  319. /**
  320. * Gets the list of texture formats supported
  321. */
  322. public get texturesSupported(): Array<string> {
  323. return this._texturesSupported;
  324. }
  325. /**
  326. * Gets the list of texture formats in use
  327. */
  328. public get textureFormatInUse(): Nullable<string> {
  329. return this._textureFormatInUse;
  330. }
  331. /**
  332. * Gets the current viewport
  333. */
  334. public get currentViewport(): Nullable<IViewportLike> {
  335. return this._cachedViewport;
  336. }
  337. /**
  338. * Gets the default empty texture
  339. */
  340. public get emptyTexture(): InternalTexture {
  341. if (!this._emptyTexture) {
  342. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  343. }
  344. return this._emptyTexture;
  345. }
  346. /**
  347. * Gets the default empty 3D texture
  348. */
  349. public get emptyTexture3D(): InternalTexture {
  350. if (!this._emptyTexture3D) {
  351. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  352. }
  353. return this._emptyTexture3D;
  354. }
  355. /**
  356. * Gets the default empty cube texture
  357. */
  358. public get emptyCubeTexture(): InternalTexture {
  359. if (!this._emptyCubeTexture) {
  360. var faceData = new Uint8Array(4);
  361. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  362. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Constants.TEXTUREFORMAT_RGBA, Constants.TEXTURETYPE_UNSIGNED_INT, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  363. }
  364. return this._emptyCubeTexture;
  365. }
  366. /**
  367. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  368. */
  369. public readonly premultipliedAlpha: boolean = true;
  370. /**
  371. * Creates a new engine
  372. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  373. * @param antialias defines enable antialiasing (default: false)
  374. * @param options defines further options to be sent to the getContext() function
  375. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  376. */
  377. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  378. let canvas: Nullable<HTMLCanvasElement> = null;
  379. if (!canvasOrContext) {
  380. return;
  381. }
  382. options = options || {};
  383. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  384. canvas = <HTMLCanvasElement>canvasOrContext;
  385. this._renderingCanvas = canvas;
  386. if (antialias != null) {
  387. options.antialias = antialias;
  388. }
  389. if (options.deterministicLockstep === undefined) {
  390. options.deterministicLockstep = false;
  391. }
  392. if (options.lockstepMaxSteps === undefined) {
  393. options.lockstepMaxSteps = 4;
  394. }
  395. if (options.preserveDrawingBuffer === undefined) {
  396. options.preserveDrawingBuffer = false;
  397. }
  398. if (options.audioEngine === undefined) {
  399. options.audioEngine = true;
  400. }
  401. if (options.stencil === undefined) {
  402. options.stencil = true;
  403. }
  404. if (options.premultipliedAlpha === false) {
  405. this.premultipliedAlpha = false;
  406. }
  407. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  408. // Exceptions
  409. if (navigator && navigator.userAgent) {
  410. let ua = navigator.userAgent;
  411. for (var exception of ThinEngine.ExceptionList) {
  412. let key = exception.key;
  413. let targets = exception.targets;
  414. let check = new RegExp(key);
  415. if (check.test(ua)) {
  416. if (exception.capture && exception.captureConstraint) {
  417. let capture = exception.capture;
  418. let constraint = exception.captureConstraint;
  419. let regex = new RegExp(capture);
  420. let matches = regex.exec(ua);
  421. if (matches && matches.length > 0) {
  422. let capturedValue = parseInt(matches[matches.length - 1]);
  423. if (capturedValue >= constraint) {
  424. continue;
  425. }
  426. }
  427. }
  428. for (var target of targets) {
  429. switch (target) {
  430. case "uniformBuffer":
  431. this.disableUniformBuffers = true;
  432. break;
  433. case "vao":
  434. this.disableVertexArrayObjects = true;
  435. break;
  436. }
  437. }
  438. }
  439. }
  440. }
  441. // Context lost
  442. if (!this._doNotHandleContextLost) {
  443. this._onContextLost = (evt: Event) => {
  444. evt.preventDefault();
  445. this._contextWasLost = true;
  446. Logger.Warn("WebGL context lost.");
  447. this.onContextLostObservable.notifyObservers(this);
  448. };
  449. this._onContextRestored = () => {
  450. // Adding a timeout to avoid race condition at browser level
  451. setTimeout(() => {
  452. // Rebuild gl context
  453. this._initGLContext();
  454. // Rebuild effects
  455. this._rebuildEffects();
  456. // Rebuild textures
  457. this._rebuildInternalTextures();
  458. // Rebuild buffers
  459. this._rebuildBuffers();
  460. // Cache
  461. this.wipeCaches(true);
  462. Logger.Warn("WebGL context successfully restored.");
  463. this.onContextRestoredObservable.notifyObservers(this);
  464. this._contextWasLost = false;
  465. }, 0);
  466. };
  467. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  468. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  469. options.powerPreference = "high-performance";
  470. }
  471. // GL
  472. if (!options.disableWebGL2Support) {
  473. try {
  474. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  475. if (this._gl) {
  476. this._webGLVersion = 2.0;
  477. // Prevent weird browsers to lie :-)
  478. if (!this._gl.deleteQuery) {
  479. this._webGLVersion = 1.0;
  480. }
  481. }
  482. } catch (e) {
  483. // Do nothing
  484. }
  485. }
  486. if (!this._gl) {
  487. if (!canvas) {
  488. throw new Error("The provided canvas is null or undefined.");
  489. }
  490. try {
  491. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  492. } catch (e) {
  493. throw new Error("WebGL not supported");
  494. }
  495. }
  496. if (!this._gl) {
  497. throw new Error("WebGL not supported");
  498. }
  499. } else {
  500. this._gl = <WebGLRenderingContext>canvasOrContext;
  501. this._renderingCanvas = this._gl.canvas as HTMLCanvasElement;
  502. if (this._gl.renderbufferStorageMultisample) {
  503. this._webGLVersion = 2.0;
  504. }
  505. const attributes = this._gl.getContextAttributes();
  506. if (attributes) {
  507. options.stencil = attributes.stencil;
  508. }
  509. }
  510. // Ensures a consistent color space unpacking of textures cross browser.
  511. this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
  512. if (options.useHighPrecisionFloats !== undefined) {
  513. this._highPrecisionShadersAllowed = options.useHighPrecisionFloats;
  514. }
  515. // Viewport
  516. const devicePixelRatio = DomManagement.IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0;
  517. var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
  518. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
  519. this.resize();
  520. this._isStencilEnable = options.stencil ? true : false;
  521. this._initGLContext();
  522. // Prepare buffer pointers
  523. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  524. this._currentBufferPointers[i] = new BufferPointer();
  525. }
  526. // Shader processor
  527. if (this.webGLVersion > 1) {
  528. this._shaderProcessor = new WebGL2ShaderProcessor();
  529. }
  530. // Detect if we are running on a faulty buggy OS.
  531. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  532. // Detect if we are running on a faulty buggy desktop OS.
  533. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  534. console.log(`Babylon.js v${ThinEngine.Version} - ${this.description}`);
  535. }
  536. private _rebuildInternalTextures(): void {
  537. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  538. for (var internalTexture of currentState) {
  539. internalTexture._rebuild();
  540. }
  541. }
  542. private _rebuildEffects(): void {
  543. for (var key in this._compiledEffects) {
  544. let effect = <Effect>this._compiledEffects[key];
  545. effect._prepareEffect();
  546. }
  547. Effect.ResetCache();
  548. }
  549. /**
  550. * Gets a boolean indicating if all created effects are ready
  551. * @returns true if all effects are ready
  552. */
  553. public areAllEffectsReady(): boolean {
  554. for (var key in this._compiledEffects) {
  555. let effect = <Effect>this._compiledEffects[key];
  556. if (!effect.isReady()) {
  557. return false;
  558. }
  559. }
  560. return true;
  561. }
  562. protected _rebuildBuffers(): void {
  563. // Uniforms
  564. for (var uniformBuffer of this._uniformBuffers) {
  565. uniformBuffer._rebuild();
  566. }
  567. }
  568. private _initGLContext(): void {
  569. // Caps
  570. this._caps = new EngineCapabilities();
  571. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  572. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  573. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  574. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  575. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  576. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  577. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  578. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  579. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  580. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  581. // Infos
  582. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  583. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  584. if (rendererInfo != null) {
  585. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  586. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  587. }
  588. if (!this._glVendor) {
  589. this._glVendor = "Unknown vendor";
  590. }
  591. if (!this._glRenderer) {
  592. this._glRenderer = "Unknown renderer";
  593. }
  594. // Constants
  595. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  596. if (this._gl.RGBA16F !== 0x881A) {
  597. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  598. }
  599. if (this._gl.RGBA32F !== 0x8814) {
  600. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  601. }
  602. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  603. this._gl.DEPTH24_STENCIL8 = 35056;
  604. }
  605. // Extensions
  606. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  607. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  608. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  609. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  610. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  611. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  612. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  613. 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');
  614. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  615. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  616. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  617. this._caps.highPrecisionShaderSupported = false;
  618. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  619. if (this._caps.timerQuery) {
  620. if (this._webGLVersion === 1) {
  621. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  622. }
  623. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  624. }
  625. // Checks if some of the format renders first to allow the use of webgl inspector.
  626. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  627. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  628. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  629. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  630. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  631. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  632. if (this._webGLVersion > 1) {
  633. this._gl.HALF_FLOAT_OES = 0x140B;
  634. }
  635. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  636. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  637. this._caps.multiview = this._gl.getExtension('OVR_multiview2');
  638. // Draw buffers
  639. if (this._webGLVersion > 1) {
  640. this._caps.drawBuffersExtension = true;
  641. this._caps.maxMSAASamples = this._gl.getParameter(this._gl.MAX_SAMPLES);
  642. } else {
  643. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  644. if (drawBuffersExtension !== null) {
  645. this._caps.drawBuffersExtension = true;
  646. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  647. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  648. for (var i = 0; i < 16; i++) {
  649. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  650. }
  651. } else {
  652. this._caps.drawBuffersExtension = false;
  653. }
  654. }
  655. // Shader compiler threads
  656. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  657. // Depth Texture
  658. if (this._webGLVersion > 1) {
  659. this._caps.depthTextureExtension = true;
  660. } else {
  661. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  662. if (depthTextureExtension != null) {
  663. this._caps.depthTextureExtension = true;
  664. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  665. }
  666. }
  667. // Vertex array object
  668. if (this.disableVertexArrayObjects) {
  669. this._caps.vertexArrayObject = false;
  670. } else if (this._webGLVersion > 1) {
  671. this._caps.vertexArrayObject = true;
  672. } else {
  673. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  674. if (vertexArrayObjectExtension != null) {
  675. this._caps.vertexArrayObject = true;
  676. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  677. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  678. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  679. } else {
  680. this._caps.vertexArrayObject = false;
  681. }
  682. }
  683. // Instances count
  684. if (this._webGLVersion > 1) {
  685. this._caps.instancedArrays = true;
  686. } else {
  687. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  688. if (instanceExtension != null) {
  689. this._caps.instancedArrays = true;
  690. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  691. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  692. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  693. } else {
  694. this._caps.instancedArrays = false;
  695. }
  696. }
  697. // Intelligently add supported compressed formats in order to check for.
  698. // Check for ASTC support first as it is most powerful and to be very cross platform.
  699. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  700. // Likely no hardware which supports both PVR & DXT, so order matters little.
  701. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  702. if (this._caps.astc) { this.texturesSupported.push('-astc.ktx'); }
  703. if (this._caps.s3tc) { this.texturesSupported.push('-dxt.ktx'); }
  704. if (this._caps.pvrtc) { this.texturesSupported.push('-pvrtc.ktx'); }
  705. if (this._caps.etc2) { this.texturesSupported.push('-etc2.ktx'); }
  706. if (this._caps.etc1) { this.texturesSupported.push('-etc1.ktx'); }
  707. if (this._gl.getShaderPrecisionFormat) {
  708. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  709. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  710. if (vertex_highp && fragment_highp) {
  711. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  712. }
  713. }
  714. if (this._webGLVersion > 1) {
  715. this._caps.blendMinMax = true;
  716. }
  717. else {
  718. const blendMinMaxExtension = this._gl.getExtension('EXT_blend_minmax');
  719. if (blendMinMaxExtension != null) {
  720. this._caps.blendMinMax = true;
  721. this._gl.MAX = blendMinMaxExtension.MAX_EXT;
  722. this._gl.MIN = blendMinMaxExtension.MIN_EXT;
  723. } else {
  724. this._caps.blendMinMax = false;
  725. }
  726. }
  727. // Depth buffer
  728. this._depthCullingState.depthTest = true;
  729. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  730. this._depthCullingState.depthMask = true;
  731. // Texture maps
  732. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  733. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  734. this._nextFreeTextureSlots.push(slot);
  735. }
  736. }
  737. /**
  738. * Gets version of the current webGL context
  739. */
  740. public get webGLVersion(): number {
  741. return this._webGLVersion;
  742. }
  743. /**
  744. * Gets a string idenfifying the name of the class
  745. * @returns "Engine" string
  746. */
  747. public getClassName(): string {
  748. return "ThinEngine";
  749. }
  750. /**
  751. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  752. */
  753. public get isStencilEnable(): boolean {
  754. return this._isStencilEnable;
  755. }
  756. /** @hidden */
  757. public _prepareWorkingCanvas(): void {
  758. if (this._workingCanvas) {
  759. return;
  760. }
  761. this._workingCanvas = document.createElement("canvas");
  762. let context = this._workingCanvas.getContext("2d");
  763. if (context) {
  764. this._workingContext = context;
  765. }
  766. }
  767. /**
  768. * Reset the texture cache to empty state
  769. */
  770. public resetTextureCache() {
  771. for (var key in this._boundTexturesCache) {
  772. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  773. continue;
  774. }
  775. this._boundTexturesCache[key] = null;
  776. }
  777. this._currentTextureChannel = -1;
  778. }
  779. /**
  780. * Gets an object containing information about the current webGL context
  781. * @returns an object containing the vender, the renderer and the version of the current webGL context
  782. */
  783. public getGlInfo() {
  784. return {
  785. vendor: this._glVendor,
  786. renderer: this._glRenderer,
  787. version: this._glVersion
  788. };
  789. }
  790. /**
  791. * Defines the hardware scaling level.
  792. * By default the hardware scaling level is computed from the window device ratio.
  793. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  794. * @param level defines the level to use
  795. */
  796. public setHardwareScalingLevel(level: number): void {
  797. this._hardwareScalingLevel = level;
  798. this.resize();
  799. }
  800. /**
  801. * Gets the current hardware scaling level.
  802. * By default the hardware scaling level is computed from the window device ratio.
  803. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  804. * @returns a number indicating the current hardware scaling level
  805. */
  806. public getHardwareScalingLevel(): number {
  807. return this._hardwareScalingLevel;
  808. }
  809. /**
  810. * Gets the list of loaded textures
  811. * @returns an array containing all loaded textures
  812. */
  813. public getLoadedTexturesCache(): InternalTexture[] {
  814. return this._internalTexturesCache;
  815. }
  816. /**
  817. * Gets the object containing all engine capabilities
  818. * @returns the EngineCapabilities object
  819. */
  820. public getCaps(): EngineCapabilities {
  821. return this._caps;
  822. }
  823. /**
  824. * stop executing a render loop function and remove it from the execution array
  825. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  826. */
  827. public stopRenderLoop(renderFunction?: () => void): void {
  828. if (!renderFunction) {
  829. this._activeRenderLoops = [];
  830. return;
  831. }
  832. var index = this._activeRenderLoops.indexOf(renderFunction);
  833. if (index >= 0) {
  834. this._activeRenderLoops.splice(index, 1);
  835. }
  836. }
  837. /** @hidden */
  838. public _renderLoop(): void {
  839. if (!this._contextWasLost) {
  840. var shouldRender = true;
  841. if (!this.renderEvenInBackground && this._windowIsBackground) {
  842. shouldRender = false;
  843. }
  844. if (shouldRender) {
  845. // Start new frame
  846. this.beginFrame();
  847. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  848. var renderFunction = this._activeRenderLoops[index];
  849. renderFunction();
  850. }
  851. // Present
  852. this.endFrame();
  853. }
  854. }
  855. if (this._activeRenderLoops.length > 0) {
  856. this._frameHandler = this._queueNewFrame(this._bindedRenderFunction, this.getHostWindow());
  857. } else {
  858. this._renderingQueueLaunched = false;
  859. }
  860. }
  861. /**
  862. * Gets the HTML canvas attached with the current webGL context
  863. * @returns a HTML canvas
  864. */
  865. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  866. return this._renderingCanvas;
  867. }
  868. /**
  869. * Gets host window
  870. * @returns the host window object
  871. */
  872. public getHostWindow(): Window {
  873. if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) {
  874. return this._renderingCanvas.ownerDocument.defaultView;
  875. }
  876. return window;
  877. }
  878. /**
  879. * Gets the current render width
  880. * @param useScreen defines if screen size must be used (or the current render target if any)
  881. * @returns a number defining the current render width
  882. */
  883. public getRenderWidth(useScreen = false): number {
  884. if (!useScreen && this._currentRenderTarget) {
  885. return this._currentRenderTarget.width;
  886. }
  887. return this._gl.drawingBufferWidth;
  888. }
  889. /**
  890. * Gets the current render height
  891. * @param useScreen defines if screen size must be used (or the current render target if any)
  892. * @returns a number defining the current render height
  893. */
  894. public getRenderHeight(useScreen = false): number {
  895. if (!useScreen && this._currentRenderTarget) {
  896. return this._currentRenderTarget.height;
  897. }
  898. return this._gl.drawingBufferHeight;
  899. }
  900. /**
  901. * Can be used to override the current requestAnimationFrame requester.
  902. * @hidden
  903. */
  904. protected _queueNewFrame(bindedRenderFunction: any, requester?: any): number {
  905. return ThinEngine.QueueNewFrame(bindedRenderFunction, requester);
  906. }
  907. /**
  908. * Register and execute a render loop. The engine can have more than one render function
  909. * @param renderFunction defines the function to continuously execute
  910. */
  911. public runRenderLoop(renderFunction: () => void): void {
  912. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  913. return;
  914. }
  915. this._activeRenderLoops.push(renderFunction);
  916. if (!this._renderingQueueLaunched) {
  917. this._renderingQueueLaunched = true;
  918. this._bindedRenderFunction = this._renderLoop.bind(this);
  919. this._frameHandler = this._queueNewFrame(this._bindedRenderFunction, this.getHostWindow());
  920. }
  921. }
  922. /**
  923. * Clear the current render buffer or the current render target (if any is set up)
  924. * @param color defines the color to use
  925. * @param backBuffer defines if the back buffer must be cleared
  926. * @param depth defines if the depth buffer must be cleared
  927. * @param stencil defines if the stencil buffer must be cleared
  928. */
  929. public clear(color: Nullable<IColor4Like>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  930. this.applyStates();
  931. var mode = 0;
  932. if (backBuffer && color) {
  933. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  934. mode |= this._gl.COLOR_BUFFER_BIT;
  935. }
  936. if (depth) {
  937. this._gl.clearDepth(1.0);
  938. mode |= this._gl.DEPTH_BUFFER_BIT;
  939. }
  940. if (stencil) {
  941. this._gl.clearStencil(0);
  942. mode |= this._gl.STENCIL_BUFFER_BIT;
  943. }
  944. this._gl.clear(mode);
  945. }
  946. private _viewportCached = { x: 0, y: 0, z: 0, w: 0 };
  947. /** @hidden */
  948. public _viewport(x: number, y: number, width: number, height: number): void {
  949. if (x !== this._viewportCached.x ||
  950. y !== this._viewportCached.y ||
  951. width !== this._viewportCached.z ||
  952. height !== this._viewportCached.w) {
  953. this._viewportCached.x = x;
  954. this._viewportCached.y = y;
  955. this._viewportCached.z = width;
  956. this._viewportCached.w = height;
  957. this._gl.viewport(x, y, width, height);
  958. }
  959. }
  960. /**
  961. * Set the WebGL's viewport
  962. * @param viewport defines the viewport element to be used
  963. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  964. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  965. */
  966. public setViewport(viewport: IViewportLike, requiredWidth?: number, requiredHeight?: number): void {
  967. var width = requiredWidth || this.getRenderWidth();
  968. var height = requiredHeight || this.getRenderHeight();
  969. var x = viewport.x || 0;
  970. var y = viewport.y || 0;
  971. this._cachedViewport = viewport;
  972. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  973. }
  974. /**
  975. * Begin a new frame
  976. */
  977. public beginFrame(): void {
  978. }
  979. /**
  980. * Enf the current frame
  981. */
  982. public endFrame(): void {
  983. // Force a flush in case we are using a bad OS.
  984. if (this._badOS) {
  985. this.flushFramebuffer();
  986. }
  987. }
  988. /**
  989. * Resize the view according to the canvas' size
  990. */
  991. public resize(): void {
  992. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  993. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  994. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  995. }
  996. /**
  997. * Force a specific size of the canvas
  998. * @param width defines the new canvas' width
  999. * @param height defines the new canvas' height
  1000. */
  1001. public setSize(width: number, height: number): void {
  1002. if (!this._renderingCanvas) {
  1003. return;
  1004. }
  1005. width = width | 0;
  1006. height = height | 0;
  1007. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1008. return;
  1009. }
  1010. this._renderingCanvas.width = width;
  1011. this._renderingCanvas.height = height;
  1012. }
  1013. /**
  1014. * Binds the frame buffer to the specified texture.
  1015. * @param texture The texture to render to or null for the default canvas
  1016. * @param faceIndex The face of the texture to render to in case of cube texture
  1017. * @param requiredWidth The width of the target to render to
  1018. * @param requiredHeight The height of the target to render to
  1019. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  1020. * @param depthStencilTexture The depth stencil texture to use to render
  1021. * @param lodLevel defines le lod level to bind to the frame buffer
  1022. */
  1023. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture, lodLevel = 0): void {
  1024. if (this._currentRenderTarget) {
  1025. this.unBindFramebuffer(this._currentRenderTarget);
  1026. }
  1027. this._currentRenderTarget = texture;
  1028. this._bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1029. var gl = this._gl;
  1030. if (texture.isCube) {
  1031. if (faceIndex === undefined) {
  1032. faceIndex = 0;
  1033. }
  1034. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  1035. if (depthStencilTexture) {
  1036. if (depthStencilTexture._generateStencilBuffer) {
  1037. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1038. }
  1039. else {
  1040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1041. }
  1042. }
  1043. }
  1044. if (this._cachedViewport && !forceFullscreenViewport) {
  1045. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1046. } else {
  1047. if (!requiredWidth) {
  1048. requiredWidth = texture.width;
  1049. if (lodLevel) {
  1050. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  1051. }
  1052. }
  1053. if (!requiredHeight) {
  1054. requiredHeight = texture.height;
  1055. if (lodLevel) {
  1056. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  1057. }
  1058. }
  1059. this._viewport(0, 0, requiredWidth, requiredHeight);
  1060. }
  1061. this.wipeCaches();
  1062. }
  1063. /** @hidden */
  1064. public _bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1065. if (this._currentFramebuffer !== framebuffer) {
  1066. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1067. this._currentFramebuffer = framebuffer;
  1068. }
  1069. }
  1070. /**
  1071. * Unbind the current render target texture from the webGL context
  1072. * @param texture defines the render target texture to unbind
  1073. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1074. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1075. */
  1076. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1077. this._currentRenderTarget = null;
  1078. // If MSAA, we need to bitblt back to main texture
  1079. var gl = this._gl;
  1080. if (texture._MSAAFramebuffer) {
  1081. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1082. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1083. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1084. 0, 0, texture.width, texture.height,
  1085. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1086. }
  1087. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1088. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1089. gl.generateMipmap(gl.TEXTURE_2D);
  1090. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1091. }
  1092. if (onBeforeUnbind) {
  1093. if (texture._MSAAFramebuffer) {
  1094. // Bind the correct framebuffer
  1095. this._bindUnboundFramebuffer(texture._framebuffer);
  1096. }
  1097. onBeforeUnbind();
  1098. }
  1099. this._bindUnboundFramebuffer(null);
  1100. }
  1101. /**
  1102. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  1103. */
  1104. public flushFramebuffer(): void {
  1105. this._gl.flush();
  1106. }
  1107. /**
  1108. * Unbind the current render target and bind the default framebuffer
  1109. */
  1110. public restoreDefaultFramebuffer(): void {
  1111. if (this._currentRenderTarget) {
  1112. this.unBindFramebuffer(this._currentRenderTarget);
  1113. } else {
  1114. this._bindUnboundFramebuffer(null);
  1115. }
  1116. if (this._cachedViewport) {
  1117. this.setViewport(this._cachedViewport);
  1118. }
  1119. this.wipeCaches();
  1120. }
  1121. // VBOs
  1122. private _resetVertexBufferBinding(): void {
  1123. this.bindArrayBuffer(null);
  1124. this._cachedVertexBuffers = null;
  1125. }
  1126. /**
  1127. * Creates a vertex buffer
  1128. * @param data the data for the vertex buffer
  1129. * @returns the new WebGL static buffer
  1130. */
  1131. public createVertexBuffer(data: DataArray): DataBuffer {
  1132. return this._createVertexBuffer(data, this._gl.STATIC_DRAW);
  1133. }
  1134. private _createVertexBuffer(data: DataArray, usage: number): DataBuffer {
  1135. var vbo = this._gl.createBuffer();
  1136. if (!vbo) {
  1137. throw new Error("Unable to create vertex buffer");
  1138. }
  1139. let dataBuffer = new WebGLDataBuffer(vbo);
  1140. this.bindArrayBuffer(dataBuffer);
  1141. if (data instanceof Array) {
  1142. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  1143. } else {
  1144. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  1145. }
  1146. this._resetVertexBufferBinding();
  1147. dataBuffer.references = 1;
  1148. return dataBuffer;
  1149. }
  1150. /**
  1151. * Creates a dynamic vertex buffer
  1152. * @param data the data for the dynamic vertex buffer
  1153. * @returns the new WebGL dynamic buffer
  1154. */
  1155. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  1156. return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW);
  1157. }
  1158. /**
  1159. * Updates a dynamic vertex buffer.
  1160. * @param vertexBuffer the vertex buffer to update
  1161. * @param data the data used to update the vertex buffer
  1162. * @param byteOffset the byte offset of the data
  1163. * @param byteLength the byte length of the data
  1164. */
  1165. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  1166. this.bindArrayBuffer(vertexBuffer);
  1167. if (byteOffset === undefined) {
  1168. byteOffset = 0;
  1169. }
  1170. if (byteLength === undefined) {
  1171. if (data instanceof Array) {
  1172. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  1173. } else {
  1174. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, <ArrayBuffer>data);
  1175. }
  1176. } else {
  1177. if (data instanceof Array) {
  1178. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  1179. } else {
  1180. if (data instanceof ArrayBuffer) {
  1181. data = new Uint8Array(data, byteOffset, byteLength);
  1182. } else {
  1183. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  1184. }
  1185. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <ArrayBuffer>data);
  1186. }
  1187. }
  1188. this._resetVertexBufferBinding();
  1189. }
  1190. protected _resetIndexBufferBinding(): void {
  1191. this.bindIndexBuffer(null);
  1192. this._cachedIndexBuffer = null;
  1193. }
  1194. /**
  1195. * Creates a new index buffer
  1196. * @param indices defines the content of the index buffer
  1197. * @param updatable defines if the index buffer must be updatable
  1198. * @returns a new webGL buffer
  1199. */
  1200. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): DataBuffer {
  1201. var vbo = this._gl.createBuffer();
  1202. let dataBuffer = new WebGLDataBuffer(vbo!);
  1203. if (!vbo) {
  1204. throw new Error("Unable to create index buffer");
  1205. }
  1206. this.bindIndexBuffer(dataBuffer);
  1207. const data = this._normalizeIndexData(indices);
  1208. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, data, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  1209. this._resetIndexBufferBinding();
  1210. dataBuffer.references = 1;
  1211. dataBuffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
  1212. return dataBuffer;
  1213. }
  1214. protected _normalizeIndexData(indices: IndicesArray): Uint16Array | Uint32Array
  1215. {
  1216. if (indices instanceof Uint16Array) {
  1217. return indices;
  1218. }
  1219. // Check 32 bit support
  1220. if (this._caps.uintIndices) {
  1221. if (indices instanceof Uint32Array) {
  1222. return indices;
  1223. } else {
  1224. // number[] or Int32Array, check if 32 bit is necessary
  1225. for (var index = 0; index < indices.length; index++) {
  1226. if (indices[index] >= 65535) {
  1227. return new Uint32Array(indices);
  1228. }
  1229. }
  1230. return new Uint16Array(indices);
  1231. }
  1232. }
  1233. // No 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1234. return new Uint16Array(indices);
  1235. }
  1236. /**
  1237. * Bind a webGL buffer to the webGL context
  1238. * @param buffer defines the buffer to bind
  1239. */
  1240. public bindArrayBuffer(buffer: Nullable<DataBuffer>): void {
  1241. if (!this._vaoRecordInProgress) {
  1242. this._unbindVertexArrayObject();
  1243. }
  1244. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1245. }
  1246. /**
  1247. * Bind a specific block at a given index in a specific shader program
  1248. * @param pipelineContext defines the pipeline context to use
  1249. * @param blockName defines the block name
  1250. * @param index defines the index where to bind the block
  1251. */
  1252. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  1253. let program = (pipelineContext as WebGLPipelineContext).program!;
  1254. var uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
  1255. this._gl.uniformBlockBinding(program, uniformLocation, index);
  1256. }
  1257. protected bindIndexBuffer(buffer: Nullable<DataBuffer>): void {
  1258. if (!this._vaoRecordInProgress) {
  1259. this._unbindVertexArrayObject();
  1260. }
  1261. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1262. }
  1263. private bindBuffer(buffer: Nullable<DataBuffer>, target: number): void {
  1264. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1265. this._gl.bindBuffer(target, buffer ? buffer.underlyingResource : null);
  1266. this._currentBoundBuffer[target] = buffer;
  1267. }
  1268. }
  1269. /**
  1270. * update the bound buffer with the given data
  1271. * @param data defines the data to update
  1272. */
  1273. public updateArrayBuffer(data: Float32Array): void {
  1274. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1275. }
  1276. private _vertexAttribPointer(buffer: DataBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1277. var pointer = this._currentBufferPointers[indx];
  1278. var changed = false;
  1279. if (!pointer.active) {
  1280. changed = true;
  1281. pointer.active = true;
  1282. pointer.index = indx;
  1283. pointer.size = size;
  1284. pointer.type = type;
  1285. pointer.normalized = normalized;
  1286. pointer.stride = stride;
  1287. pointer.offset = offset;
  1288. pointer.buffer = buffer;
  1289. } else {
  1290. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1291. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1292. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1293. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1294. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1295. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1296. }
  1297. if (changed || this._vaoRecordInProgress) {
  1298. this.bindArrayBuffer(buffer);
  1299. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1300. }
  1301. }
  1302. private _bindIndexBufferWithCache(indexBuffer: Nullable<DataBuffer>): void {
  1303. if (indexBuffer == null) {
  1304. return;
  1305. }
  1306. if (this._cachedIndexBuffer !== indexBuffer) {
  1307. this._cachedIndexBuffer = indexBuffer;
  1308. this.bindIndexBuffer(indexBuffer);
  1309. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1310. }
  1311. }
  1312. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  1313. var attributes = effect.getAttributesNames();
  1314. if (!this._vaoRecordInProgress) {
  1315. this._unbindVertexArrayObject();
  1316. }
  1317. this.unbindAllAttributes();
  1318. for (var index = 0; index < attributes.length; index++) {
  1319. var order = effect.getAttributeLocation(index);
  1320. if (order >= 0) {
  1321. var vertexBuffer = vertexBuffers[attributes[index]];
  1322. if (!vertexBuffer) {
  1323. continue;
  1324. }
  1325. this._gl.enableVertexAttribArray(order);
  1326. if (!this._vaoRecordInProgress) {
  1327. this._vertexAttribArraysEnabled[order] = true;
  1328. }
  1329. var buffer = vertexBuffer.getBuffer();
  1330. if (buffer) {
  1331. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  1332. if (vertexBuffer.getIsInstanced()) {
  1333. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1334. if (!this._vaoRecordInProgress) {
  1335. this._currentInstanceLocations.push(order);
  1336. this._currentInstanceBuffers.push(buffer);
  1337. }
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. /**
  1344. * Records a vertex array object
  1345. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  1346. * @param vertexBuffers defines the list of vertex buffers to store
  1347. * @param indexBuffer defines the index buffer to store
  1348. * @param effect defines the effect to store
  1349. * @returns the new vertex array object
  1350. */
  1351. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<DataBuffer>, effect: Effect): WebGLVertexArrayObject {
  1352. var vao = this._gl.createVertexArray();
  1353. this._vaoRecordInProgress = true;
  1354. this._gl.bindVertexArray(vao);
  1355. this._mustWipeVertexAttributes = true;
  1356. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1357. this.bindIndexBuffer(indexBuffer);
  1358. this._vaoRecordInProgress = false;
  1359. this._gl.bindVertexArray(null);
  1360. return vao;
  1361. }
  1362. /**
  1363. * Bind a specific vertex array object
  1364. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  1365. * @param vertexArrayObject defines the vertex array object to bind
  1366. * @param indexBuffer defines the index buffer to bind
  1367. */
  1368. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<DataBuffer>): void {
  1369. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1370. this._cachedVertexArrayObject = vertexArrayObject;
  1371. this._gl.bindVertexArray(vertexArrayObject);
  1372. this._cachedVertexBuffers = null;
  1373. this._cachedIndexBuffer = null;
  1374. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1375. this._mustWipeVertexAttributes = true;
  1376. }
  1377. }
  1378. /**
  1379. * Bind webGl buffers directly to the webGL context
  1380. * @param vertexBuffer defines the vertex buffer to bind
  1381. * @param indexBuffer defines the index buffer to bind
  1382. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  1383. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  1384. * @param effect defines the effect associated with the vertex buffer
  1385. */
  1386. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1387. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1388. this._cachedVertexBuffers = vertexBuffer;
  1389. this._cachedEffectForVertexBuffers = effect;
  1390. let attributesCount = effect.getAttributesCount();
  1391. this._unbindVertexArrayObject();
  1392. this.unbindAllAttributes();
  1393. var offset = 0;
  1394. for (var index = 0; index < attributesCount; index++) {
  1395. if (index < vertexDeclaration.length) {
  1396. var order = effect.getAttributeLocation(index);
  1397. if (order >= 0) {
  1398. this._gl.enableVertexAttribArray(order);
  1399. this._vertexAttribArraysEnabled[order] = true;
  1400. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1401. }
  1402. offset += vertexDeclaration[index] * 4;
  1403. }
  1404. }
  1405. }
  1406. this._bindIndexBufferWithCache(indexBuffer);
  1407. }
  1408. private _unbindVertexArrayObject(): void {
  1409. if (!this._cachedVertexArrayObject) {
  1410. return;
  1411. }
  1412. this._cachedVertexArrayObject = null;
  1413. this._gl.bindVertexArray(null);
  1414. }
  1415. /**
  1416. * Bind a list of vertex buffers to the webGL context
  1417. * @param vertexBuffers defines the list of vertex buffers to bind
  1418. * @param indexBuffer defines the index buffer to bind
  1419. * @param effect defines the effect associated with the vertex buffers
  1420. */
  1421. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect): void {
  1422. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1423. this._cachedVertexBuffers = vertexBuffers;
  1424. this._cachedEffectForVertexBuffers = effect;
  1425. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1426. }
  1427. this._bindIndexBufferWithCache(indexBuffer);
  1428. }
  1429. /**
  1430. * Unbind all instance attributes
  1431. */
  1432. public unbindInstanceAttributes() {
  1433. var boundBuffer;
  1434. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1435. var instancesBuffer = this._currentInstanceBuffers[i];
  1436. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1437. boundBuffer = instancesBuffer;
  1438. this.bindArrayBuffer(instancesBuffer);
  1439. }
  1440. var offsetLocation = this._currentInstanceLocations[i];
  1441. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1442. }
  1443. this._currentInstanceBuffers.length = 0;
  1444. this._currentInstanceLocations.length = 0;
  1445. }
  1446. /**
  1447. * Release and free the memory of a vertex array object
  1448. * @param vao defines the vertex array object to delete
  1449. */
  1450. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1451. this._gl.deleteVertexArray(vao);
  1452. }
  1453. /** @hidden */
  1454. public _releaseBuffer(buffer: DataBuffer): boolean {
  1455. buffer.references--;
  1456. if (buffer.references === 0) {
  1457. this._deleteBuffer(buffer);
  1458. return true;
  1459. }
  1460. return false;
  1461. }
  1462. protected _deleteBuffer(buffer: DataBuffer): void {
  1463. this._gl.deleteBuffer(buffer.underlyingResource);
  1464. }
  1465. /**
  1466. * Creates a webGL buffer to use with instanciation
  1467. * @param capacity defines the size of the buffer
  1468. * @returns the webGL buffer
  1469. */
  1470. public createInstancesBuffer(capacity: number): DataBuffer {
  1471. var buffer = this._gl.createBuffer();
  1472. if (!buffer) {
  1473. throw new Error("Unable to create instance buffer");
  1474. }
  1475. var result = new WebGLDataBuffer(buffer);
  1476. result.capacity = capacity;
  1477. this.bindArrayBuffer(result);
  1478. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1479. return result;
  1480. }
  1481. /**
  1482. * Delete a webGL buffer used with instanciation
  1483. * @param buffer defines the webGL buffer to delete
  1484. */
  1485. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1486. this._gl.deleteBuffer(buffer);
  1487. }
  1488. /**
  1489. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  1490. * @param instancesBuffer defines the webGL buffer to update and bind
  1491. * @param data defines the data to store in the buffer
  1492. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  1493. */
  1494. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1495. this.bindArrayBuffer(instancesBuffer);
  1496. if (data) {
  1497. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1498. }
  1499. if ((<any>offsetLocations[0]).index !== undefined) {
  1500. let stride = 0;
  1501. for (let i = 0; i < offsetLocations.length; i++) {
  1502. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1503. stride += ai.attributeSize * 4;
  1504. }
  1505. for (let i = 0; i < offsetLocations.length; i++) {
  1506. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1507. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1508. this._gl.enableVertexAttribArray(ai.index);
  1509. this._vertexAttribArraysEnabled[ai.index] = true;
  1510. }
  1511. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1512. this._gl.vertexAttribDivisor(ai.index, 1);
  1513. this._currentInstanceLocations.push(ai.index);
  1514. this._currentInstanceBuffers.push(instancesBuffer);
  1515. }
  1516. } else {
  1517. for (let index = 0; index < 4; index++) {
  1518. let offsetLocation = <number>offsetLocations[index];
  1519. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1520. this._gl.enableVertexAttribArray(offsetLocation);
  1521. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1522. }
  1523. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1524. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1525. this._currentInstanceLocations.push(offsetLocation);
  1526. this._currentInstanceBuffers.push(instancesBuffer);
  1527. }
  1528. }
  1529. }
  1530. /**
  1531. * Apply all cached states (depth, culling, stencil and alpha)
  1532. */
  1533. public applyStates() {
  1534. this._depthCullingState.apply(this._gl);
  1535. this._stencilState.apply(this._gl);
  1536. this._alphaState.apply(this._gl);
  1537. }
  1538. /**
  1539. * Send a draw order
  1540. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  1541. * @param indexStart defines the starting index
  1542. * @param indexCount defines the number of index to draw
  1543. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1544. */
  1545. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1546. this.drawElementsType(useTriangles ? Constants.MATERIAL_TriangleFillMode : Constants.MATERIAL_WireFrameFillMode, indexStart, indexCount, instancesCount);
  1547. }
  1548. /**
  1549. * Draw a list of points
  1550. * @param verticesStart defines the index of first vertex to draw
  1551. * @param verticesCount defines the count of vertices to draw
  1552. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1553. */
  1554. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1555. this.drawArraysType(Constants.MATERIAL_PointFillMode, verticesStart, verticesCount, instancesCount);
  1556. }
  1557. /**
  1558. * Draw a list of unindexed primitives
  1559. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  1560. * @param verticesStart defines the index of first vertex to draw
  1561. * @param verticesCount defines the count of vertices to draw
  1562. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1563. */
  1564. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1565. this.drawArraysType(useTriangles ? Constants.MATERIAL_TriangleFillMode : Constants.MATERIAL_WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  1566. }
  1567. /**
  1568. * Draw a list of indexed primitives
  1569. * @param fillMode defines the primitive to use
  1570. * @param indexStart defines the starting index
  1571. * @param indexCount defines the number of index to draw
  1572. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1573. */
  1574. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  1575. // Apply states
  1576. this.applyStates();
  1577. this._reportDrawCall();
  1578. // Render
  1579. const drawMode = this._drawMode(fillMode);
  1580. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1581. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1582. if (instancesCount) {
  1583. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  1584. } else {
  1585. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  1586. }
  1587. }
  1588. /**
  1589. * Draw a list of unindexed primitives
  1590. * @param fillMode defines the primitive to use
  1591. * @param verticesStart defines the index of first vertex to draw
  1592. * @param verticesCount defines the count of vertices to draw
  1593. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1594. */
  1595. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1596. // Apply states
  1597. this.applyStates();
  1598. this._reportDrawCall();
  1599. const drawMode = this._drawMode(fillMode);
  1600. if (instancesCount) {
  1601. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  1602. } else {
  1603. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  1604. }
  1605. }
  1606. private _drawMode(fillMode: number): number {
  1607. switch (fillMode) {
  1608. // Triangle views
  1609. case Constants.MATERIAL_TriangleFillMode:
  1610. return this._gl.TRIANGLES;
  1611. case Constants.MATERIAL_PointFillMode:
  1612. return this._gl.POINTS;
  1613. case Constants.MATERIAL_WireFrameFillMode:
  1614. return this._gl.LINES;
  1615. // Draw modes
  1616. case Constants.MATERIAL_PointListDrawMode:
  1617. return this._gl.POINTS;
  1618. case Constants.MATERIAL_LineListDrawMode:
  1619. return this._gl.LINES;
  1620. case Constants.MATERIAL_LineLoopDrawMode:
  1621. return this._gl.LINE_LOOP;
  1622. case Constants.MATERIAL_LineStripDrawMode:
  1623. return this._gl.LINE_STRIP;
  1624. case Constants.MATERIAL_TriangleStripDrawMode:
  1625. return this._gl.TRIANGLE_STRIP;
  1626. case Constants.MATERIAL_TriangleFanDrawMode:
  1627. return this._gl.TRIANGLE_FAN;
  1628. default:
  1629. return this._gl.TRIANGLES;
  1630. }
  1631. }
  1632. /** @hidden */
  1633. protected _reportDrawCall() {
  1634. // Will be implemented by children
  1635. }
  1636. // Shaders
  1637. /** @hidden */
  1638. public _releaseEffect(effect: Effect): void {
  1639. if (this._compiledEffects[effect._key]) {
  1640. delete this._compiledEffects[effect._key];
  1641. this._deletePipelineContext(effect.getPipelineContext() as WebGLPipelineContext);
  1642. }
  1643. }
  1644. /** @hidden */
  1645. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  1646. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1647. if (webGLPipelineContext && webGLPipelineContext.program) {
  1648. webGLPipelineContext.program.__SPECTOR_rebuildProgram = null;
  1649. this._gl.deleteProgram(webGLPipelineContext.program);
  1650. }
  1651. }
  1652. /**
  1653. * Create a new effect (used to store vertex/fragment shaders)
  1654. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  1655. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  1656. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  1657. * @param samplers defines an array of string used to represent textures
  1658. * @param defines defines the string containing the defines to use to compile the shaders
  1659. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  1660. * @param onCompiled defines a function to call when the effect creation is successful
  1661. * @param onError defines a function to call when the effect creation has failed
  1662. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  1663. * @returns the new Effect
  1664. */
  1665. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | ThinEngine, samplers?: string[], defines?: string,
  1666. fallbacks?: IEffectFallbacks,
  1667. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  1668. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1669. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1670. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  1671. if (this._compiledEffects[name]) {
  1672. var compiledEffect = <Effect>this._compiledEffects[name];
  1673. if (onCompiled && compiledEffect.isReady()) {
  1674. onCompiled(compiledEffect);
  1675. }
  1676. return compiledEffect;
  1677. }
  1678. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1679. effect._key = name;
  1680. this._compiledEffects[name] = effect;
  1681. return effect;
  1682. }
  1683. protected static _ConcatenateShader(source: string, defines: Nullable<string>, shaderVersion: string = ""): string {
  1684. return shaderVersion + (defines ? defines + "\n" : "") + source;
  1685. }
  1686. private _compileShader(source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader {
  1687. return this._compileRawShader(ThinEngine._ConcatenateShader(source, defines, shaderVersion), type);
  1688. }
  1689. private _compileRawShader(source: string, type: string): WebGLShader {
  1690. var gl = this._gl;
  1691. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  1692. if (!shader) {
  1693. throw new Error("Something went wrong while compile the shader.");
  1694. }
  1695. gl.shaderSource(shader, source);
  1696. gl.compileShader(shader);
  1697. return shader;
  1698. }
  1699. /**
  1700. * Directly creates a webGL program
  1701. * @param pipelineContext defines the pipeline context to attach to
  1702. * @param vertexCode defines the vertex shader code to use
  1703. * @param fragmentCode defines the fragment shader code to use
  1704. * @param context defines the webGL context to use (if not set, the current one will be used)
  1705. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  1706. * @returns the new webGL program
  1707. */
  1708. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1709. context = context || this._gl;
  1710. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  1711. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  1712. return this._createShaderProgram(pipelineContext as WebGLPipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
  1713. }
  1714. /**
  1715. * Creates a webGL program
  1716. * @param pipelineContext defines the pipeline context to attach to
  1717. * @param vertexCode defines the vertex shader code to use
  1718. * @param fragmentCode defines the fragment shader code to use
  1719. * @param defines defines the string containing the defines to use to compile the shaders
  1720. * @param context defines the webGL context to use (if not set, the current one will be used)
  1721. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  1722. * @returns the new webGL program
  1723. */
  1724. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1725. context = context || this._gl;
  1726. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  1727. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  1728. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  1729. return this._createShaderProgram(pipelineContext as WebGLPipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
  1730. }
  1731. /**
  1732. * Creates a new pipeline context
  1733. * @returns the new pipeline
  1734. */
  1735. public createPipelineContext(): IPipelineContext {
  1736. var pipelineContext = new WebGLPipelineContext();
  1737. pipelineContext.engine = this;
  1738. if (this._caps.parallelShaderCompile) {
  1739. pipelineContext.isParallelCompiled = true;
  1740. }
  1741. return pipelineContext;
  1742. }
  1743. protected _createShaderProgram(pipelineContext: WebGLPipelineContext, vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1744. var shaderProgram = context.createProgram();
  1745. pipelineContext.program = shaderProgram;
  1746. if (!shaderProgram) {
  1747. throw new Error("Unable to create program");
  1748. }
  1749. context.attachShader(shaderProgram, vertexShader);
  1750. context.attachShader(shaderProgram, fragmentShader);
  1751. context.linkProgram(shaderProgram);
  1752. pipelineContext.context = context;
  1753. pipelineContext.vertexShader = vertexShader;
  1754. pipelineContext.fragmentShader = fragmentShader;
  1755. if (!pipelineContext.isParallelCompiled) {
  1756. this._finalizePipelineContext(pipelineContext);
  1757. }
  1758. return shaderProgram;
  1759. }
  1760. protected _finalizePipelineContext(pipelineContext: WebGLPipelineContext) {
  1761. const context = pipelineContext.context!;
  1762. const vertexShader = pipelineContext.vertexShader!;
  1763. const fragmentShader = pipelineContext.fragmentShader!;
  1764. const program = pipelineContext.program!;
  1765. var linked = context.getProgramParameter(program, context.LINK_STATUS);
  1766. if (!linked) { // Get more info
  1767. // Vertex
  1768. if (!this._gl.getShaderParameter(vertexShader, this._gl.COMPILE_STATUS)) {
  1769. let log = this._gl.getShaderInfoLog(vertexShader);
  1770. if (log) {
  1771. throw new Error("VERTEX SHADER " + log);
  1772. }
  1773. }
  1774. // Fragment
  1775. if (!this._gl.getShaderParameter(fragmentShader, this._gl.COMPILE_STATUS)) {
  1776. let log = this._gl.getShaderInfoLog(fragmentShader);
  1777. if (log) {
  1778. throw new Error("FRAGMENT SHADER " + log);
  1779. }
  1780. }
  1781. var error = context.getProgramInfoLog(program);
  1782. if (error) {
  1783. throw new Error(error);
  1784. }
  1785. }
  1786. if (this.validateShaderPrograms) {
  1787. context.validateProgram(program);
  1788. var validated = context.getProgramParameter(program, context.VALIDATE_STATUS);
  1789. if (!validated) {
  1790. var error = context.getProgramInfoLog(program);
  1791. if (error) {
  1792. throw new Error(error);
  1793. }
  1794. }
  1795. }
  1796. context.deleteShader(vertexShader);
  1797. context.deleteShader(fragmentShader);
  1798. pipelineContext.vertexShader = undefined;
  1799. pipelineContext.fragmentShader = undefined;
  1800. if (pipelineContext.onCompiled) {
  1801. pipelineContext.onCompiled();
  1802. pipelineContext.onCompiled = undefined;
  1803. }
  1804. }
  1805. /** @hidden */
  1806. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean,
  1807. rebuildRebind: any,
  1808. defines: Nullable<string>,
  1809. transformFeedbackVaryings: Nullable<string[]>) {
  1810. let webGLRenderingState = pipelineContext as WebGLPipelineContext;
  1811. if (createAsRaw) {
  1812. webGLRenderingState.program = this.createRawShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
  1813. }
  1814. else {
  1815. webGLRenderingState.program = this.createShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
  1816. }
  1817. webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind;
  1818. }
  1819. /** @hidden */
  1820. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  1821. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1822. if (this._gl.getProgramParameter(webGLPipelineContext.program!, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  1823. this._finalizePipelineContext(webGLPipelineContext);
  1824. return true;
  1825. }
  1826. return false;
  1827. }
  1828. /** @hidden */
  1829. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  1830. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1831. if (!webGLPipelineContext.isParallelCompiled) {
  1832. action();
  1833. return;
  1834. }
  1835. webGLPipelineContext.onCompiled = action;
  1836. }
  1837. /**
  1838. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  1839. * @param pipelineContext defines the pipeline context to use
  1840. * @param uniformsNames defines the list of uniform names
  1841. * @returns an array of webGL uniform locations
  1842. */
  1843. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  1844. var results = new Array<Nullable<WebGLUniformLocation>>();
  1845. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1846. for (var index = 0; index < uniformsNames.length; index++) {
  1847. results.push(this._gl.getUniformLocation(webGLPipelineContext.program!, uniformsNames[index]));
  1848. }
  1849. return results;
  1850. }
  1851. /**
  1852. * Gets the lsit of active attributes for a given webGL program
  1853. * @param pipelineContext defines the pipeline context to use
  1854. * @param attributesNames defines the list of attribute names to get
  1855. * @returns an array of indices indicating the offset of each attribute
  1856. */
  1857. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  1858. var results = [];
  1859. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1860. for (var index = 0; index < attributesNames.length; index++) {
  1861. try {
  1862. results.push(this._gl.getAttribLocation(webGLPipelineContext.program!, attributesNames[index]));
  1863. } catch (e) {
  1864. results.push(-1);
  1865. }
  1866. }
  1867. return results;
  1868. }
  1869. /**
  1870. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  1871. * @param effect defines the effect to activate
  1872. */
  1873. public enableEffect(effect: Nullable<Effect>): void {
  1874. if (!effect || effect === this._currentEffect) {
  1875. return;
  1876. }
  1877. // Use program
  1878. this.bindSamplers(effect);
  1879. this._currentEffect = effect;
  1880. if (effect.onBind) {
  1881. effect.onBind(effect);
  1882. }
  1883. if (effect._onBindObservable) {
  1884. effect._onBindObservable.notifyObservers(effect);
  1885. }
  1886. }
  1887. /**
  1888. * Set the value of an uniform to an array of int32
  1889. * @param uniform defines the webGL uniform location where to store the value
  1890. * @param array defines the array of int32 to store
  1891. */
  1892. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  1893. if (!uniform) {
  1894. return;
  1895. }
  1896. this._gl.uniform1iv(uniform, array);
  1897. }
  1898. /**
  1899. * Set the value of an uniform to an array of int32 (stored as vec2)
  1900. * @param uniform defines the webGL uniform location where to store the value
  1901. * @param array defines the array of int32 to store
  1902. */
  1903. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  1904. if (!uniform || array.length % 2 !== 0) {
  1905. return;
  1906. }
  1907. this._gl.uniform2iv(uniform, array);
  1908. }
  1909. /**
  1910. * Set the value of an uniform to an array of int32 (stored as vec3)
  1911. * @param uniform defines the webGL uniform location where to store the value
  1912. * @param array defines the array of int32 to store
  1913. */
  1914. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  1915. if (!uniform || array.length % 3 !== 0) {
  1916. return;
  1917. }
  1918. this._gl.uniform3iv(uniform, array);
  1919. }
  1920. /**
  1921. * Set the value of an uniform to an array of int32 (stored as vec4)
  1922. * @param uniform defines the webGL uniform location where to store the value
  1923. * @param array defines the array of int32 to store
  1924. */
  1925. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  1926. if (!uniform || array.length % 4 !== 0) {
  1927. return;
  1928. }
  1929. this._gl.uniform4iv(uniform, array);
  1930. }
  1931. /**
  1932. * Set the value of an uniform to an array of float32
  1933. * @param uniform defines the webGL uniform location where to store the value
  1934. * @param array defines the array of float32 to store
  1935. */
  1936. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  1937. if (!uniform) {
  1938. return;
  1939. }
  1940. this._gl.uniform1fv(uniform, array);
  1941. }
  1942. /**
  1943. * Set the value of an uniform to an array of float32 (stored as vec2)
  1944. * @param uniform defines the webGL uniform location where to store the value
  1945. * @param array defines the array of float32 to store
  1946. */
  1947. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  1948. if (!uniform || array.length % 2 !== 0) {
  1949. return;
  1950. }
  1951. this._gl.uniform2fv(uniform, array);
  1952. }
  1953. /**
  1954. * Set the value of an uniform to an array of float32 (stored as vec3)
  1955. * @param uniform defines the webGL uniform location where to store the value
  1956. * @param array defines the array of float32 to store
  1957. */
  1958. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  1959. if (!uniform || array.length % 3 !== 0) {
  1960. return;
  1961. }
  1962. this._gl.uniform3fv(uniform, array);
  1963. }
  1964. /**
  1965. * Set the value of an uniform to an array of float32 (stored as vec4)
  1966. * @param uniform defines the webGL uniform location where to store the value
  1967. * @param array defines the array of float32 to store
  1968. */
  1969. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  1970. if (!uniform || array.length % 4 !== 0) {
  1971. return;
  1972. }
  1973. this._gl.uniform4fv(uniform, array);
  1974. }
  1975. /**
  1976. * Set the value of an uniform to an array of number
  1977. * @param uniform defines the webGL uniform location where to store the value
  1978. * @param array defines the array of number to store
  1979. */
  1980. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  1981. if (!uniform) {
  1982. return;
  1983. }
  1984. this._gl.uniform1fv(uniform, <any>array);
  1985. }
  1986. /**
  1987. * Set the value of an uniform to an array of number (stored as vec2)
  1988. * @param uniform defines the webGL uniform location where to store the value
  1989. * @param array defines the array of number to store
  1990. */
  1991. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  1992. if (!uniform || array.length % 2 !== 0) {
  1993. return;
  1994. }
  1995. this._gl.uniform2fv(uniform, <any>array);
  1996. }
  1997. /**
  1998. * Set the value of an uniform to an array of number (stored as vec3)
  1999. * @param uniform defines the webGL uniform location where to store the value
  2000. * @param array defines the array of number to store
  2001. */
  2002. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2003. if (!uniform || array.length % 3 !== 0) {
  2004. return;
  2005. }
  2006. this._gl.uniform3fv(uniform, <any>array);
  2007. }
  2008. /**
  2009. * Set the value of an uniform to an array of number (stored as vec4)
  2010. * @param uniform defines the webGL uniform location where to store the value
  2011. * @param array defines the array of number to store
  2012. */
  2013. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2014. if (!uniform || array.length % 4 !== 0) {
  2015. return;
  2016. }
  2017. this._gl.uniform4fv(uniform, <any>array);
  2018. }
  2019. /**
  2020. * Set the value of an uniform to an array of float32 (stored as matrices)
  2021. * @param uniform defines the webGL uniform location where to store the value
  2022. * @param matrices defines the array of float32 to store
  2023. */
  2024. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  2025. if (!uniform) {
  2026. return;
  2027. }
  2028. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2029. }
  2030. /**
  2031. * Set the value of an uniform to a matrix (3x3)
  2032. * @param uniform defines the webGL uniform location where to store the value
  2033. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  2034. */
  2035. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2036. if (!uniform) {
  2037. return;
  2038. }
  2039. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2040. }
  2041. /**
  2042. * Set the value of an uniform to a matrix (2x2)
  2043. * @param uniform defines the webGL uniform location where to store the value
  2044. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  2045. */
  2046. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2047. if (!uniform) {
  2048. return;
  2049. }
  2050. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2051. }
  2052. /**
  2053. * Set the value of an uniform to a number (int)
  2054. * @param uniform defines the webGL uniform location where to store the value
  2055. * @param value defines the int number to store
  2056. */
  2057. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2058. if (!uniform) {
  2059. return;
  2060. }
  2061. this._gl.uniform1i(uniform, value);
  2062. }
  2063. /**
  2064. * Set the value of an uniform to a number (float)
  2065. * @param uniform defines the webGL uniform location where to store the value
  2066. * @param value defines the float number to store
  2067. */
  2068. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2069. if (!uniform) {
  2070. return;
  2071. }
  2072. this._gl.uniform1f(uniform, value);
  2073. }
  2074. /**
  2075. * Set the value of an uniform to a vec2
  2076. * @param uniform defines the webGL uniform location where to store the value
  2077. * @param x defines the 1st component of the value
  2078. * @param y defines the 2nd component of the value
  2079. */
  2080. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  2081. if (!uniform) {
  2082. return;
  2083. }
  2084. this._gl.uniform2f(uniform, x, y);
  2085. }
  2086. /**
  2087. * Set the value of an uniform to a vec3
  2088. * @param uniform defines the webGL uniform location where to store the value
  2089. * @param x defines the 1st component of the value
  2090. * @param y defines the 2nd component of the value
  2091. * @param z defines the 3rd component of the value
  2092. */
  2093. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  2094. if (!uniform) {
  2095. return;
  2096. }
  2097. this._gl.uniform3f(uniform, x, y, z);
  2098. }
  2099. /**
  2100. * Set the value of an uniform to a boolean
  2101. * @param uniform defines the webGL uniform location where to store the value
  2102. * @param bool defines the boolean to store
  2103. */
  2104. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  2105. if (!uniform) {
  2106. return;
  2107. }
  2108. this._gl.uniform1i(uniform, bool);
  2109. }
  2110. /**
  2111. * Set the value of an uniform to a vec4
  2112. * @param uniform defines the webGL uniform location where to store the value
  2113. * @param x defines the 1st component of the value
  2114. * @param y defines the 2nd component of the value
  2115. * @param z defines the 3rd component of the value
  2116. * @param w defines the 4th component of the value
  2117. */
  2118. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  2119. if (!uniform) {
  2120. return;
  2121. }
  2122. this._gl.uniform4f(uniform, x, y, z, w);
  2123. }
  2124. /**
  2125. * Sets a Color4 on a uniform variable
  2126. * @param uniform defines the uniform location
  2127. * @param color4 defines the value to be set
  2128. */
  2129. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: IColor4Like): void {
  2130. if (!uniform) {
  2131. return;
  2132. }
  2133. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  2134. }
  2135. // States
  2136. /**
  2137. * Gets the depth culling state manager
  2138. */
  2139. public get depthCullingState(): DepthCullingState {
  2140. return this._depthCullingState;
  2141. }
  2142. /**
  2143. * Gets the alpha state manager
  2144. */
  2145. public get alphaState(): AlphaState {
  2146. return this._alphaState;
  2147. }
  2148. /**
  2149. * Gets the stencil state manager
  2150. */
  2151. public get stencilState(): StencilState {
  2152. return this._stencilState;
  2153. }
  2154. // Textures
  2155. /**
  2156. * Clears the list of texture accessible through engine.
  2157. * This can help preventing texture load conflict due to name collision.
  2158. */
  2159. public clearInternalTexturesCache() {
  2160. this._internalTexturesCache = [];
  2161. }
  2162. /**
  2163. * Force the entire cache to be cleared
  2164. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  2165. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  2166. */
  2167. public wipeCaches(bruteForce?: boolean): void {
  2168. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  2169. return;
  2170. }
  2171. this._currentEffect = null;
  2172. this._viewportCached.x = 0;
  2173. this._viewportCached.y = 0;
  2174. this._viewportCached.z = 0;
  2175. this._viewportCached.w = 0;
  2176. if (bruteForce) {
  2177. this.resetTextureCache();
  2178. this._currentProgram = null;
  2179. this._stencilState.reset();
  2180. this._depthCullingState.reset();
  2181. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2182. this._alphaState.reset();
  2183. this._unpackFlipYCached = null;
  2184. this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
  2185. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2186. }
  2187. this._resetVertexBufferBinding();
  2188. this._cachedIndexBuffer = null;
  2189. this._cachedEffectForVertexBuffers = null;
  2190. this._unbindVertexArrayObject();
  2191. this.bindIndexBuffer(null);
  2192. }
  2193. /** @hidden */
  2194. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  2195. var gl = this._gl;
  2196. var magFilter = gl.NEAREST;
  2197. var minFilter = gl.NEAREST;
  2198. switch (samplingMode) {
  2199. case Constants.TEXTURE_BILINEAR_SAMPLINGMODE:
  2200. magFilter = gl.LINEAR;
  2201. if (generateMipMaps) {
  2202. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2203. } else {
  2204. minFilter = gl.LINEAR;
  2205. }
  2206. break;
  2207. case Constants.TEXTURE_TRILINEAR_SAMPLINGMODE:
  2208. magFilter = gl.LINEAR;
  2209. if (generateMipMaps) {
  2210. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2211. } else {
  2212. minFilter = gl.LINEAR;
  2213. }
  2214. break;
  2215. case Constants.TEXTURE_NEAREST_SAMPLINGMODE:
  2216. magFilter = gl.NEAREST;
  2217. if (generateMipMaps) {
  2218. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2219. } else {
  2220. minFilter = gl.NEAREST;
  2221. }
  2222. break;
  2223. case Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  2224. magFilter = gl.NEAREST;
  2225. if (generateMipMaps) {
  2226. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  2227. } else {
  2228. minFilter = gl.NEAREST;
  2229. }
  2230. break;
  2231. case Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  2232. magFilter = gl.NEAREST;
  2233. if (generateMipMaps) {
  2234. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2235. } else {
  2236. minFilter = gl.LINEAR;
  2237. }
  2238. break;
  2239. case Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  2240. magFilter = gl.NEAREST;
  2241. if (generateMipMaps) {
  2242. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2243. } else {
  2244. minFilter = gl.LINEAR;
  2245. }
  2246. break;
  2247. case Constants.TEXTURE_NEAREST_LINEAR:
  2248. magFilter = gl.NEAREST;
  2249. minFilter = gl.LINEAR;
  2250. break;
  2251. case Constants.TEXTURE_NEAREST_NEAREST:
  2252. magFilter = gl.NEAREST;
  2253. minFilter = gl.NEAREST;
  2254. break;
  2255. case Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  2256. magFilter = gl.LINEAR;
  2257. if (generateMipMaps) {
  2258. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  2259. } else {
  2260. minFilter = gl.NEAREST;
  2261. }
  2262. break;
  2263. case Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  2264. magFilter = gl.LINEAR;
  2265. if (generateMipMaps) {
  2266. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2267. } else {
  2268. minFilter = gl.NEAREST;
  2269. }
  2270. break;
  2271. case Constants.TEXTURE_LINEAR_LINEAR:
  2272. magFilter = gl.LINEAR;
  2273. minFilter = gl.LINEAR;
  2274. break;
  2275. case Constants.TEXTURE_LINEAR_NEAREST:
  2276. magFilter = gl.LINEAR;
  2277. minFilter = gl.NEAREST;
  2278. break;
  2279. }
  2280. return {
  2281. min: minFilter,
  2282. mag: magFilter
  2283. };
  2284. }
  2285. /** @hidden */
  2286. public _createTexture(): WebGLTexture {
  2287. let texture = this._gl.createTexture();
  2288. if (!texture) {
  2289. throw new Error("Unable to create texture");
  2290. }
  2291. return texture;
  2292. }
  2293. /**
  2294. * Usually called from Texture.ts.
  2295. * Passed information to create a WebGLTexture
  2296. * @param urlArg defines a value which contains one of the following:
  2297. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  2298. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2299. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2300. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  2301. * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
  2302. * @param scene needed for loading to the correct scene
  2303. * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
  2304. * @param onLoad optional callback to be called upon successful completion
  2305. * @param onError optional callback to be called upon failure
  2306. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  2307. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  2308. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  2309. * @param forcedExtension defines the extension to use to pick the right loader
  2310. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (default: empty array)
  2311. * @returns a InternalTexture for assignment back into BABYLON.Texture
  2312. */
  2313. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<ISceneLike>, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  2314. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2315. buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  2316. forcedExtension: Nullable<string> = null, excludeLoaders: Array<IInternalTextureLoader> = []): InternalTexture {
  2317. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2318. var fromData = url.substr(0, 5) === "data:";
  2319. var fromBlob = url.substr(0, 5) === "blob:";
  2320. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  2321. let texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Url);
  2322. // establish the file extension, if possible
  2323. var lastDot = url.lastIndexOf('.');
  2324. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  2325. let loader: Nullable<IInternalTextureLoader> = null;
  2326. for (let availableLoader of ThinEngine._TextureLoaders) {
  2327. if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  2328. loader = availableLoader;
  2329. break;
  2330. }
  2331. }
  2332. if (loader) {
  2333. url = loader.transformUrl(url, this._textureFormatInUse);
  2334. }
  2335. if (scene) {
  2336. scene._addPendingData(texture);
  2337. }
  2338. texture.url = url;
  2339. texture.generateMipMaps = !noMipmap;
  2340. texture.samplingMode = samplingMode;
  2341. texture.invertY = invertY;
  2342. if (!this._doNotHandleContextLost) {
  2343. // Keep a link to the buffer only if we plan to handle context lost
  2344. texture._buffer = buffer;
  2345. }
  2346. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  2347. if (onLoad && !fallback) {
  2348. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  2349. }
  2350. if (!fallback) { this._internalTexturesCache.push(texture); }
  2351. let onInternalError = (message?: string, exception?: any) => {
  2352. if (scene) {
  2353. scene._removePendingData(texture);
  2354. }
  2355. let customFallback = false;
  2356. if (loader) {
  2357. const fallbackUrl = loader.getFallbackTextureUrl(url, this._textureFormatInUse);
  2358. if (fallbackUrl) {
  2359. // Add Back
  2360. customFallback = true;
  2361. excludeLoaders.push(loader);
  2362. this.createTexture(urlArg, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture, undefined, undefined, excludeLoaders);
  2363. return;
  2364. }
  2365. }
  2366. if (!customFallback) {
  2367. if (onLoadObserver) {
  2368. texture.onLoadedObservable.remove(onLoadObserver);
  2369. }
  2370. if (EngineStore.UseFallbackTexture) {
  2371. this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);
  2372. return;
  2373. }
  2374. }
  2375. if (onError) {
  2376. onError(message || "Unknown error", exception);
  2377. }
  2378. };
  2379. // processing for non-image formats
  2380. if (loader) {
  2381. var callback = (data: string | ArrayBuffer) => {
  2382. loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void, loadFailed) => {
  2383. if (loadFailed) {
  2384. onInternalError("TextureLoader failed to load data");
  2385. } else {
  2386. this._prepareWebGLTexture(texture, scene, width, height, texture.invertY, !loadMipmap, isCompressed, () => {
  2387. done();
  2388. return false;
  2389. }, samplingMode);
  2390. }
  2391. });
  2392. };
  2393. if (!buffer) {
  2394. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, (request?: IWebRequest, exception?: any) => {
  2395. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  2396. });
  2397. } else {
  2398. //callback(buffer as ArrayBuffer);
  2399. if (buffer instanceof ArrayBuffer) {
  2400. callback(buffer);
  2401. }
  2402. else {
  2403. if (onError) {
  2404. onError("Unable to load: only ArrayBuffer supported here", null);
  2405. }
  2406. }
  2407. }
  2408. } else {
  2409. var onload = (img: HTMLImageElement) => {
  2410. if (fromBlob && !this._doNotHandleContextLost) {
  2411. // We need to store the image if we need to rebuild the texture
  2412. // in case of a webgl context lost
  2413. texture._buffer = img;
  2414. }
  2415. this._prepareWebGLTexture(texture, scene, img.width, img.height, texture.invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2416. let gl = this._gl;
  2417. var isPot = (img.width === potWidth && img.height === potHeight);
  2418. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2419. if (isPot) {
  2420. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2421. return false;
  2422. }
  2423. let maxTextureSize = this._caps.maxTextureSize;
  2424. if (img.width > maxTextureSize || img.height > maxTextureSize || !this._supportsHardwareTextureRescaling) {
  2425. this._prepareWorkingCanvas();
  2426. if (!this._workingCanvas || !this._workingContext) {
  2427. return false;
  2428. }
  2429. this._workingCanvas.width = potWidth;
  2430. this._workingCanvas.height = potHeight;
  2431. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  2432. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2433. texture.width = potWidth;
  2434. texture.height = potHeight;
  2435. return false;
  2436. } else {
  2437. // Using shaders when possible to rescale because canvas.drawImage is lossy
  2438. let source = new InternalTexture(this, InternalTextureSource.Temp);
  2439. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  2440. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2441. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2442. this._releaseTexture(source);
  2443. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2444. continuationCallback();
  2445. });
  2446. }
  2447. return true;
  2448. }, samplingMode);
  2449. };
  2450. if (!fromData || isBase64) {
  2451. if (buffer instanceof HTMLImageElement) {
  2452. onload(buffer);
  2453. } else {
  2454. FileTools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  2455. }
  2456. }
  2457. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) {
  2458. FileTools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  2459. }
  2460. else if (buffer) {
  2461. onload(<HTMLImageElement>buffer);
  2462. }
  2463. }
  2464. return texture;
  2465. }
  2466. /**
  2467. * @hidden
  2468. */
  2469. public _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<any>, internalFormat: number, onComplete: () => void): void {
  2470. }
  2471. /**
  2472. * Creates a raw texture
  2473. * @param data defines the data to store in the texture
  2474. * @param width defines the width of the texture
  2475. * @param height defines the height of the texture
  2476. * @param format defines the format of the data
  2477. * @param generateMipMaps defines if the engine should generate the mip levels
  2478. * @param invertY defines if data must be stored with Y axis inverted
  2479. * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
  2480. * @param compression defines the compression used (null by default)
  2481. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  2482. * @returns the raw texture inside an InternalTexture
  2483. */
  2484. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  2485. throw _DevTools.WarnImport("Engine.RawTexture");
  2486. }
  2487. /**
  2488. * Creates a new raw cube texture
  2489. * @param data defines the array of data to use to create each face
  2490. * @param size defines the size of the textures
  2491. * @param format defines the format of the data
  2492. * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
  2493. * @param generateMipMaps defines if the engine should generate the mip levels
  2494. * @param invertY defines if data must be stored with Y axis inverted
  2495. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2496. * @param compression defines the compression used (null by default)
  2497. * @returns the cube texture as an InternalTexture
  2498. */
  2499. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  2500. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  2501. compression: Nullable<string> = null): InternalTexture {
  2502. throw _DevTools.WarnImport("Engine.RawTexture");
  2503. }
  2504. /**
  2505. * Creates a new raw 3D texture
  2506. * @param data defines the data used to create the texture
  2507. * @param width defines the width of the texture
  2508. * @param height defines the height of the texture
  2509. * @param depth defines the depth of the texture
  2510. * @param format defines the format of the texture
  2511. * @param generateMipMaps defines if the engine must generate mip levels
  2512. * @param invertY defines if data must be stored with Y axis inverted
  2513. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2514. * @param compression defines the compressed used (can be null)
  2515. * @param textureType defines the compressed used (can be null)
  2516. * @returns a new raw 3D texture (stored in an InternalTexture)
  2517. */
  2518. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  2519. throw _DevTools.WarnImport("Engine.RawTexture");
  2520. }
  2521. private _unpackFlipYCached: Nullable<boolean> = null;
  2522. /**
  2523. * In case you are sharing the context with other applications, it might
  2524. * be interested to not cache the unpack flip y state to ensure a consistent
  2525. * value would be set.
  2526. */
  2527. public enableUnpackFlipYCached = true;
  2528. /** @hidden */
  2529. public _unpackFlipY(value: boolean): void {
  2530. if (this._unpackFlipYCached !== value) {
  2531. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  2532. if (this.enableUnpackFlipYCached) {
  2533. this._unpackFlipYCached = value;
  2534. }
  2535. }
  2536. }
  2537. /** @hidden */
  2538. public _getUnpackAlignement(): number {
  2539. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  2540. }
  2541. /**
  2542. * Update the sampling mode of a given texture
  2543. * @param samplingMode defines the required sampling mode
  2544. * @param texture defines the texture to update
  2545. */
  2546. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  2547. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  2548. if (texture.isCube) {
  2549. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  2550. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2551. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2552. } else if (texture.is3D) {
  2553. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  2554. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2555. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  2556. } else {
  2557. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  2558. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2559. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2560. }
  2561. texture.samplingMode = samplingMode;
  2562. }
  2563. /**
  2564. * Updates a depth texture Comparison Mode and Function.
  2565. * If the comparison Function is equal to 0, the mode will be set to none.
  2566. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  2567. * @param texture The texture to set the comparison function for
  2568. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  2569. */
  2570. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  2571. if (this.webGLVersion === 1) {
  2572. Logger.Error("WebGL 1 does not support texture comparison.");
  2573. return;
  2574. }
  2575. var gl = this._gl;
  2576. if (texture.isCube) {
  2577. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  2578. if (comparisonFunction === 0) {
  2579. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Constants.LEQUAL);
  2580. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  2581. }
  2582. else {
  2583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  2584. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  2585. }
  2586. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2587. } else {
  2588. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2589. if (comparisonFunction === 0) {
  2590. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Constants.LEQUAL);
  2591. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  2592. }
  2593. else {
  2594. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  2595. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  2596. }
  2597. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2598. }
  2599. texture._comparisonFunction = comparisonFunction;
  2600. }
  2601. /** @hidden */
  2602. public _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number): void {
  2603. var width = (<{ width: number, height: number }>size).width || <number>size;
  2604. var height = (<{ width: number, height: number }>size).height || <number>size;
  2605. internalTexture.baseWidth = width;
  2606. internalTexture.baseHeight = height;
  2607. internalTexture.width = width;
  2608. internalTexture.height = height;
  2609. internalTexture.isReady = true;
  2610. internalTexture.samples = 1;
  2611. internalTexture.generateMipMaps = false;
  2612. internalTexture._generateDepthBuffer = true;
  2613. internalTexture._generateStencilBuffer = generateStencil;
  2614. internalTexture.samplingMode = bilinearFiltering ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  2615. internalTexture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  2616. internalTexture._comparisonFunction = comparisonFunction;
  2617. var gl = this._gl;
  2618. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  2619. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  2620. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  2621. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  2622. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2623. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2624. if (comparisonFunction === 0) {
  2625. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Constants.LEQUAL);
  2626. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  2627. }
  2628. else {
  2629. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  2630. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  2631. }
  2632. }
  2633. /**
  2634. * Creates a depth stencil texture.
  2635. * This is only available in WebGL 2 or with the depth texture extension available.
  2636. * @param size The size of face edge in the texture.
  2637. * @param options The options defining the texture.
  2638. * @returns The texture
  2639. */
  2640. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions): InternalTexture {
  2641. if (options.isCube) {
  2642. let width = (<{ width: number, height: number }>size).width || <number>size;
  2643. return this._createDepthStencilCubeTexture(width, options);
  2644. }
  2645. else {
  2646. return this._createDepthStencilTexture(size, options);
  2647. }
  2648. }
  2649. /**
  2650. * Creates a depth stencil texture.
  2651. * This is only available in WebGL 2 or with the depth texture extension available.
  2652. * @param size The size of face edge in the texture.
  2653. * @param options The options defining the texture.
  2654. * @returns The texture
  2655. */
  2656. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions): InternalTexture {
  2657. var internalTexture = new InternalTexture(this, InternalTextureSource.Depth);
  2658. if (!this._caps.depthTextureExtension) {
  2659. Logger.Error("Depth texture is not supported by your browser or hardware.");
  2660. return internalTexture;
  2661. }
  2662. var internalOptions = {
  2663. bilinearFiltering: false,
  2664. comparisonFunction: 0,
  2665. generateStencil: false,
  2666. ...options
  2667. };
  2668. var gl = this._gl;
  2669. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  2670. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  2671. if (this.webGLVersion > 1) {
  2672. if (internalOptions.generateStencil) {
  2673. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  2674. }
  2675. else {
  2676. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  2677. }
  2678. }
  2679. else {
  2680. if (internalOptions.generateStencil) {
  2681. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  2682. }
  2683. else {
  2684. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  2685. }
  2686. }
  2687. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2688. return internalTexture;
  2689. }
  2690. /** @hidden */
  2691. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  2692. var gl = this._gl;
  2693. var target = gl.TEXTURE_2D;
  2694. if (texture.isCube) {
  2695. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2696. }
  2697. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  2698. }
  2699. /** @hidden */
  2700. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0, babylonInternalFormat?: number, useTextureWidthAndHeight = false): void {
  2701. var gl = this._gl;
  2702. var textureType = this._getWebGLTextureType(texture.type);
  2703. var format = this._getInternalFormat(texture.format);
  2704. var internalFormat = babylonInternalFormat === undefined ? this._getRGBABufferInternalSizedFormat(texture.type, format) : this._getInternalFormat(babylonInternalFormat);
  2705. this._unpackFlipY(texture.invertY);
  2706. var target = gl.TEXTURE_2D;
  2707. if (texture.isCube) {
  2708. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2709. }
  2710. const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
  2711. const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
  2712. const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  2713. const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  2714. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  2715. }
  2716. /** @hidden */
  2717. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  2718. var gl = this._gl;
  2719. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  2720. this._bindTextureDirectly(bindTarget, texture, true);
  2721. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  2722. this._bindTextureDirectly(bindTarget, null, true);
  2723. }
  2724. /** @hidden */
  2725. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  2726. var gl = this._gl;
  2727. var textureType = this._getWebGLTextureType(texture.type);
  2728. var format = this._getInternalFormat(texture.format);
  2729. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  2730. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  2731. this._bindTextureDirectly(bindTarget, texture, true);
  2732. this._unpackFlipY(texture.invertY);
  2733. var target = gl.TEXTURE_2D;
  2734. if (texture.isCube) {
  2735. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2736. }
  2737. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  2738. this._bindTextureDirectly(bindTarget, null, true);
  2739. }
  2740. /**
  2741. * @hidden
  2742. */
  2743. public _setCubeMapTextureParams(loadMipmap: boolean): void {
  2744. var gl = this._gl;
  2745. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2746. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2749. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2750. }
  2751. protected _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<ISceneLike>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  2752. var gl = this._gl;
  2753. if (!gl) {
  2754. return;
  2755. }
  2756. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  2757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2759. if (!noMipmap && !isCompressed) {
  2760. gl.generateMipmap(gl.TEXTURE_2D);
  2761. }
  2762. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2763. // this.resetTextureCache();
  2764. if (scene) {
  2765. scene._removePendingData(texture);
  2766. }
  2767. texture.onLoadedObservable.notifyObservers(texture);
  2768. texture.onLoadedObservable.clear();
  2769. }
  2770. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<ISceneLike>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  2771. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE): void {
  2772. var maxTextureSize = this.getCaps().maxTextureSize;
  2773. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(width, maxTextureSize) : width);
  2774. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(height, maxTextureSize) : height);
  2775. var gl = this._gl;
  2776. if (!gl) {
  2777. return;
  2778. }
  2779. if (!texture._webGLTexture) {
  2780. // this.resetTextureCache();
  2781. if (scene) {
  2782. scene._removePendingData(texture);
  2783. }
  2784. return;
  2785. }
  2786. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2787. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  2788. texture.baseWidth = width;
  2789. texture.baseHeight = height;
  2790. texture.width = potWidth;
  2791. texture.height = potHeight;
  2792. texture.isReady = true;
  2793. if (processFunction(potWidth, potHeight, () => {
  2794. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  2795. })) {
  2796. // Returning as texture needs extra async steps
  2797. return;
  2798. }
  2799. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  2800. }
  2801. /** @hidden */
  2802. public _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  2803. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  2804. var gl = this._gl;
  2805. // Create the depth/stencil buffer
  2806. if (generateStencilBuffer) {
  2807. depthStencilBuffer = gl.createRenderbuffer();
  2808. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2809. if (samples > 1) {
  2810. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  2811. } else {
  2812. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  2813. }
  2814. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2815. }
  2816. else if (generateDepthBuffer) {
  2817. depthStencilBuffer = gl.createRenderbuffer();
  2818. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2819. if (samples > 1) {
  2820. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  2821. } else {
  2822. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  2823. }
  2824. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2825. }
  2826. return depthStencilBuffer;
  2827. }
  2828. /** @hidden */
  2829. public _releaseFramebufferObjects(texture: InternalTexture): void {
  2830. var gl = this._gl;
  2831. if (texture._framebuffer) {
  2832. gl.deleteFramebuffer(texture._framebuffer);
  2833. texture._framebuffer = null;
  2834. }
  2835. if (texture._depthStencilBuffer) {
  2836. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2837. texture._depthStencilBuffer = null;
  2838. }
  2839. if (texture._MSAAFramebuffer) {
  2840. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2841. texture._MSAAFramebuffer = null;
  2842. }
  2843. if (texture._MSAARenderBuffer) {
  2844. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2845. texture._MSAARenderBuffer = null;
  2846. }
  2847. }
  2848. /** @hidden */
  2849. public _releaseTexture(texture: InternalTexture): void {
  2850. this._releaseFramebufferObjects(texture);
  2851. this._deleteTexture(texture._webGLTexture);
  2852. // Unbind channels
  2853. this.unbindAllTextures();
  2854. var index = this._internalTexturesCache.indexOf(texture);
  2855. if (index !== -1) {
  2856. this._internalTexturesCache.splice(index, 1);
  2857. }
  2858. // Integrated fixed lod samplers.
  2859. if (texture._lodTextureHigh) {
  2860. texture._lodTextureHigh.dispose();
  2861. }
  2862. if (texture._lodTextureMid) {
  2863. texture._lodTextureMid.dispose();
  2864. }
  2865. if (texture._lodTextureLow) {
  2866. texture._lodTextureLow.dispose();
  2867. }
  2868. // Integrated irradiance map.
  2869. if (texture._irradianceTexture) {
  2870. texture._irradianceTexture.dispose();
  2871. }
  2872. }
  2873. protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
  2874. this._gl.deleteTexture(texture);
  2875. }
  2876. protected _setProgram(program: WebGLProgram): void {
  2877. if (this._currentProgram !== program) {
  2878. this._gl.useProgram(program);
  2879. this._currentProgram = program;
  2880. }
  2881. }
  2882. protected _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  2883. /**
  2884. * Binds an effect to the webGL context
  2885. * @param effect defines the effect to bind
  2886. */
  2887. public bindSamplers(effect: Effect): void {
  2888. let webGLPipelineContext = effect.getPipelineContext() as WebGLPipelineContext;
  2889. this._setProgram(webGLPipelineContext.program!);
  2890. var samplers = effect.getSamplers();
  2891. for (var index = 0; index < samplers.length; index++) {
  2892. var uniform = effect.getUniform(samplers[index]);
  2893. if (uniform) {
  2894. this._boundUniforms[index] = uniform;
  2895. }
  2896. }
  2897. this._currentEffect = null;
  2898. }
  2899. private _activateCurrentTexture() {
  2900. if (this._currentTextureChannel !== this._activeChannel) {
  2901. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  2902. this._currentTextureChannel = this._activeChannel;
  2903. }
  2904. }
  2905. /** @hidden */
  2906. public _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  2907. var wasPreviouslyBound = false;
  2908. let isTextureForRendering = texture && texture._associatedChannel > -1;
  2909. if (forTextureDataUpdate && isTextureForRendering) {
  2910. this._activeChannel = texture!._associatedChannel;
  2911. }
  2912. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  2913. if (currentTextureBound !== texture || force) {
  2914. this._activateCurrentTexture();
  2915. if (texture && texture.isMultiview) {
  2916. this._gl.bindTexture(target, texture ? texture._colorTextureArray : null);
  2917. } else {
  2918. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  2919. }
  2920. this._boundTexturesCache[this._activeChannel] = texture;
  2921. if (texture) {
  2922. texture._associatedChannel = this._activeChannel;
  2923. }
  2924. } else if (forTextureDataUpdate) {
  2925. wasPreviouslyBound = true;
  2926. this._activateCurrentTexture();
  2927. }
  2928. if (isTextureForRendering && !forTextureDataUpdate) {
  2929. this._bindSamplerUniformToChannel(texture!._associatedChannel, this._activeChannel);
  2930. }
  2931. return wasPreviouslyBound;
  2932. }
  2933. /** @hidden */
  2934. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  2935. if (channel === undefined) {
  2936. return;
  2937. }
  2938. if (texture) {
  2939. texture._associatedChannel = channel;
  2940. }
  2941. this._activeChannel = channel;
  2942. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2943. }
  2944. /**
  2945. * Unbind all textures from the webGL context
  2946. */
  2947. public unbindAllTextures(): void {
  2948. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  2949. this._activeChannel = channel;
  2950. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2951. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2952. if (this.webGLVersion > 1) {
  2953. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  2954. }
  2955. }
  2956. }
  2957. /**
  2958. * Sets a texture to the according uniform.
  2959. * @param channel The texture channel
  2960. * @param uniform The uniform to set
  2961. * @param texture The texture to apply
  2962. */
  2963. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  2964. if (channel === undefined) {
  2965. return;
  2966. }
  2967. if (uniform) {
  2968. this._boundUniforms[channel] = uniform;
  2969. }
  2970. this._setTexture(channel, texture);
  2971. }
  2972. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  2973. let uniform = this._boundUniforms[sourceSlot];
  2974. if (!uniform || uniform._currentState === destination) {
  2975. return;
  2976. }
  2977. this._gl.uniform1i(uniform, destination);
  2978. uniform._currentState = destination;
  2979. }
  2980. private _getTextureWrapMode(mode: number): number {
  2981. switch (mode) {
  2982. case Constants.TEXTURE_WRAP_ADDRESSMODE:
  2983. return this._gl.REPEAT;
  2984. case Constants.TEXTURE_CLAMP_ADDRESSMODE:
  2985. return this._gl.CLAMP_TO_EDGE;
  2986. case Constants.TEXTURE_MIRROR_ADDRESSMODE:
  2987. return this._gl.MIRRORED_REPEAT;
  2988. }
  2989. return this._gl.REPEAT;
  2990. }
  2991. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  2992. // Not ready?
  2993. if (!texture) {
  2994. if (this._boundTexturesCache[channel] != null) {
  2995. this._activeChannel = channel;
  2996. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2997. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2998. if (this.webGLVersion > 1) {
  2999. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3000. }
  3001. }
  3002. return false;
  3003. }
  3004. // Video
  3005. if ((<VideoTexture>texture).video) {
  3006. this._activeChannel = channel;
  3007. (<VideoTexture>texture).update();
  3008. } else if (texture.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3009. texture.delayLoad();
  3010. return false;
  3011. }
  3012. let internalTexture: InternalTexture;
  3013. if (depthStencilTexture) {
  3014. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  3015. }
  3016. else if (texture.isReady()) {
  3017. internalTexture = <InternalTexture>texture.getInternalTexture();
  3018. }
  3019. else if (texture.isCube) {
  3020. internalTexture = this.emptyCubeTexture;
  3021. }
  3022. else if (texture.is3D) {
  3023. internalTexture = this.emptyTexture3D;
  3024. }
  3025. else {
  3026. internalTexture = this.emptyTexture;
  3027. }
  3028. if (!isPartOfTextureArray && internalTexture) {
  3029. internalTexture._associatedChannel = channel;
  3030. }
  3031. let needToBind = true;
  3032. if (this._boundTexturesCache[channel] === internalTexture) {
  3033. if (!isPartOfTextureArray) {
  3034. this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel);
  3035. }
  3036. needToBind = false;
  3037. }
  3038. this._activeChannel = channel;
  3039. if (internalTexture && internalTexture.isMultiview) {
  3040. if (needToBind) {
  3041. this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, internalTexture, isPartOfTextureArray);
  3042. }
  3043. } else if (internalTexture && internalTexture.is3D) {
  3044. if (needToBind) {
  3045. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  3046. }
  3047. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  3048. internalTexture._cachedWrapU = texture.wrapU;
  3049. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  3050. }
  3051. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  3052. internalTexture._cachedWrapV = texture.wrapV;
  3053. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  3054. }
  3055. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  3056. internalTexture._cachedWrapR = texture.wrapR;
  3057. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  3058. }
  3059. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  3060. }
  3061. else if (internalTexture && internalTexture.isCube) {
  3062. if (needToBind) {
  3063. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  3064. }
  3065. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3066. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3067. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  3068. var textureWrapMode = (texture.coordinatesMode !== Constants.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Constants.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3069. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  3070. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3071. }
  3072. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3073. } else {
  3074. if (needToBind) {
  3075. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  3076. }
  3077. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  3078. internalTexture._cachedWrapU = texture.wrapU;
  3079. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  3080. }
  3081. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  3082. internalTexture._cachedWrapV = texture.wrapV;
  3083. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  3084. }
  3085. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3086. }
  3087. return true;
  3088. }
  3089. /**
  3090. * Sets an array of texture to the webGL context
  3091. * @param channel defines the channel where the texture array must be set
  3092. * @param uniform defines the associated uniform location
  3093. * @param textures defines the array of textures to bind
  3094. */
  3095. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  3096. if (channel === undefined || !uniform) {
  3097. return;
  3098. }
  3099. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  3100. this._textureUnits = new Int32Array(textures.length);
  3101. }
  3102. for (let i = 0; i < textures.length; i++) {
  3103. let texture = textures[i].getInternalTexture();
  3104. if (texture) {
  3105. this._textureUnits[i] = channel + i;
  3106. texture._associatedChannel = channel + i;
  3107. } else {
  3108. this._textureUnits[i] = -1;
  3109. }
  3110. }
  3111. this._gl.uniform1iv(uniform, this._textureUnits);
  3112. for (var index = 0; index < textures.length; index++) {
  3113. this._setTexture(this._textureUnits[index], textures[index], true);
  3114. }
  3115. }
  3116. /** @hidden */
  3117. public _setAnisotropicLevel(target: number, texture: BaseTexture) {
  3118. var internalTexture = texture.getInternalTexture();
  3119. if (!internalTexture) {
  3120. return;
  3121. }
  3122. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3123. var value = texture.anisotropicFilteringLevel;
  3124. if (internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  3125. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  3126. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR) {
  3127. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  3128. }
  3129. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  3130. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  3131. internalTexture._cachedAnisotropicFilteringLevel = value;
  3132. }
  3133. }
  3134. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  3135. this._bindTextureDirectly(target, texture, true, true);
  3136. this._gl.texParameterf(target, parameter, value);
  3137. }
  3138. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  3139. if (texture) {
  3140. this._bindTextureDirectly(target, texture, true, true);
  3141. }
  3142. this._gl.texParameteri(target, parameter, value);
  3143. }
  3144. /**
  3145. * Unbind all vertex attributes from the webGL context
  3146. */
  3147. public unbindAllAttributes() {
  3148. if (this._mustWipeVertexAttributes) {
  3149. this._mustWipeVertexAttributes = false;
  3150. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  3151. this._gl.disableVertexAttribArray(i);
  3152. this._vertexAttribArraysEnabled[i] = false;
  3153. this._currentBufferPointers[i].active = false;
  3154. }
  3155. return;
  3156. }
  3157. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  3158. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  3159. continue;
  3160. }
  3161. this._gl.disableVertexAttribArray(i);
  3162. this._vertexAttribArraysEnabled[i] = false;
  3163. this._currentBufferPointers[i].active = false;
  3164. }
  3165. }
  3166. /**
  3167. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  3168. */
  3169. public releaseEffects() {
  3170. for (var name in this._compiledEffects) {
  3171. let webGLPipelineContext = this._compiledEffects[name].getPipelineContext() as WebGLPipelineContext;
  3172. this._deletePipelineContext(webGLPipelineContext);
  3173. }
  3174. this._compiledEffects = {};
  3175. }
  3176. /**
  3177. * Dispose and release all associated resources
  3178. */
  3179. public dispose(): void {
  3180. this.stopRenderLoop();
  3181. // Empty texture
  3182. if (this._emptyTexture) {
  3183. this._releaseTexture(this._emptyTexture);
  3184. this._emptyTexture = null;
  3185. }
  3186. if (this._emptyCubeTexture) {
  3187. this._releaseTexture(this._emptyCubeTexture);
  3188. this._emptyCubeTexture = null;
  3189. }
  3190. // Release effects
  3191. this.releaseEffects();
  3192. // Unbind
  3193. this.unbindAllAttributes();
  3194. this._boundUniforms = [];
  3195. // Events
  3196. if (DomManagement.IsWindowObjectExist()) {
  3197. if (this._renderingCanvas) {
  3198. if (!this._doNotHandleContextLost) {
  3199. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  3200. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  3201. }
  3202. }
  3203. }
  3204. this._workingCanvas = null;
  3205. this._workingContext = null;
  3206. this._currentBufferPointers = [];
  3207. this._renderingCanvas = null;
  3208. this._currentProgram = null;
  3209. this._bindedRenderFunction = null;
  3210. Effect.ResetCache();
  3211. // Abort active requests
  3212. for (let request of this._activeRequests) {
  3213. request.abort();
  3214. }
  3215. }
  3216. /**
  3217. * Attach a new callback raised when context lost event is fired
  3218. * @param callback defines the callback to call
  3219. */
  3220. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3221. if (this._renderingCanvas) {
  3222. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  3223. }
  3224. }
  3225. /**
  3226. * Attach a new callback raised when context restored event is fired
  3227. * @param callback defines the callback to call
  3228. */
  3229. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3230. if (this._renderingCanvas) {
  3231. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  3232. }
  3233. }
  3234. /**
  3235. * Get the current error code of the webGL context
  3236. * @returns the error code
  3237. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  3238. */
  3239. public getError(): number {
  3240. return this._gl.getError();
  3241. }
  3242. private _canRenderToFloatFramebuffer(): boolean {
  3243. if (this._webGLVersion > 1) {
  3244. return this._caps.colorBufferFloat;
  3245. }
  3246. return this._canRenderToFramebuffer(Constants.TEXTURETYPE_FLOAT);
  3247. }
  3248. private _canRenderToHalfFloatFramebuffer(): boolean {
  3249. if (this._webGLVersion > 1) {
  3250. return this._caps.colorBufferFloat;
  3251. }
  3252. return this._canRenderToFramebuffer(Constants.TEXTURETYPE_HALF_FLOAT);
  3253. }
  3254. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  3255. private _canRenderToFramebuffer(type: number): boolean {
  3256. let gl = this._gl;
  3257. //clear existing errors
  3258. while (gl.getError() !== gl.NO_ERROR) { }
  3259. let successful = true;
  3260. let texture = gl.createTexture();
  3261. gl.bindTexture(gl.TEXTURE_2D, texture);
  3262. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3263. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3264. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3265. let fb = gl.createFramebuffer();
  3266. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  3267. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3268. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  3269. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  3270. successful = successful && (gl.getError() === gl.NO_ERROR);
  3271. //try render by clearing frame buffer's color buffer
  3272. if (successful) {
  3273. gl.clear(gl.COLOR_BUFFER_BIT);
  3274. successful = successful && (gl.getError() === gl.NO_ERROR);
  3275. }
  3276. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  3277. if (successful) {
  3278. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  3279. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3280. let readFormat = gl.RGBA;
  3281. let readType = gl.UNSIGNED_BYTE;
  3282. let buffer = new Uint8Array(4);
  3283. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  3284. successful = successful && (gl.getError() === gl.NO_ERROR);
  3285. }
  3286. //clean up
  3287. gl.deleteTexture(texture);
  3288. gl.deleteFramebuffer(fb);
  3289. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3290. //clear accumulated errors
  3291. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  3292. return successful;
  3293. }
  3294. /** @hidden */
  3295. public _getWebGLTextureType(type: number): number {
  3296. if (this._webGLVersion === 1) {
  3297. switch (type) {
  3298. case Constants.TEXTURETYPE_FLOAT:
  3299. return this._gl.FLOAT;
  3300. case Constants.TEXTURETYPE_HALF_FLOAT:
  3301. return this._gl.HALF_FLOAT_OES;
  3302. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3303. return this._gl.UNSIGNED_BYTE;
  3304. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3305. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  3306. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3307. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  3308. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3309. return this._gl.UNSIGNED_SHORT_5_6_5;
  3310. }
  3311. return this._gl.UNSIGNED_BYTE;
  3312. }
  3313. switch (type) {
  3314. case Constants.TEXTURETYPE_BYTE:
  3315. return this._gl.BYTE;
  3316. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3317. return this._gl.UNSIGNED_BYTE;
  3318. case Constants.TEXTURETYPE_SHORT:
  3319. return this._gl.SHORT;
  3320. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  3321. return this._gl.UNSIGNED_SHORT;
  3322. case Constants.TEXTURETYPE_INT:
  3323. return this._gl.INT;
  3324. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  3325. return this._gl.UNSIGNED_INT;
  3326. case Constants.TEXTURETYPE_FLOAT:
  3327. return this._gl.FLOAT;
  3328. case Constants.TEXTURETYPE_HALF_FLOAT:
  3329. return this._gl.HALF_FLOAT;
  3330. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3331. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  3332. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3333. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  3334. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3335. return this._gl.UNSIGNED_SHORT_5_6_5;
  3336. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  3337. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  3338. case Constants.TEXTURETYPE_UNSIGNED_INT_24_8:
  3339. return this._gl.UNSIGNED_INT_24_8;
  3340. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  3341. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  3342. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  3343. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  3344. case Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  3345. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  3346. }
  3347. return this._gl.UNSIGNED_BYTE;
  3348. }
  3349. /** @hidden */
  3350. public _getInternalFormat(format: number): number {
  3351. var internalFormat = this._gl.RGBA;
  3352. switch (format) {
  3353. case Constants.TEXTUREFORMAT_ALPHA:
  3354. internalFormat = this._gl.ALPHA;
  3355. break;
  3356. case Constants.TEXTUREFORMAT_LUMINANCE:
  3357. internalFormat = this._gl.LUMINANCE;
  3358. break;
  3359. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3360. internalFormat = this._gl.LUMINANCE_ALPHA;
  3361. break;
  3362. case Constants.TEXTUREFORMAT_RED:
  3363. internalFormat = this._gl.RED;
  3364. break;
  3365. case Constants.TEXTUREFORMAT_RG:
  3366. internalFormat = this._gl.RG;
  3367. break;
  3368. case Constants.TEXTUREFORMAT_RGB:
  3369. internalFormat = this._gl.RGB;
  3370. break;
  3371. case Constants.TEXTUREFORMAT_RGBA:
  3372. internalFormat = this._gl.RGBA;
  3373. break;
  3374. }
  3375. if (this._webGLVersion > 1) {
  3376. switch (format) {
  3377. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3378. internalFormat = this._gl.RED_INTEGER;
  3379. break;
  3380. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3381. internalFormat = this._gl.RG_INTEGER;
  3382. break;
  3383. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3384. internalFormat = this._gl.RGB_INTEGER;
  3385. break;
  3386. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3387. internalFormat = this._gl.RGBA_INTEGER;
  3388. break;
  3389. }
  3390. }
  3391. return internalFormat;
  3392. }
  3393. /** @hidden */
  3394. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  3395. if (this._webGLVersion === 1) {
  3396. if (format !== undefined) {
  3397. switch (format) {
  3398. case Constants.TEXTUREFORMAT_ALPHA:
  3399. return this._gl.ALPHA;
  3400. case Constants.TEXTUREFORMAT_LUMINANCE:
  3401. return this._gl.LUMINANCE;
  3402. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3403. return this._gl.LUMINANCE_ALPHA;
  3404. }
  3405. }
  3406. return this._gl.RGBA;
  3407. }
  3408. switch (type) {
  3409. case Constants.TEXTURETYPE_BYTE:
  3410. switch (format) {
  3411. case Constants.TEXTUREFORMAT_RED:
  3412. return this._gl.R8_SNORM;
  3413. case Constants.TEXTUREFORMAT_RG:
  3414. return this._gl.RG8_SNORM;
  3415. case Constants.TEXTUREFORMAT_RGB:
  3416. return this._gl.RGB8_SNORM;
  3417. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3418. return this._gl.R8I;
  3419. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3420. return this._gl.RG8I;
  3421. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3422. return this._gl.RGB8I;
  3423. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3424. return this._gl.RGBA8I;
  3425. default:
  3426. return this._gl.RGBA8_SNORM;
  3427. }
  3428. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3429. switch (format) {
  3430. case Constants.TEXTUREFORMAT_RED:
  3431. return this._gl.R8;
  3432. case Constants.TEXTUREFORMAT_RG:
  3433. return this._gl.RG8;
  3434. case Constants.TEXTUREFORMAT_RGB:
  3435. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  3436. case Constants.TEXTUREFORMAT_RGBA:
  3437. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  3438. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3439. return this._gl.R8UI;
  3440. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3441. return this._gl.RG8UI;
  3442. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3443. return this._gl.RGB8UI;
  3444. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3445. return this._gl.RGBA8UI;
  3446. case Constants.TEXTUREFORMAT_ALPHA:
  3447. return this._gl.ALPHA;
  3448. case Constants.TEXTUREFORMAT_LUMINANCE:
  3449. return this._gl.LUMINANCE;
  3450. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3451. return this._gl.LUMINANCE_ALPHA;
  3452. default:
  3453. return this._gl.RGBA8;
  3454. }
  3455. case Constants.TEXTURETYPE_SHORT:
  3456. switch (format) {
  3457. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3458. return this._gl.R16I;
  3459. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3460. return this._gl.RG16I;
  3461. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3462. return this._gl.RGB16I;
  3463. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3464. return this._gl.RGBA16I;
  3465. default:
  3466. return this._gl.RGBA16I;
  3467. }
  3468. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  3469. switch (format) {
  3470. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3471. return this._gl.R16UI;
  3472. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3473. return this._gl.RG16UI;
  3474. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3475. return this._gl.RGB16UI;
  3476. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3477. return this._gl.RGBA16UI;
  3478. default:
  3479. return this._gl.RGBA16UI;
  3480. }
  3481. case Constants.TEXTURETYPE_INT:
  3482. switch (format) {
  3483. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3484. return this._gl.R32I;
  3485. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3486. return this._gl.RG32I;
  3487. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3488. return this._gl.RGB32I;
  3489. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3490. return this._gl.RGBA32I;
  3491. default:
  3492. return this._gl.RGBA32I;
  3493. }
  3494. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  3495. switch (format) {
  3496. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3497. return this._gl.R32UI;
  3498. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3499. return this._gl.RG32UI;
  3500. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3501. return this._gl.RGB32UI;
  3502. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3503. return this._gl.RGBA32UI;
  3504. default:
  3505. return this._gl.RGBA32UI;
  3506. }
  3507. case Constants.TEXTURETYPE_FLOAT:
  3508. switch (format) {
  3509. case Constants.TEXTUREFORMAT_RED:
  3510. return this._gl.R32F; // By default. Other possibility is R16F.
  3511. case Constants.TEXTUREFORMAT_RG:
  3512. return this._gl.RG32F; // By default. Other possibility is RG16F.
  3513. case Constants.TEXTUREFORMAT_RGB:
  3514. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  3515. case Constants.TEXTUREFORMAT_RGBA:
  3516. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  3517. default:
  3518. return this._gl.RGBA32F;
  3519. }
  3520. case Constants.TEXTURETYPE_HALF_FLOAT:
  3521. switch (format) {
  3522. case Constants.TEXTUREFORMAT_RED:
  3523. return this._gl.R16F;
  3524. case Constants.TEXTUREFORMAT_RG:
  3525. return this._gl.RG16F;
  3526. case Constants.TEXTUREFORMAT_RGB:
  3527. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  3528. case Constants.TEXTUREFORMAT_RGBA:
  3529. return this._gl.RGBA16F;
  3530. default:
  3531. return this._gl.RGBA16F;
  3532. }
  3533. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3534. return this._gl.RGB565;
  3535. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  3536. return this._gl.R11F_G11F_B10F;
  3537. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  3538. return this._gl.RGB9_E5;
  3539. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3540. return this._gl.RGBA4;
  3541. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3542. return this._gl.RGB5_A1;
  3543. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  3544. switch (format) {
  3545. case Constants.TEXTUREFORMAT_RGBA:
  3546. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  3547. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3548. return this._gl.RGB10_A2UI;
  3549. default:
  3550. return this._gl.RGB10_A2;
  3551. }
  3552. }
  3553. return this._gl.RGBA8;
  3554. }
  3555. /** @hidden */
  3556. public _getRGBAMultiSampleBufferFormat(type: number): number {
  3557. if (type === Constants.TEXTURETYPE_FLOAT) {
  3558. return this._gl.RGBA32F;
  3559. }
  3560. else if (type === Constants.TEXTURETYPE_HALF_FLOAT) {
  3561. return this._gl.RGBA16F;
  3562. }
  3563. return this._gl.RGBA8;
  3564. }
  3565. /** @hidden */
  3566. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void,
  3567. offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: IWebRequest, exception?: any) => void): IFileRequest {
  3568. let request = FileTools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  3569. this._activeRequests.push(request);
  3570. request.onCompleteObservable.add((request) => {
  3571. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  3572. });
  3573. return request;
  3574. }
  3575. // Statics
  3576. /**
  3577. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  3578. * @returns true if the engine can be created
  3579. * @ignorenaming
  3580. */
  3581. public static isSupported(): boolean {
  3582. try {
  3583. var tempcanvas = document.createElement("canvas");
  3584. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3585. return gl != null && !!window.WebGLRenderingContext;
  3586. } catch (e) {
  3587. return false;
  3588. }
  3589. }
  3590. /**
  3591. * Find the next highest power of two.
  3592. * @param x Number to start search from.
  3593. * @return Next highest power of two.
  3594. */
  3595. public static CeilingPOT(x: number): number {
  3596. x--;
  3597. x |= x >> 1;
  3598. x |= x >> 2;
  3599. x |= x >> 4;
  3600. x |= x >> 8;
  3601. x |= x >> 16;
  3602. x++;
  3603. return x;
  3604. }
  3605. /**
  3606. * Find the next lowest power of two.
  3607. * @param x Number to start search from.
  3608. * @return Next lowest power of two.
  3609. */
  3610. public static FloorPOT(x: number): number {
  3611. x = x | (x >> 1);
  3612. x = x | (x >> 2);
  3613. x = x | (x >> 4);
  3614. x = x | (x >> 8);
  3615. x = x | (x >> 16);
  3616. return x - (x >> 1);
  3617. }
  3618. /**
  3619. * Find the nearest power of two.
  3620. * @param x Number to start search from.
  3621. * @return Next nearest power of two.
  3622. */
  3623. public static NearestPOT(x: number): number {
  3624. var c = ThinEngine.CeilingPOT(x);
  3625. var f = ThinEngine.FloorPOT(x);
  3626. return (c - x) > (x - f) ? f : c;
  3627. }
  3628. /**
  3629. * Get the closest exponent of two
  3630. * @param value defines the value to approximate
  3631. * @param max defines the maximum value to return
  3632. * @param mode defines how to define the closest value
  3633. * @returns closest exponent of two of the given value
  3634. */
  3635. public static GetExponentOfTwo(value: number, max: number, mode = Constants.SCALEMODE_NEAREST): number {
  3636. let pot;
  3637. switch (mode) {
  3638. case Constants.SCALEMODE_FLOOR:
  3639. pot = ThinEngine.FloorPOT(value);
  3640. break;
  3641. case Constants.SCALEMODE_NEAREST:
  3642. pot = ThinEngine.NearestPOT(value);
  3643. break;
  3644. case Constants.SCALEMODE_CEILING:
  3645. default:
  3646. pot = ThinEngine.CeilingPOT(value);
  3647. break;
  3648. }
  3649. return Math.min(pot, max);
  3650. }
  3651. /**
  3652. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  3653. * @param func - the function to be called
  3654. * @param requester - the object that will request the next frame. Falls back to window.
  3655. * @returns frame number
  3656. */
  3657. public static QueueNewFrame(func: () => void, requester?: any): number {
  3658. if (!DomManagement.IsWindowObjectExist()) {
  3659. return setTimeout(func, 16);
  3660. }
  3661. if (!requester) {
  3662. requester = window;
  3663. }
  3664. if (requester.requestAnimationFrame) {
  3665. return requester.requestAnimationFrame(func);
  3666. }
  3667. else if (requester.msRequestAnimationFrame) {
  3668. return requester.msRequestAnimationFrame(func);
  3669. }
  3670. else if (requester.webkitRequestAnimationFrame) {
  3671. return requester.webkitRequestAnimationFrame(func);
  3672. }
  3673. else if (requester.mozRequestAnimationFrame) {
  3674. return requester.mozRequestAnimationFrame(func);
  3675. }
  3676. else if (requester.oRequestAnimationFrame) {
  3677. return requester.oRequestAnimationFrame(func);
  3678. }
  3679. else {
  3680. return window.setTimeout(func, 16);
  3681. }
  3682. }
  3683. }