thinEngine.ts 175 KB

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