thinEngine.ts 165 KB

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