thinEngine.ts 188 KB

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