thinEngine.ts 180 KB

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