thinEngine.ts 174 KB

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