thinEngine.ts 176 KB

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