thinEngine.ts 186 KB

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