thinEngine.ts 175 KB

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