babylon.scene.ts 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. export interface IActiveMeshCandidateProvider {
  6. getMeshes(scene: Scene): AbstractMesh[];
  7. readonly checksIsEnabled: boolean; // Indicates if the meshes have been checked to make sure they are isEnabled().
  8. }
  9. class ClickInfo {
  10. private _singleClick = false;
  11. private _doubleClick = false;
  12. private _hasSwiped = false;
  13. private _ignore = false;
  14. public get singleClick(): boolean {
  15. return this._singleClick;
  16. }
  17. public get doubleClick(): boolean {
  18. return this._doubleClick;
  19. }
  20. public get hasSwiped(): boolean {
  21. return this._hasSwiped;
  22. }
  23. public get ignore(): boolean {
  24. return this._ignore;
  25. }
  26. public set singleClick(b: boolean) {
  27. this._singleClick = b;
  28. }
  29. public set doubleClick(b: boolean) {
  30. this._doubleClick = b;
  31. }
  32. public set hasSwiped(b: boolean) {
  33. this._hasSwiped = b;
  34. }
  35. public set ignore(b: boolean) {
  36. this._ignore = b;
  37. }
  38. }
  39. /**
  40. * This class is used by the onRenderingGroupObservable
  41. */
  42. export class RenderingGroupInfo {
  43. /**
  44. * The Scene that being rendered
  45. */
  46. scene: Scene;
  47. /**
  48. * The camera currently used for the rendering pass
  49. */
  50. camera: Nullable<Camera>;
  51. /**
  52. * The ID of the renderingGroup being processed
  53. */
  54. renderingGroupId: number;
  55. /**
  56. * The rendering stage, can be either STAGE_PRECLEAR, STAGE_PREOPAQUE, STAGE_PRETRANSPARENT, STAGE_POSTTRANSPARENT
  57. */
  58. renderStage: number;
  59. /**
  60. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  61. * This stage will be fired no matter what
  62. */
  63. static STAGE_PRECLEAR = 1;
  64. /**
  65. * Called before opaque object are rendered.
  66. * This stage will be fired only if there's 3D Opaque content to render
  67. */
  68. static STAGE_PREOPAQUE = 2;
  69. /**
  70. * Called after the opaque objects are rendered and before the transparent ones
  71. * This stage will be fired only if there's 3D transparent content to render
  72. */
  73. static STAGE_PRETRANSPARENT = 3;
  74. /**
  75. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  76. * This stage will be fired no matter what
  77. */
  78. static STAGE_POSTTRANSPARENT = 4;
  79. }
  80. /**
  81. * Represents a scene to be rendered by the engine.
  82. * @see http://doc.babylonjs.com/page.php?p=21911
  83. */
  84. export class Scene implements IAnimatable {
  85. // Statics
  86. private static _FOGMODE_NONE = 0;
  87. private static _FOGMODE_EXP = 1;
  88. private static _FOGMODE_EXP2 = 2;
  89. private static _FOGMODE_LINEAR = 3;
  90. private static _uniqueIdCounter = 0;
  91. public static MinDeltaTime = 1.0;
  92. public static MaxDeltaTime = 1000.0;
  93. /** The fog is deactivated */
  94. public static get FOGMODE_NONE(): number {
  95. return Scene._FOGMODE_NONE;
  96. }
  97. /** The fog density is following an exponential function */
  98. public static get FOGMODE_EXP(): number {
  99. return Scene._FOGMODE_EXP;
  100. }
  101. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  102. public static get FOGMODE_EXP2(): number {
  103. return Scene._FOGMODE_EXP2;
  104. }
  105. /** The fog density is following a linear function. */
  106. public static get FOGMODE_LINEAR(): number {
  107. return Scene._FOGMODE_LINEAR;
  108. }
  109. // Members
  110. public autoClear = true;
  111. public autoClearDepthAndStencil = true;
  112. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  113. public ambientColor = new Color3(0, 0, 0);
  114. public _environmentBRDFTexture: BaseTexture;
  115. protected _environmentTexture: BaseTexture;
  116. /**
  117. * Texture used in all pbr material as the reflection texture.
  118. * As in the majority of the scene they are the same (exception for multi room and so on),
  119. * this is easier to reference from here than from all the materials.
  120. */
  121. public get environmentTexture(): BaseTexture {
  122. return this._environmentTexture;
  123. }
  124. /**
  125. * Texture used in all pbr material as the reflection texture.
  126. * As in the majority of the scene they are the same (exception for multi room and so on),
  127. * this is easier to set here than in all the materials.
  128. */
  129. public set environmentTexture(value: BaseTexture) {
  130. if (this._environmentTexture === value) {
  131. return;
  132. }
  133. this._environmentTexture = value;
  134. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  135. }
  136. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  137. /**
  138. * Default image processing configuration used either in the rendering
  139. * Forward main pass or through the imageProcessingPostProcess if present.
  140. * As in the majority of the scene they are the same (exception for multi camera),
  141. * this is easier to reference from here than from all the materials and post process.
  142. *
  143. * No setter as we it is a shared configuration, you can set the values instead.
  144. */
  145. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  146. return this._imageProcessingConfiguration;
  147. }
  148. public forceWireframe = false;
  149. private _forcePointsCloud = false;
  150. public set forcePointsCloud(value: boolean) {
  151. if (this._forcePointsCloud === value) {
  152. return;
  153. }
  154. this._forcePointsCloud = value;
  155. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  156. }
  157. public get forcePointsCloud(): boolean {
  158. return this._forcePointsCloud;
  159. }
  160. public forceShowBoundingBoxes = false;
  161. public clipPlane: Nullable<Plane>;
  162. public animationsEnabled = true;
  163. public useConstantAnimationDeltaTime = false;
  164. public constantlyUpdateMeshUnderPointer = false;
  165. public hoverCursor = "pointer";
  166. public defaultCursor: string = "";
  167. /**
  168. * This is used to call preventDefault() on pointer down
  169. * in order to block unwanted artifacts like system double clicks
  170. */
  171. public preventDefaultOnPointerDown = true;
  172. // Metadata
  173. public metadata: any = null;
  174. public loadingPluginName: string;
  175. // Events
  176. private _spritePredicate: (sprite: Sprite) => boolean;
  177. /**
  178. * An event triggered when the scene is disposed.
  179. * @type {BABYLON.Observable}
  180. */
  181. public onDisposeObservable = new Observable<Scene>();
  182. private _onDisposeObserver: Nullable<Observer<Scene>>;
  183. /** A function to be executed when this scene is disposed. */
  184. public set onDispose(callback: () => void) {
  185. if (this._onDisposeObserver) {
  186. this.onDisposeObservable.remove(this._onDisposeObserver);
  187. }
  188. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  189. }
  190. /**
  191. * An event triggered before rendering the scene (right after animations and physics)
  192. * @type {BABYLON.Observable}
  193. */
  194. public onBeforeRenderObservable = new Observable<Scene>();
  195. private _onBeforeRenderObserver: Nullable<Observer<Scene>>;
  196. /** A function to be executed before rendering this scene */
  197. public set beforeRender(callback: Nullable<() => void>) {
  198. if (this._onBeforeRenderObserver) {
  199. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  200. }
  201. if (callback) {
  202. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  203. }
  204. }
  205. /**
  206. * An event triggered after rendering the scene
  207. * @type {BABYLON.Observable}
  208. */
  209. public onAfterRenderObservable = new Observable<Scene>();
  210. private _onAfterRenderObserver: Nullable<Observer<Scene>>;
  211. /** A function to be executed after rendering this scene */
  212. public set afterRender(callback: Nullable<() => void>) {
  213. if (this._onAfterRenderObserver) {
  214. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  215. }
  216. if (callback) {
  217. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  218. }
  219. }
  220. /**
  221. * An event triggered before animating the scene
  222. * @type {BABYLON.Observable}
  223. */
  224. public onBeforeAnimationsObservable = new Observable<Scene>();
  225. /**
  226. * An event triggered after animations processing
  227. * @type {BABYLON.Observable}
  228. */
  229. public onAfterAnimationsObservable = new Observable<Scene>();
  230. /**
  231. * An event triggered before draw calls are ready to be sent
  232. * @type {BABYLON.Observable}
  233. */
  234. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  235. /**
  236. * An event triggered after draw calls have been sent
  237. * @type {BABYLON.Observable}
  238. */
  239. public onAfterDrawPhaseObservable = new Observable<Scene>();
  240. /**
  241. * An event triggered when physic simulation is about to be run
  242. * @type {BABYLON.Observable}
  243. */
  244. public onBeforePhysicsObservable = new Observable<Scene>();
  245. /**
  246. * An event triggered when physic simulation has been done
  247. * @type {BABYLON.Observable}
  248. */
  249. public onAfterPhysicsObservable = new Observable<Scene>();
  250. /**
  251. * An event triggered when the scene is ready
  252. * @type {BABYLON.Observable}
  253. */
  254. public onReadyObservable = new Observable<Scene>();
  255. /**
  256. * An event triggered before rendering a camera
  257. * @type {BABYLON.Observable}
  258. */
  259. public onBeforeCameraRenderObservable = new Observable<Camera>();
  260. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>>;
  261. public set beforeCameraRender(callback: () => void) {
  262. if (this._onBeforeCameraRenderObserver) {
  263. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  264. }
  265. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  266. }
  267. /**
  268. * An event triggered after rendering a camera
  269. * @type {BABYLON.Observable}
  270. */
  271. public onAfterCameraRenderObservable = new Observable<Camera>();
  272. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>>;
  273. public set afterCameraRender(callback: () => void) {
  274. if (this._onAfterCameraRenderObserver) {
  275. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  276. }
  277. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  278. }
  279. /**
  280. * An event triggered when active meshes evaluation is about to start
  281. * @type {BABYLON.Observable}
  282. */
  283. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  284. /**
  285. * An event triggered when active meshes evaluation is done
  286. * @type {BABYLON.Observable}
  287. */
  288. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  289. /**
  290. * An event triggered when particles rendering is about to start
  291. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  292. * @type {BABYLON.Observable}
  293. */
  294. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  295. /**
  296. * An event triggered when particles rendering is done
  297. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  298. * @type {BABYLON.Observable}
  299. */
  300. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  301. /**
  302. * An event triggered when sprites rendering is about to start
  303. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  304. * @type {BABYLON.Observable}
  305. */
  306. public onBeforeSpritesRenderingObservable = new Observable<Scene>();
  307. /**
  308. * An event triggered when sprites rendering is done
  309. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  310. * @type {BABYLON.Observable}
  311. */
  312. public onAfterSpritesRenderingObservable = new Observable<Scene>();
  313. /**
  314. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  315. * @type {BABYLON.Observable}
  316. */
  317. public onDataLoadedObservable = new Observable<Scene>();
  318. /**
  319. * An event triggered when a camera is created
  320. * @type {BABYLON.Observable}
  321. */
  322. public onNewCameraAddedObservable = new Observable<Camera>();
  323. /**
  324. * An event triggered when a camera is removed
  325. * @type {BABYLON.Observable}
  326. */
  327. public onCameraRemovedObservable = new Observable<Camera>();
  328. /**
  329. * An event triggered when a light is created
  330. * @type {BABYLON.Observable}
  331. */
  332. public onNewLightAddedObservable = new Observable<Light>();
  333. /**
  334. * An event triggered when a light is removed
  335. * @type {BABYLON.Observable}
  336. */
  337. public onLightRemovedObservable = new Observable<Light>();
  338. /**
  339. * An event triggered when a geometry is created
  340. * @type {BABYLON.Observable}
  341. */
  342. public onNewGeometryAddedObservable = new Observable<Geometry>();
  343. /**
  344. * An event triggered when a geometry is removed
  345. * @type {BABYLON.Observable}
  346. */
  347. public onGeometryRemovedObservable = new Observable<Geometry>();
  348. /**
  349. * An event triggered when a transform node is created
  350. * @type {BABYLON.Observable}
  351. */
  352. public onNewTransformNodeAddedObservable = new Observable<TransformNode>();
  353. /**
  354. * An event triggered when a transform node is removed
  355. * @type {BABYLON.Observable}
  356. */
  357. public onTransformNodeRemovedObservable = new Observable<TransformNode>();
  358. /**
  359. * An event triggered when a mesh is created
  360. * @type {BABYLON.Observable}
  361. */
  362. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  363. /**
  364. * An event triggered when a mesh is removed
  365. * @type {BABYLON.Observable}
  366. */
  367. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  368. /**
  369. * An event triggered when render targets are about to be rendered
  370. * Can happen multiple times per frame.
  371. * @type {BABYLON.Observable}
  372. */
  373. public OnBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  374. /**
  375. * An event triggered when render targets were rendered.
  376. * Can happen multiple times per frame.
  377. * @type {BABYLON.Observable}
  378. */
  379. public OnAfterRenderTargetsRenderObservable = new Observable<Scene>();
  380. /**
  381. * An event triggered before calculating deterministic simulation step
  382. * @type {BABYLON.Observable}
  383. */
  384. public onBeforeStepObservable = new Observable<Scene>();
  385. /**
  386. * An event triggered after calculating deterministic simulation step
  387. * @type {BABYLON.Observable}
  388. */
  389. public onAfterStepObservable = new Observable<Scene>();
  390. /**
  391. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  392. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  393. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  394. */
  395. public onRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  396. // Animations
  397. public animations: Animation[] = [];
  398. // Pointers
  399. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  400. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  401. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  402. private _onPointerMove: (evt: PointerEvent) => void;
  403. private _onPointerDown: (evt: PointerEvent) => void;
  404. private _onPointerUp: (evt: PointerEvent) => void;
  405. /** Deprecated. Use onPointerObservable instead */
  406. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  407. /** Deprecated. Use onPointerObservable instead */
  408. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  409. /** Deprecated. Use onPointerObservable instead */
  410. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>) => void;
  411. /** Deprecated. Use onPointerObservable instead */
  412. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  413. // Gamepads
  414. private _gamepadManager: Nullable<GamepadManager>;
  415. public get gamepadManager(): GamepadManager {
  416. if (!this._gamepadManager) {
  417. this._gamepadManager = new GamepadManager(this);
  418. }
  419. return this._gamepadManager;
  420. }
  421. /**
  422. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  423. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  424. */
  425. public onPrePointerObservable = new Observable<PointerInfoPre>();
  426. /**
  427. * Observable event triggered each time an input event is received from the rendering canvas
  428. */
  429. public onPointerObservable = new Observable<PointerInfo>();
  430. public get unTranslatedPointer(): Vector2 {
  431. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  432. }
  433. /** The distance in pixel that you have to move to prevent some events */
  434. public static DragMovementThreshold = 10; // in pixels
  435. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  436. public static LongPressDelay = 500; // in milliseconds
  437. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  438. public static DoubleClickDelay = 300; // in milliseconds
  439. /** If you need to check double click without raising a single click at first click, enable this flag */
  440. public static ExclusiveDoubleClickMode = false;
  441. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  442. private _initActionManager: (act: Nullable<ActionManager>, clickInfo: ClickInfo) => Nullable<ActionManager>;
  443. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  444. private _delayedSimpleClickTimeout: number;
  445. private _previousDelayedSimpleClickTimeout: number;
  446. private _meshPickProceed = false;
  447. private _previousButtonPressed: number;
  448. private _currentPickResult: Nullable<PickingInfo> = null;
  449. private _previousPickResult: Nullable<PickingInfo> = null;
  450. private _totalPointersPressed = 0;
  451. private _doubleClickOccured = false;
  452. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  453. public cameraToUseForPointers: Nullable<Camera> = null;
  454. private _pointerX: number;
  455. private _pointerY: number;
  456. private _unTranslatedPointerX: number;
  457. private _unTranslatedPointerY: number;
  458. private _startingPointerPosition = new Vector2(0, 0);
  459. private _previousStartingPointerPosition = new Vector2(0, 0);
  460. private _startingPointerTime = 0;
  461. private _previousStartingPointerTime = 0;
  462. // Deterministic lockstep
  463. private _timeAccumulator: number = 0;
  464. private _currentStepId: number = 0;
  465. private _currentInternalStep: number = 0;
  466. // Mirror
  467. public _mirroredCameraPosition: Nullable<Vector3>;
  468. // Keyboard
  469. /**
  470. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  471. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  472. */
  473. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  474. /**
  475. * Observable event triggered each time an keyboard event is received from the hosting window
  476. */
  477. public onKeyboardObservable = new Observable<KeyboardInfo>();
  478. private _onKeyDown: (evt: KeyboardEvent) => void;
  479. private _onKeyUp: (evt: KeyboardEvent) => void;
  480. private _onCanvasFocusObserver: Nullable<Observer<Engine>>;
  481. private _onCanvasBlurObserver: Nullable<Observer<Engine>>;
  482. // Coordinate system
  483. /**
  484. * use right-handed coordinate system on this scene.
  485. * @type {boolean}
  486. */
  487. private _useRightHandedSystem = false;
  488. public set useRightHandedSystem(value: boolean) {
  489. if (this._useRightHandedSystem === value) {
  490. return;
  491. }
  492. this._useRightHandedSystem = value;
  493. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  494. }
  495. public get useRightHandedSystem(): boolean {
  496. return this._useRightHandedSystem;
  497. }
  498. public setStepId(newStepId: number): void {
  499. this._currentStepId = newStepId;
  500. };
  501. public getStepId(): number {
  502. return this._currentStepId;
  503. };
  504. public getInternalStep(): number {
  505. return this._currentInternalStep;
  506. };
  507. // Fog
  508. private _fogEnabled = true;
  509. /**
  510. * is fog enabled on this scene.
  511. */
  512. public set fogEnabled(value: boolean) {
  513. if (this._fogEnabled === value) {
  514. return;
  515. }
  516. this._fogEnabled = value;
  517. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  518. }
  519. public get fogEnabled(): boolean {
  520. return this._fogEnabled;
  521. }
  522. private _fogMode = Scene.FOGMODE_NONE;
  523. public set fogMode(value: number) {
  524. if (this._fogMode === value) {
  525. return;
  526. }
  527. this._fogMode = value;
  528. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  529. }
  530. public get fogMode(): number {
  531. return this._fogMode;
  532. }
  533. public fogColor = new Color3(0.2, 0.2, 0.3);
  534. public fogDensity = 0.1;
  535. public fogStart = 0;
  536. public fogEnd = 1000.0;
  537. // Lights
  538. /**
  539. * is shadow enabled on this scene.
  540. * @type {boolean}
  541. */
  542. private _shadowsEnabled = true;
  543. public set shadowsEnabled(value: boolean) {
  544. if (this._shadowsEnabled === value) {
  545. return;
  546. }
  547. this._shadowsEnabled = value;
  548. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  549. }
  550. public get shadowsEnabled(): boolean {
  551. return this._shadowsEnabled;
  552. }
  553. /**
  554. * is light enabled on this scene.
  555. * @type {boolean}
  556. */
  557. private _lightsEnabled = true;
  558. public set lightsEnabled(value: boolean) {
  559. if (this._lightsEnabled === value) {
  560. return;
  561. }
  562. this._lightsEnabled = value;
  563. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  564. }
  565. public get lightsEnabled(): boolean {
  566. return this._lightsEnabled;
  567. }
  568. /**
  569. * All of the lights added to this scene.
  570. * @see BABYLON.Light
  571. * @type {BABYLON.Light[]}
  572. */
  573. public lights = new Array<Light>();
  574. // Cameras
  575. /** All of the cameras added to this scene. */
  576. public cameras = new Array<Camera>();
  577. /** All of the active cameras added to this scene. */
  578. public activeCameras = new Array<Camera>();
  579. /** The current active camera */
  580. public activeCamera: Nullable<Camera>;
  581. // Meshes
  582. /**
  583. * All of the tranform nodes added to this scene.
  584. * @see BABYLON.TransformNode
  585. * @type {BABYLON.TransformNode[]}
  586. */
  587. public transformNodes = new Array<TransformNode>();
  588. /**
  589. * All of the (abstract) meshes added to this scene.
  590. * @see BABYLON.AbstractMesh
  591. * @type {BABYLON.AbstractMesh[]}
  592. */
  593. public meshes = new Array<AbstractMesh>();
  594. /**
  595. * All of the animation groups added to this scene.
  596. * @see BABYLON.AnimationGroup
  597. * @type {BABYLON.AnimationGroup[]}
  598. */
  599. public animationGroups = new Array<AnimationGroup>();
  600. // Geometries
  601. private _geometries = new Array<Geometry>();
  602. public materials = new Array<Material>();
  603. public multiMaterials = new Array<MultiMaterial>();
  604. private _defaultMaterial: Material;
  605. /** The default material used on meshes when no material is affected */
  606. public get defaultMaterial(): Material {
  607. if (!this._defaultMaterial) {
  608. this._defaultMaterial = new StandardMaterial("default material", this);
  609. }
  610. return this._defaultMaterial;
  611. }
  612. /** The default material used on meshes when no material is affected */
  613. public set defaultMaterial(value: Material) {
  614. this._defaultMaterial = value;
  615. }
  616. // Textures
  617. private _texturesEnabled = true;
  618. public set texturesEnabled(value: boolean) {
  619. if (this._texturesEnabled === value) {
  620. return;
  621. }
  622. this._texturesEnabled = value;
  623. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  624. }
  625. public get texturesEnabled(): boolean {
  626. return this._texturesEnabled;
  627. }
  628. public textures = new Array<BaseTexture>();
  629. // Particles
  630. public particlesEnabled = true;
  631. public particleSystems = new Array<IParticleSystem>();
  632. // Sprites
  633. public spritesEnabled = true;
  634. public spriteManagers = new Array<SpriteManager>();
  635. // Layers
  636. public layers = new Array<Layer>();
  637. public highlightLayers = new Array<HighlightLayer>();
  638. // Skeletons
  639. private _skeletonsEnabled = true;
  640. public set skeletonsEnabled(value: boolean) {
  641. if (this._skeletonsEnabled === value) {
  642. return;
  643. }
  644. this._skeletonsEnabled = value;
  645. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  646. }
  647. public get skeletonsEnabled(): boolean {
  648. return this._skeletonsEnabled;
  649. }
  650. public skeletons = new Array<Skeleton>();
  651. // Morph targets
  652. public morphTargetManagers = new Array<MorphTargetManager>();
  653. // Lens flares
  654. public lensFlaresEnabled = true;
  655. public lensFlareSystems = new Array<LensFlareSystem>();
  656. // Collisions
  657. public collisionsEnabled = true;
  658. private _workerCollisions: boolean;
  659. public collisionCoordinator: ICollisionCoordinator;
  660. /** Defines the gravity applied to this scene */
  661. public gravity = new Vector3(0, -9.807, 0);
  662. // Postprocesses
  663. public postProcesses = new Array<PostProcess>();
  664. public postProcessesEnabled = true;
  665. public postProcessManager: PostProcessManager;
  666. private _postProcessRenderPipelineManager: PostProcessRenderPipelineManager
  667. public get postProcessRenderPipelineManager(): PostProcessRenderPipelineManager {
  668. if (!this._postProcessRenderPipelineManager) {
  669. this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  670. }
  671. return this._postProcessRenderPipelineManager;
  672. }
  673. // Customs render targets
  674. public renderTargetsEnabled = true;
  675. public dumpNextRenderTargets = false;
  676. public customRenderTargets = new Array<RenderTargetTexture>();
  677. // Delay loading
  678. public useDelayedTextureLoading: boolean;
  679. // Imported meshes
  680. public importedMeshesFiles = new Array<String>();
  681. // Probes
  682. public probesEnabled = true;
  683. public reflectionProbes = new Array<ReflectionProbe>();
  684. // Database
  685. public database: Database;
  686. /**
  687. * This scene's action manager
  688. * @type {BABYLON.ActionManager}
  689. */
  690. public actionManager: ActionManager;
  691. public _actionManagers = new Array<ActionManager>();
  692. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  693. // Procedural textures
  694. public proceduralTexturesEnabled = true;
  695. public _proceduralTextures = new Array<ProceduralTexture>();
  696. // Sound Tracks
  697. private _mainSoundTrack: SoundTrack;
  698. public soundTracks = new Array<SoundTrack>();
  699. private _audioEnabled = true;
  700. private _headphone = false;
  701. public get mainSoundTrack(): SoundTrack {
  702. if (!this._mainSoundTrack) {
  703. this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  704. }
  705. return this._mainSoundTrack;
  706. }
  707. // VR Helper
  708. public VRHelper: VRExperienceHelper;
  709. //Simplification Queue
  710. public simplificationQueue: SimplificationQueue;
  711. // Private
  712. private _engine: Engine;
  713. // Performance counters
  714. private _totalVertices = new PerfCounter();
  715. public _activeIndices = new PerfCounter();
  716. public _activeParticles = new PerfCounter();
  717. public _activeBones = new PerfCounter();
  718. private _animationRatio: number;
  719. private _animationTimeLast: number;
  720. private _animationTime: number = 0;
  721. public animationTimeScale: number = 1;
  722. public _cachedMaterial: Nullable<Material>;
  723. public _cachedEffect: Nullable<Effect>;
  724. public _cachedVisibility: Nullable<number>;
  725. private _renderId = 0;
  726. private _executeWhenReadyTimeoutId = -1;
  727. private _intermediateRendering = false;
  728. private _viewUpdateFlag = -1;
  729. private _projectionUpdateFlag = -1;
  730. private _alternateViewUpdateFlag = -1;
  731. private _alternateProjectionUpdateFlag = -1;
  732. public _toBeDisposed = new SmartArray<Nullable<IDisposable>>(256);
  733. private _activeRequests = new Array<IFileRequest>();
  734. private _pendingData = new Array();
  735. private _isDisposed = false;
  736. public dispatchAllSubMeshesOfActiveMeshes:boolean = false;
  737. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  738. private _processedMaterials = new SmartArray<Material>(256);
  739. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  740. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  741. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  742. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  743. private _renderingManager: RenderingManager;
  744. private _physicsEngine: Nullable<PhysicsEngine>;
  745. public _activeAnimatables = new Array<Animatable>();
  746. private _transformMatrix = Matrix.Zero();
  747. private _sceneUbo: UniformBuffer;
  748. private _alternateSceneUbo: UniformBuffer;
  749. private _pickWithRayInverseMatrix: Matrix;
  750. private _boundingBoxRenderer: BoundingBoxRenderer;
  751. private _outlineRenderer: OutlineRenderer;
  752. private _viewMatrix: Matrix;
  753. private _projectionMatrix: Matrix;
  754. private _alternateViewMatrix: Matrix;
  755. private _alternateProjectionMatrix: Matrix;
  756. private _alternateTransformMatrix: Matrix;
  757. private _useAlternateCameraConfiguration = false;
  758. private _alternateRendering = false;
  759. public _forcedViewPosition: Nullable<Vector3>;
  760. public get _isAlternateRenderingEnabled(): boolean {
  761. return this._alternateRendering;
  762. }
  763. private _frustumPlanes: Plane[];
  764. public get frustumPlanes(): Plane[] {
  765. return this._frustumPlanes;
  766. }
  767. public requireLightSorting = false;
  768. private _selectionOctree: Octree<AbstractMesh>;
  769. private _pointerOverMesh: Nullable<AbstractMesh>;
  770. private _pointerOverSprite: Nullable<Sprite>;
  771. private _debugLayer: DebugLayer;
  772. private _depthRenderer: Nullable<DepthRenderer>;
  773. private _geometryBufferRenderer: Nullable<GeometryBufferRenderer>;
  774. public get geometryBufferRenderer(): Nullable<GeometryBufferRenderer> {
  775. return this._geometryBufferRenderer;
  776. }
  777. public set geometryBufferRenderer(geometryBufferRenderer: Nullable<GeometryBufferRenderer>) {
  778. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  779. this._geometryBufferRenderer = geometryBufferRenderer;
  780. }
  781. }
  782. private _pickedDownMesh: Nullable<AbstractMesh>;
  783. private _pickedUpMesh: Nullable<AbstractMesh>;
  784. private _pickedDownSprite: Nullable<Sprite>;
  785. private _externalData: StringDictionary<Object>;
  786. private _uid: Nullable<string>;
  787. /**
  788. * @constructor
  789. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  790. */
  791. constructor(engine: Engine) {
  792. this._engine = engine || Engine.LastCreatedEngine;
  793. this._engine.scenes.push(this);
  794. this._uid = null;
  795. this._renderingManager = new RenderingManager(this);
  796. this.postProcessManager = new PostProcessManager(this);
  797. if (OutlineRenderer) {
  798. this._outlineRenderer = new OutlineRenderer(this);
  799. }
  800. if (Tools.IsWindowObjectExist()) {
  801. this.attachControl();
  802. }
  803. //simplification queue
  804. if (SimplificationQueue) {
  805. this.simplificationQueue = new SimplificationQueue();
  806. }
  807. //collision coordinator initialization. For now legacy per default.
  808. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  809. // Uniform Buffer
  810. this._createUbo();
  811. // Default Image processing definition.
  812. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  813. }
  814. // Properties
  815. public get debugLayer(): DebugLayer {
  816. if (!this._debugLayer) {
  817. this._debugLayer = new DebugLayer(this);
  818. }
  819. return this._debugLayer;
  820. }
  821. public set workerCollisions(enabled: boolean) {
  822. if (!CollisionCoordinatorLegacy) {
  823. return;
  824. }
  825. enabled = (enabled && !!Worker);
  826. this._workerCollisions = enabled;
  827. if (this.collisionCoordinator) {
  828. this.collisionCoordinator.destroy();
  829. }
  830. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  831. this.collisionCoordinator.init(this);
  832. }
  833. public get workerCollisions(): boolean {
  834. return this._workerCollisions;
  835. }
  836. public get selectionOctree(): Octree<AbstractMesh> {
  837. return this._selectionOctree;
  838. }
  839. /**
  840. * The mesh that is currently under the pointer.
  841. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  842. */
  843. public get meshUnderPointer(): Nullable<AbstractMesh> {
  844. return this._pointerOverMesh;
  845. }
  846. /**
  847. * Current on-screen X position of the pointer
  848. * @return {number} X position of the pointer
  849. */
  850. public get pointerX(): number {
  851. return this._pointerX;
  852. }
  853. /**
  854. * Current on-screen Y position of the pointer
  855. * @return {number} Y position of the pointer
  856. */
  857. public get pointerY(): number {
  858. return this._pointerY;
  859. }
  860. public getCachedMaterial(): Nullable<Material> {
  861. return this._cachedMaterial;
  862. }
  863. public getCachedEffect(): Nullable<Effect> {
  864. return this._cachedEffect;
  865. }
  866. public getCachedVisibility(): Nullable<number> {
  867. return this._cachedVisibility;
  868. }
  869. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  870. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  871. }
  872. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  873. if (!this._boundingBoxRenderer) {
  874. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  875. }
  876. return this._boundingBoxRenderer;
  877. }
  878. public getOutlineRenderer(): OutlineRenderer {
  879. return this._outlineRenderer;
  880. }
  881. public getEngine(): Engine {
  882. return this._engine;
  883. }
  884. public getTotalVertices(): number {
  885. return this._totalVertices.current;
  886. }
  887. public get totalVerticesPerfCounter(): PerfCounter {
  888. return this._totalVertices;
  889. }
  890. public getActiveIndices(): number {
  891. return this._activeIndices.current;
  892. }
  893. public get totalActiveIndicesPerfCounter(): PerfCounter {
  894. return this._activeIndices;
  895. }
  896. public getActiveParticles(): number {
  897. return this._activeParticles.current;
  898. }
  899. public get activeParticlesPerfCounter(): PerfCounter {
  900. return this._activeParticles;
  901. }
  902. public getActiveBones(): number {
  903. return this._activeBones.current;
  904. }
  905. public get activeBonesPerfCounter(): PerfCounter {
  906. return this._activeBones;
  907. }
  908. // Stats
  909. public getInterFramePerfCounter(): number {
  910. Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  911. return 0;
  912. }
  913. public get interFramePerfCounter(): Nullable<PerfCounter> {
  914. Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  915. return null;
  916. }
  917. public getLastFrameDuration(): number {
  918. Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  919. return 0;
  920. }
  921. public get lastFramePerfCounter(): Nullable<PerfCounter> {
  922. Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  923. return null;
  924. }
  925. public getEvaluateActiveMeshesDuration(): number {
  926. Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  927. return 0;
  928. }
  929. public get evaluateActiveMeshesDurationPerfCounter(): Nullable<PerfCounter> {
  930. Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  931. return null;
  932. }
  933. public getActiveMeshes(): SmartArray<AbstractMesh> {
  934. return this._activeMeshes;
  935. }
  936. public getRenderTargetsDuration(): number {
  937. Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  938. return 0;
  939. }
  940. public getRenderDuration(): number {
  941. Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  942. return 0;
  943. }
  944. public get renderDurationPerfCounter(): Nullable<PerfCounter> {
  945. Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  946. return null;
  947. }
  948. public getParticlesDuration(): number {
  949. Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  950. return 0;
  951. }
  952. public get particlesDurationPerfCounter(): Nullable<PerfCounter> {
  953. Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  954. return null;
  955. }
  956. public getSpritesDuration(): number {
  957. Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  958. return 0;
  959. }
  960. public get spriteDuractionPerfCounter(): Nullable<PerfCounter> {
  961. Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  962. return null;
  963. }
  964. public getAnimationRatio(): number {
  965. return this._animationRatio;
  966. }
  967. public getRenderId(): number {
  968. return this._renderId;
  969. }
  970. public incrementRenderId(): void {
  971. this._renderId++;
  972. }
  973. private _updatePointerPosition(evt: PointerEvent): void {
  974. var canvasRect = this._engine.getRenderingCanvasClientRect();
  975. if (!canvasRect) {
  976. return;
  977. }
  978. this._pointerX = evt.clientX - canvasRect.left;
  979. this._pointerY = evt.clientY - canvasRect.top;
  980. this._unTranslatedPointerX = this._pointerX;
  981. this._unTranslatedPointerY = this._pointerY;
  982. }
  983. private _createUbo(): void {
  984. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  985. this._sceneUbo.addUniform("viewProjection", 16);
  986. this._sceneUbo.addUniform("view", 16);
  987. }
  988. private _createAlternateUbo(): void {
  989. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  990. this._alternateSceneUbo.addUniform("viewProjection", 16);
  991. this._alternateSceneUbo.addUniform("view", 16);
  992. }
  993. // Pointers handling
  994. /**
  995. * Use this method to simulate a pointer move on a mesh
  996. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  997. */
  998. public simulatePointerMove(pickResult: PickingInfo): Scene {
  999. let evt = new PointerEvent("pointermove");
  1000. return this._processPointerMove(pickResult, evt);
  1001. }
  1002. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1003. var canvas = this._engine.getRenderingCanvas();
  1004. if (!canvas) {
  1005. return this;
  1006. }
  1007. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1008. this.setPointerOverSprite(null);
  1009. this.setPointerOverMesh(pickResult.pickedMesh);
  1010. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  1011. if (this._pointerOverMesh.actionManager.hoverCursor) {
  1012. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  1013. } else {
  1014. canvas.style.cursor = this.hoverCursor;
  1015. }
  1016. } else {
  1017. canvas.style.cursor = this.defaultCursor;
  1018. }
  1019. } else {
  1020. this.setPointerOverMesh(null);
  1021. // Sprites
  1022. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1023. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1024. this.setPointerOverSprite(pickResult.pickedSprite);
  1025. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  1026. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  1027. } else {
  1028. canvas.style.cursor = this.hoverCursor;
  1029. }
  1030. } else {
  1031. this.setPointerOverSprite(null);
  1032. // Restore pointer
  1033. canvas.style.cursor = this.defaultCursor;
  1034. }
  1035. }
  1036. if (pickResult) {
  1037. if (this.onPointerMove) {
  1038. this.onPointerMove(evt, pickResult);
  1039. }
  1040. if (this.onPointerObservable.hasObservers()) {
  1041. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1042. let pi = new PointerInfo(type, evt, pickResult);
  1043. this.onPointerObservable.notifyObservers(pi, type);
  1044. }
  1045. }
  1046. return this;
  1047. }
  1048. /**
  1049. * Use this method to simulate a pointer down on a mesh
  1050. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1051. */
  1052. public simulatePointerDown(pickResult: PickingInfo): Scene {
  1053. let evt = new PointerEvent("pointerdown");
  1054. return this._processPointerDown(pickResult, evt);
  1055. }
  1056. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1057. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1058. this._pickedDownMesh = pickResult.pickedMesh;
  1059. var actionManager = pickResult.pickedMesh.actionManager;
  1060. if (actionManager) {
  1061. if (actionManager.hasPickTriggers) {
  1062. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1063. switch (evt.button) {
  1064. case 0:
  1065. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1066. break;
  1067. case 1:
  1068. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1069. break;
  1070. case 2:
  1071. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1072. break;
  1073. }
  1074. }
  1075. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  1076. window.setTimeout(() => {
  1077. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1078. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1079. false, this.cameraToUseForPointers);
  1080. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1081. if (this._totalPointersPressed !== 0 &&
  1082. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1083. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  1084. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  1085. this._startingPointerTime = 0;
  1086. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1087. }
  1088. }
  1089. }, Scene.LongPressDelay);
  1090. }
  1091. }
  1092. }
  1093. if (pickResult) {
  1094. if (this.onPointerDown) {
  1095. this.onPointerDown(evt, pickResult);
  1096. }
  1097. if (this.onPointerObservable.hasObservers()) {
  1098. let type = PointerEventTypes.POINTERDOWN;
  1099. let pi = new PointerInfo(type, evt, pickResult);
  1100. this.onPointerObservable.notifyObservers(pi, type);
  1101. }
  1102. }
  1103. return this;
  1104. }
  1105. /**
  1106. * Use this method to simulate a pointer up on a mesh
  1107. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1108. */
  1109. public simulatePointerUp(pickResult: PickingInfo): Scene {
  1110. let evt = new PointerEvent("pointerup");
  1111. let clickInfo = new ClickInfo();
  1112. clickInfo.singleClick = true;
  1113. clickInfo.ignore = true;
  1114. return this._processPointerUp(pickResult, evt, clickInfo);
  1115. }
  1116. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1117. if (pickResult && pickResult && pickResult.pickedMesh) {
  1118. this._pickedUpMesh = pickResult.pickedMesh;
  1119. if (this._pickedDownMesh === this._pickedUpMesh) {
  1120. if (this.onPointerPick) {
  1121. this.onPointerPick(evt, pickResult);
  1122. }
  1123. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1124. let type = PointerEventTypes.POINTERPICK;
  1125. let pi = new PointerInfo(type, evt, pickResult);
  1126. this.onPointerObservable.notifyObservers(pi, type);
  1127. }
  1128. }
  1129. if (pickResult.pickedMesh.actionManager) {
  1130. if (clickInfo.ignore) {
  1131. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1132. }
  1133. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  1134. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1135. }
  1136. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1137. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1138. }
  1139. }
  1140. }
  1141. if (this._pickedDownMesh &&
  1142. this._pickedDownMesh.actionManager &&
  1143. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  1144. this._pickedDownMesh !== this._pickedUpMesh) {
  1145. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1146. }
  1147. if (this.onPointerUp) {
  1148. this.onPointerUp(evt, pickResult);
  1149. }
  1150. if (this.onPointerObservable.hasObservers()) {
  1151. if (!clickInfo.ignore) {
  1152. if (!clickInfo.hasSwiped) {
  1153. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1154. let type = PointerEventTypes.POINTERTAP;
  1155. let pi = new PointerInfo(type, evt, pickResult);
  1156. this.onPointerObservable.notifyObservers(pi, type);
  1157. }
  1158. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1159. let type = PointerEventTypes.POINTERDOUBLETAP;
  1160. let pi = new PointerInfo(type, evt, pickResult);
  1161. this.onPointerObservable.notifyObservers(pi, type);
  1162. }
  1163. }
  1164. }
  1165. else {
  1166. let type = PointerEventTypes.POINTERUP;
  1167. let pi = new PointerInfo(type, evt, pickResult);
  1168. this.onPointerObservable.notifyObservers(pi, type);
  1169. }
  1170. }
  1171. return this;
  1172. }
  1173. /**
  1174. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1175. * @param attachUp defines if you want to attach events to pointerup
  1176. * @param attachDown defines if you want to attach events to pointerdown
  1177. * @param attachMove defines if you want to attach events to pointermove
  1178. */
  1179. public attachControl(attachUp = true, attachDown = true, attachMove = true) {
  1180. this._initActionManager = (act: Nullable<ActionManager>, clickInfo: ClickInfo): Nullable<ActionManager> => {
  1181. if (!this._meshPickProceed) {
  1182. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1183. this._currentPickResult = pickResult;
  1184. if (pickResult) {
  1185. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1186. }
  1187. this._meshPickProceed = true;
  1188. }
  1189. return act;
  1190. };
  1191. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1192. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1193. if ((new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1194. btn !== this._previousButtonPressed) {
  1195. this._doubleClickOccured = false;
  1196. clickInfo.singleClick = true;
  1197. clickInfo.ignore = false;
  1198. cb(clickInfo, this._currentPickResult);
  1199. }
  1200. }
  1201. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1202. let clickInfo = new ClickInfo();
  1203. this._currentPickResult = null;
  1204. let act: Nullable<ActionManager> = null;
  1205. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1206. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1207. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1208. if (!checkPicking && ActionManager && ActionManager.HasPickTriggers) {
  1209. act = this._initActionManager(act, clickInfo);
  1210. if (act)
  1211. checkPicking = act.hasPickTriggers;
  1212. }
  1213. if (checkPicking) {
  1214. let btn = evt.button;
  1215. clickInfo.hasSwiped = Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1216. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1217. if (!clickInfo.hasSwiped) {
  1218. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1219. if (!checkSingleClickImmediately) {
  1220. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1221. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1222. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1223. act = this._initActionManager(act, clickInfo);
  1224. if (act)
  1225. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1226. }
  1227. }
  1228. if (checkSingleClickImmediately) {
  1229. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1230. if (new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1231. btn !== this._previousButtonPressed) {
  1232. clickInfo.singleClick = true;
  1233. cb(clickInfo, this._currentPickResult);
  1234. }
  1235. }
  1236. // at least one double click is required to be check and exclusive double click is enabled
  1237. else {
  1238. // wait that no double click has been raised during the double click delay
  1239. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1240. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1241. }
  1242. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1243. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1244. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1245. act = this._initActionManager(act, clickInfo);
  1246. if (act)
  1247. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1248. }
  1249. if (checkDoubleClick) {
  1250. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1251. if (btn === this._previousButtonPressed &&
  1252. new Date().getTime() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1253. !this._doubleClickOccured
  1254. ) {
  1255. // pointer has not moved for 2 clicks, it's a double click
  1256. if (!clickInfo.hasSwiped &&
  1257. Math.abs(this._previousStartingPointerPosition.x - this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  1258. Math.abs(this._previousStartingPointerPosition.y - this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  1259. this._previousStartingPointerTime = 0;
  1260. this._doubleClickOccured = true;
  1261. clickInfo.doubleClick = true;
  1262. clickInfo.ignore = false;
  1263. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1264. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1265. }
  1266. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1267. cb(clickInfo, this._currentPickResult);
  1268. }
  1269. // if the two successive clicks are too far, it's just two simple clicks
  1270. else {
  1271. this._doubleClickOccured = false;
  1272. this._previousStartingPointerTime = this._startingPointerTime;
  1273. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1274. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1275. this._previousButtonPressed = btn;
  1276. if (Scene.ExclusiveDoubleClickMode) {
  1277. if (this._previousDelayedSimpleClickTimeout) {
  1278. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1279. }
  1280. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1281. cb(clickInfo, this._previousPickResult);
  1282. }
  1283. else {
  1284. cb(clickInfo, this._currentPickResult);
  1285. }
  1286. }
  1287. }
  1288. // just the first click of the double has been raised
  1289. else {
  1290. this._doubleClickOccured = false;
  1291. this._previousStartingPointerTime = this._startingPointerTime;
  1292. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1293. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1294. this._previousButtonPressed = btn;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. clickInfo.ignore = true;
  1300. cb(clickInfo, this._currentPickResult);
  1301. };
  1302. this._spritePredicate = (sprite: Sprite): boolean => {
  1303. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  1304. };
  1305. this._onPointerMove = (evt: PointerEvent) => {
  1306. this._updatePointerPosition(evt);
  1307. // PreObservable support
  1308. if (this.onPrePointerObservable.hasObservers()) {
  1309. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1310. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1311. this.onPrePointerObservable.notifyObservers(pi, type);
  1312. if (pi.skipOnPointerObservable) {
  1313. return;
  1314. }
  1315. }
  1316. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1317. return;
  1318. }
  1319. if (!this.pointerMovePredicate) {
  1320. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1321. }
  1322. // Meshes
  1323. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1324. this._processPointerMove(pickResult, evt);
  1325. };
  1326. this._onPointerDown = (evt: PointerEvent) => {
  1327. this._totalPointersPressed++;
  1328. this._pickedDownMesh = null;
  1329. this._meshPickProceed = false;
  1330. this._updatePointerPosition(evt);
  1331. if (this.preventDefaultOnPointerDown && canvas) {
  1332. evt.preventDefault();
  1333. canvas.focus();
  1334. }
  1335. // PreObservable support
  1336. if (this.onPrePointerObservable.hasObservers()) {
  1337. let type = PointerEventTypes.POINTERDOWN;
  1338. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1339. this.onPrePointerObservable.notifyObservers(pi, type);
  1340. if (pi.skipOnPointerObservable) {
  1341. return;
  1342. }
  1343. }
  1344. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1345. return;
  1346. }
  1347. this._startingPointerPosition.x = this._pointerX;
  1348. this._startingPointerPosition.y = this._pointerY;
  1349. this._startingPointerTime = new Date().getTime();
  1350. if (!this.pointerDownPredicate) {
  1351. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1352. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1353. };
  1354. }
  1355. // Meshes
  1356. this._pickedDownMesh = null;
  1357. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1358. this._processPointerDown(pickResult, evt);
  1359. // Sprites
  1360. this._pickedDownSprite = null;
  1361. if (this.spriteManagers.length > 0) {
  1362. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1363. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1364. if (pickResult.pickedSprite.actionManager) {
  1365. this._pickedDownSprite = pickResult.pickedSprite;
  1366. switch (evt.button) {
  1367. case 0:
  1368. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1369. break;
  1370. case 1:
  1371. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1372. break;
  1373. case 2:
  1374. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1375. break;
  1376. }
  1377. if (pickResult.pickedSprite.actionManager) {
  1378. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1379. }
  1380. }
  1381. }
  1382. }
  1383. };
  1384. this._onPointerUp = (evt: PointerEvent) => {
  1385. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1386. return; // So we need to test it the pointer down was pressed before.
  1387. }
  1388. this._totalPointersPressed--;
  1389. this._pickedUpMesh = null;
  1390. this._meshPickProceed = false;
  1391. this._updatePointerPosition(evt);
  1392. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1393. // PreObservable support
  1394. if (this.onPrePointerObservable.hasObservers()) {
  1395. if (!clickInfo.ignore) {
  1396. if (!clickInfo.hasSwiped) {
  1397. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1398. let type = PointerEventTypes.POINTERTAP;
  1399. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1400. this.onPrePointerObservable.notifyObservers(pi, type);
  1401. if (pi.skipOnPointerObservable) {
  1402. return;
  1403. }
  1404. }
  1405. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1406. let type = PointerEventTypes.POINTERDOUBLETAP;
  1407. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1408. this.onPrePointerObservable.notifyObservers(pi, type);
  1409. if (pi.skipOnPointerObservable) {
  1410. return;
  1411. }
  1412. }
  1413. }
  1414. }
  1415. else {
  1416. let type = PointerEventTypes.POINTERUP;
  1417. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1418. this.onPrePointerObservable.notifyObservers(pi, type);
  1419. if (pi.skipOnPointerObservable) {
  1420. return;
  1421. }
  1422. }
  1423. }
  1424. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1425. return;
  1426. }
  1427. if (!this.pointerUpPredicate) {
  1428. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1429. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1430. };
  1431. }
  1432. // Meshes
  1433. if (!this._meshPickProceed && (ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1434. this._initActionManager(null, clickInfo);
  1435. }
  1436. if (!pickResult) {
  1437. pickResult = this._currentPickResult;
  1438. }
  1439. this._processPointerUp(pickResult, evt, clickInfo);
  1440. // Sprites
  1441. if (this.spriteManagers.length > 0) {
  1442. let spritePickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1443. if (spritePickResult) {
  1444. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  1445. if (spritePickResult.pickedSprite.actionManager) {
  1446. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1447. if (spritePickResult.pickedSprite.actionManager) {
  1448. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  1449. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1450. }
  1451. }
  1452. }
  1453. }
  1454. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== spritePickResult.pickedSprite) {
  1455. this._pickedDownSprite.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  1456. }
  1457. }
  1458. }
  1459. this._previousPickResult = this._currentPickResult;
  1460. });
  1461. };
  1462. this._onKeyDown = (evt: KeyboardEvent) => {
  1463. let type = KeyboardEventTypes.KEYDOWN;
  1464. if (this.onPreKeyboardObservable.hasObservers()) {
  1465. let pi = new KeyboardInfoPre(type, evt);
  1466. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1467. if (pi.skipOnPointerObservable) {
  1468. return;
  1469. }
  1470. }
  1471. if (this.onKeyboardObservable.hasObservers()) {
  1472. let pi = new KeyboardInfo(type, evt);
  1473. this.onKeyboardObservable.notifyObservers(pi, type);
  1474. }
  1475. if (this.actionManager) {
  1476. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1477. }
  1478. };
  1479. this._onKeyUp = (evt: KeyboardEvent) => {
  1480. let type = KeyboardEventTypes.KEYUP;
  1481. if (this.onPreKeyboardObservable.hasObservers()) {
  1482. let pi = new KeyboardInfoPre(type, evt);
  1483. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1484. if (pi.skipOnPointerObservable) {
  1485. return;
  1486. }
  1487. }
  1488. if (this.onKeyboardObservable.hasObservers()) {
  1489. let pi = new KeyboardInfo(type, evt);
  1490. this.onKeyboardObservable.notifyObservers(pi, type);
  1491. }
  1492. if (this.actionManager) {
  1493. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1494. }
  1495. };
  1496. let engine = this.getEngine();
  1497. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(() => {
  1498. if (!canvas) {
  1499. return;
  1500. }
  1501. canvas.addEventListener("keydown", this._onKeyDown, false);
  1502. canvas.addEventListener("keyup", this._onKeyUp, false);
  1503. });
  1504. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(() => {
  1505. if (!canvas) {
  1506. return;
  1507. }
  1508. canvas.removeEventListener("keydown", this._onKeyDown);
  1509. canvas.removeEventListener("keyup", this._onKeyUp);
  1510. });
  1511. var eventPrefix = Tools.GetPointerPrefix();
  1512. var canvas = this._engine.getRenderingCanvas();
  1513. if (!canvas) {
  1514. return;
  1515. }
  1516. if (attachMove) {
  1517. canvas.addEventListener(eventPrefix + "move", <any>this._onPointerMove, false);
  1518. // Wheel
  1519. canvas.addEventListener('mousewheel', <any>this._onPointerMove, false);
  1520. canvas.addEventListener('DOMMouseScroll', <any>this._onPointerMove, false);
  1521. }
  1522. if (attachDown) {
  1523. canvas.addEventListener(eventPrefix + "down", <any>this._onPointerDown, false);
  1524. }
  1525. if (attachUp) {
  1526. window.addEventListener(eventPrefix + "up", <any>this._onPointerUp, false);
  1527. }
  1528. canvas.tabIndex = 1;
  1529. }
  1530. public detachControl() {
  1531. let engine = this.getEngine();
  1532. var eventPrefix = Tools.GetPointerPrefix();
  1533. var canvas = engine.getRenderingCanvas();
  1534. if (!canvas) {
  1535. return;
  1536. }
  1537. canvas.removeEventListener(eventPrefix + "move", <any>this._onPointerMove);
  1538. canvas.removeEventListener(eventPrefix + "down", <any>this._onPointerDown);
  1539. window.removeEventListener(eventPrefix + "up", <any>this._onPointerUp);
  1540. if (this._onCanvasBlurObserver) {
  1541. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1542. }
  1543. if (this._onCanvasFocusObserver) {
  1544. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1545. }
  1546. // Wheel
  1547. canvas.removeEventListener('mousewheel', <any>this._onPointerMove);
  1548. canvas.removeEventListener('DOMMouseScroll', <any>this._onPointerMove);
  1549. // Keyboard
  1550. canvas.removeEventListener("keydown", this._onKeyDown);
  1551. canvas.removeEventListener("keyup", this._onKeyUp);
  1552. // Observables
  1553. this.onKeyboardObservable.clear();
  1554. this.onPreKeyboardObservable.clear();
  1555. this.onPointerObservable.clear();
  1556. this.onPrePointerObservable.clear();
  1557. }
  1558. // Ready
  1559. public isReady(): boolean {
  1560. if (this._isDisposed) {
  1561. return false;
  1562. }
  1563. if (this._pendingData.length > 0) {
  1564. return false;
  1565. }
  1566. var index: number;
  1567. // Geometries
  1568. for (index = 0; index < this._geometries.length; index++) {
  1569. var geometry = this._geometries[index];
  1570. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1571. return false;
  1572. }
  1573. }
  1574. // Meshes
  1575. for (index = 0; index < this.meshes.length; index++) {
  1576. var mesh = this.meshes[index];
  1577. if (!mesh.isEnabled()) {
  1578. continue;
  1579. }
  1580. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1581. continue;
  1582. }
  1583. if (!mesh.isReady()) {
  1584. return false;
  1585. }
  1586. var mat = mesh.material;
  1587. if (mat) {
  1588. if (!mat.isReady(mesh)) {
  1589. return false;
  1590. }
  1591. }
  1592. }
  1593. return true;
  1594. }
  1595. public resetCachedMaterial(): void {
  1596. this._cachedMaterial = null;
  1597. this._cachedEffect = null;
  1598. this._cachedVisibility = null;
  1599. }
  1600. public registerBeforeRender(func: () => void): void {
  1601. this.onBeforeRenderObservable.add(func);
  1602. }
  1603. public unregisterBeforeRender(func: () => void): void {
  1604. this.onBeforeRenderObservable.removeCallback(func);
  1605. }
  1606. public registerAfterRender(func: () => void): void {
  1607. this.onAfterRenderObservable.add(func);
  1608. }
  1609. public unregisterAfterRender(func: () => void): void {
  1610. this.onAfterRenderObservable.removeCallback(func);
  1611. }
  1612. public _addPendingData(data: any): void {
  1613. this._pendingData.push(data);
  1614. }
  1615. public _removePendingData(data: any): void {
  1616. var wasLoading = this.isLoading;
  1617. var index = this._pendingData.indexOf(data);
  1618. if (index !== -1) {
  1619. this._pendingData.splice(index, 1);
  1620. }
  1621. if (wasLoading && !this.isLoading) {
  1622. this.onDataLoadedObservable.notifyObservers(this);
  1623. }
  1624. }
  1625. public getWaitingItemsCount(): number {
  1626. return this._pendingData.length;
  1627. }
  1628. public get isLoading(): boolean {
  1629. return this._pendingData.length > 0;
  1630. }
  1631. /**
  1632. * Registers a function to be executed when the scene is ready.
  1633. * @param {Function} func - the function to be executed.
  1634. */
  1635. public executeWhenReady(func: () => void): void {
  1636. this.onReadyObservable.add(func);
  1637. if (this._executeWhenReadyTimeoutId !== -1) {
  1638. return;
  1639. }
  1640. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1641. this._checkIsReady();
  1642. }, 150);
  1643. }
  1644. public _checkIsReady() {
  1645. if (this.isReady()) {
  1646. this.onReadyObservable.notifyObservers(this);
  1647. this.onReadyObservable.clear();
  1648. this._executeWhenReadyTimeoutId = -1;
  1649. return;
  1650. }
  1651. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1652. this._checkIsReady();
  1653. }, 150);
  1654. }
  1655. // Animations
  1656. /**
  1657. * Will start the animation sequence of a given target
  1658. * @param target - the target
  1659. * @param {number} from - from which frame should animation start
  1660. * @param {number} to - till which frame should animation run.
  1661. * @param {boolean} [loop] - should the animation loop
  1662. * @param {number} [speedRatio] - the speed in which to run the animation
  1663. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  1664. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  1665. * Returns {BABYLON.Animatable} the animatable object created for this animation
  1666. * See BABYLON.Animatable
  1667. */
  1668. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  1669. if (from > to && speedRatio > 0) {
  1670. speedRatio *= -1;
  1671. }
  1672. this.stopAnimation(target);
  1673. if (!animatable) {
  1674. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  1675. }
  1676. // Local animations
  1677. if (target.animations) {
  1678. animatable.appendAnimations(target, target.animations);
  1679. }
  1680. // Children animations
  1681. if (target.getAnimatables) {
  1682. var animatables = target.getAnimatables();
  1683. for (var index = 0; index < animatables.length; index++) {
  1684. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  1685. }
  1686. }
  1687. animatable.reset();
  1688. return animatable;
  1689. }
  1690. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  1691. if (speedRatio === undefined) {
  1692. speedRatio = 1.0;
  1693. }
  1694. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  1695. return animatable;
  1696. }
  1697. public getAnimatableByTarget(target: any): Nullable<Animatable> {
  1698. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1699. if (this._activeAnimatables[index].target === target) {
  1700. return this._activeAnimatables[index];
  1701. }
  1702. }
  1703. return null;
  1704. }
  1705. public get animatables(): Animatable[] {
  1706. return this._activeAnimatables;
  1707. }
  1708. /**
  1709. * Will stop the animation of the given target
  1710. * @param target - the target
  1711. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  1712. * @see beginAnimation
  1713. */
  1714. public stopAnimation(target: any, animationName?: string): void {
  1715. var animatable = this.getAnimatableByTarget(target);
  1716. if (animatable) {
  1717. animatable.stop(animationName);
  1718. }
  1719. }
  1720. /**
  1721. * Stops and removes all animations that have been applied to the scene
  1722. */
  1723. public stopAllAnimations(): void {
  1724. if (this._activeAnimatables) {
  1725. for (let i = 0; i < this._activeAnimatables.length; i++) {
  1726. this._activeAnimatables[i].stop();
  1727. }
  1728. this._activeAnimatables = [];
  1729. }
  1730. }
  1731. private _animate(): void {
  1732. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  1733. return;
  1734. }
  1735. // Getting time
  1736. var now = Tools.Now;
  1737. if (!this._animationTimeLast) {
  1738. if (this._pendingData.length > 0) {
  1739. return;
  1740. }
  1741. this._animationTimeLast = now;
  1742. }
  1743. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  1744. this._animationTime += deltaTime;
  1745. this._animationTimeLast = now;
  1746. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1747. this._activeAnimatables[index]._animate(this._animationTime);
  1748. }
  1749. }
  1750. // Matrix
  1751. public _switchToAlternateCameraConfiguration(active: boolean): void {
  1752. this._useAlternateCameraConfiguration = active;
  1753. }
  1754. public getViewMatrix(): Matrix {
  1755. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  1756. }
  1757. public getProjectionMatrix(): Matrix {
  1758. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  1759. }
  1760. public getTransformMatrix(): Matrix {
  1761. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  1762. }
  1763. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  1764. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  1765. return;
  1766. }
  1767. this._viewUpdateFlag = view.updateFlag;
  1768. this._projectionUpdateFlag = projection.updateFlag;
  1769. this._viewMatrix = view;
  1770. this._projectionMatrix = projection;
  1771. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1772. // Update frustum
  1773. if (!this._frustumPlanes) {
  1774. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1775. } else {
  1776. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1777. }
  1778. if (this.activeCamera && this.activeCamera._alternateCamera) {
  1779. let otherCamera = this.activeCamera._alternateCamera;
  1780. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  1781. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  1782. }
  1783. if (this._sceneUbo.useUbo) {
  1784. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  1785. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  1786. this._sceneUbo.update();
  1787. }
  1788. }
  1789. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  1790. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  1791. return;
  1792. }
  1793. this._alternateViewUpdateFlag = view.updateFlag;
  1794. this._alternateProjectionUpdateFlag = projection.updateFlag;
  1795. this._alternateViewMatrix = view;
  1796. this._alternateProjectionMatrix = projection;
  1797. if (!this._alternateTransformMatrix) {
  1798. this._alternateTransformMatrix = Matrix.Zero();
  1799. }
  1800. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  1801. if (!this._alternateSceneUbo) {
  1802. this._createAlternateUbo();
  1803. }
  1804. if (this._alternateSceneUbo.useUbo) {
  1805. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  1806. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  1807. this._alternateSceneUbo.update();
  1808. }
  1809. }
  1810. public getSceneUniformBuffer(): UniformBuffer {
  1811. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  1812. }
  1813. // Methods
  1814. public getUniqueId() {
  1815. var result = Scene._uniqueIdCounter;
  1816. Scene._uniqueIdCounter++;
  1817. return result;
  1818. }
  1819. public addMesh(newMesh: AbstractMesh) {
  1820. this.meshes.push(newMesh);
  1821. //notify the collision coordinator
  1822. if (this.collisionCoordinator) {
  1823. this.collisionCoordinator.onMeshAdded(newMesh);
  1824. }
  1825. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  1826. }
  1827. public removeMesh(toRemove: AbstractMesh): number {
  1828. var index = this.meshes.indexOf(toRemove);
  1829. if (index !== -1) {
  1830. // Remove from the scene if mesh found
  1831. this.meshes.splice(index, 1);
  1832. }
  1833. this.onMeshRemovedObservable.notifyObservers(toRemove);
  1834. return index;
  1835. }
  1836. public addTransformNode(newTransformNode: TransformNode) {
  1837. this.transformNodes.push(newTransformNode);
  1838. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  1839. }
  1840. public removeTransformNode(toRemove: TransformNode): number {
  1841. var index = this.transformNodes.indexOf(toRemove);
  1842. if (index !== -1) {
  1843. // Remove from the scene if found
  1844. this.transformNodes.splice(index, 1);
  1845. }
  1846. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  1847. return index;
  1848. }
  1849. public removeSkeleton(toRemove: Skeleton): number {
  1850. var index = this.skeletons.indexOf(toRemove);
  1851. if (index !== -1) {
  1852. // Remove from the scene if found
  1853. this.skeletons.splice(index, 1);
  1854. }
  1855. return index;
  1856. }
  1857. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  1858. var index = this.morphTargetManagers.indexOf(toRemove);
  1859. if (index !== -1) {
  1860. // Remove from the scene if found
  1861. this.morphTargetManagers.splice(index, 1);
  1862. }
  1863. return index;
  1864. }
  1865. public removeLight(toRemove: Light): number {
  1866. var index = this.lights.indexOf(toRemove);
  1867. if (index !== -1) {
  1868. // Remove from the scene if mesh found
  1869. this.lights.splice(index, 1);
  1870. this.sortLightsByPriority();
  1871. }
  1872. this.onLightRemovedObservable.notifyObservers(toRemove);
  1873. return index;
  1874. }
  1875. public removeCamera(toRemove: Camera): number {
  1876. var index = this.cameras.indexOf(toRemove);
  1877. if (index !== -1) {
  1878. // Remove from the scene if mesh found
  1879. this.cameras.splice(index, 1);
  1880. }
  1881. // Remove from activeCameras
  1882. var index2 = this.activeCameras.indexOf(toRemove);
  1883. if (index2 !== -1) {
  1884. // Remove from the scene if mesh found
  1885. this.activeCameras.splice(index2, 1);
  1886. }
  1887. // Reset the activeCamera
  1888. if (this.activeCamera === toRemove) {
  1889. if (this.cameras.length > 0) {
  1890. this.activeCamera = this.cameras[0];
  1891. } else {
  1892. this.activeCamera = null;
  1893. }
  1894. }
  1895. this.onCameraRemovedObservable.notifyObservers(toRemove);
  1896. return index;
  1897. }
  1898. public addLight(newLight: Light) {
  1899. this.lights.push(newLight);
  1900. this.sortLightsByPriority();
  1901. this.onNewLightAddedObservable.notifyObservers(newLight);
  1902. }
  1903. public sortLightsByPriority(): void {
  1904. if (this.requireLightSorting) {
  1905. this.lights.sort(Light.compareLightsPriority);
  1906. }
  1907. }
  1908. public addCamera(newCamera: Camera) {
  1909. this.cameras.push(newCamera);
  1910. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  1911. }
  1912. /**
  1913. * Switch active camera
  1914. * @param {Camera} newCamera - new active camera
  1915. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  1916. */
  1917. public switchActiveCamera(newCamera: Camera, attachControl = true) {
  1918. var canvas = this._engine.getRenderingCanvas();
  1919. if (!canvas) {
  1920. return;
  1921. }
  1922. if (this.activeCamera) {
  1923. this.activeCamera.detachControl(canvas);
  1924. }
  1925. this.activeCamera = newCamera;
  1926. if (attachControl) {
  1927. newCamera.attachControl(canvas);
  1928. }
  1929. }
  1930. /**
  1931. * sets the active camera of the scene using its ID
  1932. * @param {string} id - the camera's ID
  1933. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1934. * @see activeCamera
  1935. */
  1936. public setActiveCameraByID(id: string): Nullable<Camera> {
  1937. var camera = this.getCameraByID(id);
  1938. if (camera) {
  1939. this.activeCamera = camera;
  1940. return camera;
  1941. }
  1942. return null;
  1943. }
  1944. /**
  1945. * sets the active camera of the scene using its name
  1946. * @param {string} name - the camera's name
  1947. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1948. * @see activeCamera
  1949. */
  1950. public setActiveCameraByName(name: string): Nullable<Camera> {
  1951. var camera = this.getCameraByName(name);
  1952. if (camera) {
  1953. this.activeCamera = camera;
  1954. return camera;
  1955. }
  1956. return null;
  1957. }
  1958. /**
  1959. * get an animation group using its name
  1960. * @param {string} the material's name
  1961. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  1962. */
  1963. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  1964. for (var index = 0; index < this.animationGroups.length; index++) {
  1965. if (this.animationGroups[index].name === name) {
  1966. return this.animationGroups[index];
  1967. }
  1968. }
  1969. return null;
  1970. }
  1971. /**
  1972. * get a material using its id
  1973. * @param {string} the material's ID
  1974. * @return {BABYLON.Material|null} the material or null if none found.
  1975. */
  1976. public getMaterialByID(id: string): Nullable<Material> {
  1977. for (var index = 0; index < this.materials.length; index++) {
  1978. if (this.materials[index].id === id) {
  1979. return this.materials[index];
  1980. }
  1981. }
  1982. return null;
  1983. }
  1984. /**
  1985. * get a material using its name
  1986. * @param {string} the material's name
  1987. * @return {BABYLON.Material|null} the material or null if none found.
  1988. */
  1989. public getMaterialByName(name: string): Nullable<Material> {
  1990. for (var index = 0; index < this.materials.length; index++) {
  1991. if (this.materials[index].name === name) {
  1992. return this.materials[index];
  1993. }
  1994. }
  1995. return null;
  1996. }
  1997. public getLensFlareSystemByName(name: string): Nullable<LensFlareSystem> {
  1998. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1999. if (this.lensFlareSystems[index].name === name) {
  2000. return this.lensFlareSystems[index];
  2001. }
  2002. }
  2003. return null;
  2004. }
  2005. public getLensFlareSystemByID(id: string): Nullable<LensFlareSystem> {
  2006. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  2007. if (this.lensFlareSystems[index].id === id) {
  2008. return this.lensFlareSystems[index];
  2009. }
  2010. }
  2011. return null;
  2012. }
  2013. public getCameraByID(id: string): Nullable<Camera> {
  2014. for (var index = 0; index < this.cameras.length; index++) {
  2015. if (this.cameras[index].id === id) {
  2016. return this.cameras[index];
  2017. }
  2018. }
  2019. return null;
  2020. }
  2021. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  2022. for (var index = 0; index < this.cameras.length; index++) {
  2023. if (this.cameras[index].uniqueId === uniqueId) {
  2024. return this.cameras[index];
  2025. }
  2026. }
  2027. return null;
  2028. }
  2029. /**
  2030. * get a camera using its name
  2031. * @param {string} the camera's name
  2032. * @return {BABYLON.Camera|null} the camera or null if none found.
  2033. */
  2034. public getCameraByName(name: string): Nullable<Camera> {
  2035. for (var index = 0; index < this.cameras.length; index++) {
  2036. if (this.cameras[index].name === name) {
  2037. return this.cameras[index];
  2038. }
  2039. }
  2040. return null;
  2041. }
  2042. /**
  2043. * get a bone using its id
  2044. * @param {string} the bone's id
  2045. * @return {BABYLON.Bone|null} the bone or null if not found
  2046. */
  2047. public getBoneByID(id: string): Nullable<Bone> {
  2048. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2049. var skeleton = this.skeletons[skeletonIndex];
  2050. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2051. if (skeleton.bones[boneIndex].id === id) {
  2052. return skeleton.bones[boneIndex];
  2053. }
  2054. }
  2055. }
  2056. return null;
  2057. }
  2058. /**
  2059. * get a bone using its id
  2060. * @param {string} the bone's name
  2061. * @return {BABYLON.Bone|null} the bone or null if not found
  2062. */
  2063. public getBoneByName(name: string): Nullable<Bone> {
  2064. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2065. var skeleton = this.skeletons[skeletonIndex];
  2066. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2067. if (skeleton.bones[boneIndex].name === name) {
  2068. return skeleton.bones[boneIndex];
  2069. }
  2070. }
  2071. }
  2072. return null;
  2073. }
  2074. /**
  2075. * get a light node using its name
  2076. * @param {string} the light's name
  2077. * @return {BABYLON.Light|null} the light or null if none found.
  2078. */
  2079. public getLightByName(name: string): Nullable<Light> {
  2080. for (var index = 0; index < this.lights.length; index++) {
  2081. if (this.lights[index].name === name) {
  2082. return this.lights[index];
  2083. }
  2084. }
  2085. return null;
  2086. }
  2087. /**
  2088. * get a light node using its ID
  2089. * @param {string} the light's id
  2090. * @return {BABYLON.Light|null} the light or null if none found.
  2091. */
  2092. public getLightByID(id: string): Nullable<Light> {
  2093. for (var index = 0; index < this.lights.length; index++) {
  2094. if (this.lights[index].id === id) {
  2095. return this.lights[index];
  2096. }
  2097. }
  2098. return null;
  2099. }
  2100. /**
  2101. * get a light node using its scene-generated unique ID
  2102. * @param {number} the light's unique id
  2103. * @return {BABYLON.Light|null} the light or null if none found.
  2104. */
  2105. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  2106. for (var index = 0; index < this.lights.length; index++) {
  2107. if (this.lights[index].uniqueId === uniqueId) {
  2108. return this.lights[index];
  2109. }
  2110. }
  2111. return null;
  2112. }
  2113. /**
  2114. * get a particle system by id
  2115. * @param id {number} the particle system id
  2116. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  2117. */
  2118. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  2119. for (var index = 0; index < this.particleSystems.length; index++) {
  2120. if (this.particleSystems[index].id === id) {
  2121. return this.particleSystems[index];
  2122. }
  2123. }
  2124. return null;
  2125. }
  2126. /**
  2127. * get a geometry using its ID
  2128. * @param {string} the geometry's id
  2129. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  2130. */
  2131. public getGeometryByID(id: string): Nullable<Geometry> {
  2132. for (var index = 0; index < this._geometries.length; index++) {
  2133. if (this._geometries[index].id === id) {
  2134. return this._geometries[index];
  2135. }
  2136. }
  2137. return null;
  2138. }
  2139. /**
  2140. * add a new geometry to this scene.
  2141. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  2142. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  2143. * @return {boolean} was the geometry added or not
  2144. */
  2145. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  2146. if (!force && this.getGeometryByID(geometry.id)) {
  2147. return false;
  2148. }
  2149. this._geometries.push(geometry);
  2150. //notify the collision coordinator
  2151. if (this.collisionCoordinator) {
  2152. this.collisionCoordinator.onGeometryAdded(geometry);
  2153. }
  2154. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  2155. return true;
  2156. }
  2157. /**
  2158. * Removes an existing geometry
  2159. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  2160. * @return {boolean} was the geometry removed or not
  2161. */
  2162. public removeGeometry(geometry: Geometry): boolean {
  2163. var index = this._geometries.indexOf(geometry);
  2164. if (index > -1) {
  2165. this._geometries.splice(index, 1);
  2166. //notify the collision coordinator
  2167. if (this.collisionCoordinator) {
  2168. this.collisionCoordinator.onGeometryDeleted(geometry);
  2169. }
  2170. this.onGeometryRemovedObservable.notifyObservers(geometry);
  2171. return true;
  2172. }
  2173. return false;
  2174. }
  2175. public getGeometries(): Geometry[] {
  2176. return this._geometries;
  2177. }
  2178. /**
  2179. * Get the first added mesh found of a given ID
  2180. * @param {string} id - the id to search for
  2181. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2182. */
  2183. public getMeshByID(id: string): Nullable<AbstractMesh> {
  2184. for (var index = 0; index < this.meshes.length; index++) {
  2185. if (this.meshes[index].id === id) {
  2186. return this.meshes[index];
  2187. }
  2188. }
  2189. return null;
  2190. }
  2191. public getMeshesByID(id: string): Array<AbstractMesh> {
  2192. return this.meshes.filter(function (m) {
  2193. return m.id === id;
  2194. })
  2195. }
  2196. /**
  2197. * Get the first added transform node found of a given ID
  2198. * @param {string} id - the id to search for
  2199. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  2200. */
  2201. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  2202. for (var index = 0; index < this.transformNodes.length; index++) {
  2203. if (this.transformNodes[index].id === id) {
  2204. return this.transformNodes[index];
  2205. }
  2206. }
  2207. return null;
  2208. }
  2209. public getTransformNodesByID(id: string): Array<TransformNode> {
  2210. return this.transformNodes.filter(function (m) {
  2211. return m.id === id;
  2212. })
  2213. }
  2214. /**
  2215. * Get a mesh with its auto-generated unique id
  2216. * @param {number} uniqueId - the unique id to search for
  2217. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2218. */
  2219. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  2220. for (var index = 0; index < this.meshes.length; index++) {
  2221. if (this.meshes[index].uniqueId === uniqueId) {
  2222. return this.meshes[index];
  2223. }
  2224. }
  2225. return null;
  2226. }
  2227. /**
  2228. * Get a the last added mesh found of a given ID
  2229. * @param {string} id - the id to search for
  2230. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2231. */
  2232. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  2233. for (var index = this.meshes.length - 1; index >= 0; index--) {
  2234. if (this.meshes[index].id === id) {
  2235. return this.meshes[index];
  2236. }
  2237. }
  2238. return null;
  2239. }
  2240. /**
  2241. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  2242. * @param {string} id - the id to search for
  2243. * @return {BABYLON.Node|null} the node found or null if not found at all.
  2244. */
  2245. public getLastEntryByID(id: string): Nullable<Node> {
  2246. var index: number;
  2247. for (index = this.meshes.length - 1; index >= 0; index--) {
  2248. if (this.meshes[index].id === id) {
  2249. return this.meshes[index];
  2250. }
  2251. }
  2252. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  2253. if (this.transformNodes[index].id === id) {
  2254. return this.transformNodes[index];
  2255. }
  2256. }
  2257. for (index = this.cameras.length - 1; index >= 0; index--) {
  2258. if (this.cameras[index].id === id) {
  2259. return this.cameras[index];
  2260. }
  2261. }
  2262. for (index = this.lights.length - 1; index >= 0; index--) {
  2263. if (this.lights[index].id === id) {
  2264. return this.lights[index];
  2265. }
  2266. }
  2267. return null;
  2268. }
  2269. public getNodeByID(id: string): Nullable<Node> {
  2270. var mesh = this.getMeshByID(id);
  2271. if (mesh) {
  2272. return mesh;
  2273. }
  2274. var light = this.getLightByID(id);
  2275. if (light) {
  2276. return light;
  2277. }
  2278. var camera = this.getCameraByID(id);
  2279. if (camera) {
  2280. return camera;
  2281. }
  2282. var bone = this.getBoneByID(id);
  2283. return bone;
  2284. }
  2285. public getNodeByName(name: string): Nullable<Node> {
  2286. var mesh = this.getMeshByName(name);
  2287. if (mesh) {
  2288. return mesh;
  2289. }
  2290. var light = this.getLightByName(name);
  2291. if (light) {
  2292. return light;
  2293. }
  2294. var camera = this.getCameraByName(name);
  2295. if (camera) {
  2296. return camera;
  2297. }
  2298. var bone = this.getBoneByName(name);
  2299. return bone;
  2300. }
  2301. public getMeshByName(name: string): Nullable<AbstractMesh> {
  2302. for (var index = 0; index < this.meshes.length; index++) {
  2303. if (this.meshes[index].name === name) {
  2304. return this.meshes[index];
  2305. }
  2306. }
  2307. return null;
  2308. }
  2309. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  2310. for (var index = 0; index < this.transformNodes.length; index++) {
  2311. if (this.transformNodes[index].name === name) {
  2312. return this.transformNodes[index];
  2313. }
  2314. }
  2315. return null;
  2316. }
  2317. public getSoundByName(name: string): Nullable<Sound> {
  2318. var index: number;
  2319. if (AudioEngine) {
  2320. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  2321. if (this.mainSoundTrack.soundCollection[index].name === name) {
  2322. return this.mainSoundTrack.soundCollection[index];
  2323. }
  2324. }
  2325. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  2326. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  2327. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  2328. return this.soundTracks[sdIndex].soundCollection[index];
  2329. }
  2330. }
  2331. }
  2332. }
  2333. return null;
  2334. }
  2335. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  2336. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  2337. if (this.skeletons[index].id === id) {
  2338. return this.skeletons[index];
  2339. }
  2340. }
  2341. return null;
  2342. }
  2343. public getSkeletonById(id: string): Nullable<Skeleton> {
  2344. for (var index = 0; index < this.skeletons.length; index++) {
  2345. if (this.skeletons[index].id === id) {
  2346. return this.skeletons[index];
  2347. }
  2348. }
  2349. return null;
  2350. }
  2351. public getSkeletonByName(name: string): Nullable<Skeleton> {
  2352. for (var index = 0; index < this.skeletons.length; index++) {
  2353. if (this.skeletons[index].name === name) {
  2354. return this.skeletons[index];
  2355. }
  2356. }
  2357. return null;
  2358. }
  2359. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  2360. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  2361. if (this.morphTargetManagers[index].uniqueId === id) {
  2362. return this.morphTargetManagers[index];
  2363. }
  2364. }
  2365. return null;
  2366. }
  2367. public isActiveMesh(mesh: AbstractMesh): boolean {
  2368. return (this._activeMeshes.indexOf(mesh) !== -1);
  2369. }
  2370. /**
  2371. * Return a the first highlight layer of the scene with a given name.
  2372. * @param name The name of the highlight layer to look for.
  2373. * @return The highlight layer if found otherwise null.
  2374. */
  2375. public getHighlightLayerByName(name: string): Nullable<HighlightLayer> {
  2376. for (var index = 0; index < this.highlightLayers.length; index++) {
  2377. if (this.highlightLayers[index].name === name) {
  2378. return this.highlightLayers[index];
  2379. }
  2380. }
  2381. return null;
  2382. }
  2383. /**
  2384. * Return a unique id as a string which can serve as an identifier for the scene
  2385. */
  2386. public get uid(): string {
  2387. if (!this._uid) {
  2388. this._uid = Tools.RandomId();
  2389. }
  2390. return this._uid;
  2391. }
  2392. /**
  2393. * Add an externaly attached data from its key.
  2394. * This method call will fail and return false, if such key already exists.
  2395. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2396. * @param key the unique key that identifies the data
  2397. * @param data the data object to associate to the key for this Engine instance
  2398. * @return true if no such key were already present and the data was added successfully, false otherwise
  2399. */
  2400. public addExternalData<T>(key: string, data: T): boolean {
  2401. if (!this._externalData) {
  2402. this._externalData = new StringDictionary<Object>();
  2403. }
  2404. return this._externalData.add(key, data);
  2405. }
  2406. /**
  2407. * Get an externaly attached data from its key
  2408. * @param key the unique key that identifies the data
  2409. * @return the associated data, if present (can be null), or undefined if not present
  2410. */
  2411. public getExternalData<T>(key: string): Nullable<T> {
  2412. if (!this._externalData) {
  2413. return null;
  2414. }
  2415. return <T>this._externalData.get(key);
  2416. }
  2417. /**
  2418. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2419. * @param key the unique key that identifies the data
  2420. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2421. * @return the associated data, can be null if the factory returned null.
  2422. */
  2423. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2424. if (!this._externalData) {
  2425. this._externalData = new StringDictionary<Object>();
  2426. }
  2427. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2428. }
  2429. /**
  2430. * Remove an externaly attached data from the Engine instance
  2431. * @param key the unique key that identifies the data
  2432. * @return true if the data was successfully removed, false if it doesn't exist
  2433. */
  2434. public removeExternalData(key: string): boolean {
  2435. return this._externalData.remove(key);
  2436. }
  2437. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  2438. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  2439. if (mesh.showSubMeshesBoundingBox) {
  2440. const boundingInfo = subMesh.getBoundingInfo();
  2441. if (boundingInfo !== null && boundingInfo !== undefined) {
  2442. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  2443. }
  2444. }
  2445. const material = subMesh.getMaterial();
  2446. if (material !== null && material !== undefined) {
  2447. // Render targets
  2448. if (material.getRenderTargetTextures !== undefined) {
  2449. if (this._processedMaterials.indexOf(material) === -1) {
  2450. this._processedMaterials.push(material);
  2451. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  2452. }
  2453. }
  2454. // Dispatch
  2455. this._activeIndices.addCount(subMesh.indexCount, false);
  2456. this._renderingManager.dispatch(subMesh, mesh, material);
  2457. }
  2458. }
  2459. }
  2460. public _isInIntermediateRendering(): boolean {
  2461. return this._intermediateRendering
  2462. }
  2463. private _activeMeshCandidateProvider: IActiveMeshCandidateProvider;
  2464. public setActiveMeshCandidateProvider(provider: IActiveMeshCandidateProvider): void {
  2465. this._activeMeshCandidateProvider = provider;
  2466. }
  2467. public getActiveMeshCandidateProvider(): IActiveMeshCandidateProvider {
  2468. return this._activeMeshCandidateProvider;
  2469. }
  2470. private _activeMeshesFrozen = false;
  2471. /**
  2472. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  2473. */
  2474. public freezeActiveMeshes(): Scene {
  2475. this._evaluateActiveMeshes();
  2476. this._activeMeshesFrozen = true;
  2477. return this;
  2478. }
  2479. /**
  2480. * Use this function to restart evaluating active meshes on every frame
  2481. */
  2482. public unfreezeActiveMeshes() {
  2483. this._activeMeshesFrozen = false;
  2484. return this;
  2485. }
  2486. private _evaluateActiveMeshes(): void {
  2487. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  2488. return;
  2489. }
  2490. if (!this.activeCamera) {
  2491. return;
  2492. }
  2493. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  2494. this.activeCamera._activeMeshes.reset();
  2495. this._activeMeshes.reset();
  2496. this._renderingManager.reset();
  2497. this._processedMaterials.reset();
  2498. this._activeParticleSystems.reset();
  2499. this._activeSkeletons.reset();
  2500. this._softwareSkinnedMeshes.reset();
  2501. if (this._boundingBoxRenderer) {
  2502. this._boundingBoxRenderer.reset();
  2503. }
  2504. // Meshes
  2505. var meshes: AbstractMesh[];
  2506. var len: number;
  2507. var checkIsEnabled = true;
  2508. // Determine mesh candidates
  2509. if (this._activeMeshCandidateProvider !== undefined) {
  2510. // Use _activeMeshCandidateProvider
  2511. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  2512. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  2513. if (meshes !== undefined) {
  2514. len = meshes.length;
  2515. } else {
  2516. len = 0;
  2517. }
  2518. } else if (this._selectionOctree !== undefined) {
  2519. // Octree
  2520. var selection = this._selectionOctree.select(this._frustumPlanes);
  2521. meshes = selection.data;
  2522. len = selection.length;
  2523. } else {
  2524. // Full scene traversal
  2525. len = this.meshes.length;
  2526. meshes = this.meshes;
  2527. }
  2528. // Check each mesh
  2529. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  2530. mesh = meshes[meshIndex];
  2531. if (mesh.isBlocked) {
  2532. continue;
  2533. }
  2534. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  2535. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  2536. continue;
  2537. }
  2538. mesh.computeWorldMatrix();
  2539. // Intersections
  2540. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  2541. this._meshesForIntersections.pushNoDuplicate(mesh);
  2542. }
  2543. // Switch to current LOD
  2544. meshLOD = mesh.getLOD(this.activeCamera);
  2545. if (meshLOD === undefined || meshLOD === null) {
  2546. continue;
  2547. }
  2548. mesh._preActivate();
  2549. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  2550. this._activeMeshes.push(mesh);
  2551. this.activeCamera._activeMeshes.push(mesh);
  2552. mesh._activate(this._renderId);
  2553. if (meshLOD !== mesh) {
  2554. meshLOD._activate(this._renderId);
  2555. }
  2556. this._activeMesh(mesh, meshLOD);
  2557. }
  2558. }
  2559. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  2560. // Particle systems
  2561. if (this.particlesEnabled) {
  2562. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  2563. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  2564. var particleSystem = this.particleSystems[particleIndex];
  2565. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  2566. continue;
  2567. }
  2568. let emitter = <any>particleSystem.emitter;
  2569. if (!emitter.position || emitter.isEnabled()) {
  2570. this._activeParticleSystems.push(particleSystem);
  2571. particleSystem.animate();
  2572. this._renderingManager.dispatchParticles(particleSystem);
  2573. }
  2574. }
  2575. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  2576. }
  2577. }
  2578. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  2579. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  2580. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  2581. mesh.skeleton.prepare();
  2582. }
  2583. if (!mesh.computeBonesUsingShaders) {
  2584. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  2585. }
  2586. }
  2587. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  2588. let boundingInfo = sourceMesh.getBoundingInfo();
  2589. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  2590. }
  2591. if (
  2592. mesh !== undefined && mesh !== null
  2593. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  2594. ) {
  2595. // Submeshes Octrees
  2596. var len: number;
  2597. var subMeshes: SubMesh[];
  2598. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  2599. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  2600. len = intersections.length;
  2601. subMeshes = intersections.data;
  2602. } else {
  2603. subMeshes = mesh.subMeshes;
  2604. len = subMeshes.length;
  2605. }
  2606. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  2607. subMesh = subMeshes[subIndex];
  2608. this._evaluateSubMesh(subMesh, mesh);
  2609. }
  2610. }
  2611. }
  2612. public updateTransformMatrix(force?: boolean): void {
  2613. if (!this.activeCamera) {
  2614. return;
  2615. }
  2616. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  2617. }
  2618. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  2619. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  2620. }
  2621. private _renderForCamera(camera: Camera): void {
  2622. if (camera && camera._skipRendering) {
  2623. return;
  2624. }
  2625. var engine = this._engine;
  2626. this.activeCamera = camera;
  2627. if (!this.activeCamera)
  2628. throw new Error("Active camera not set");
  2629. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2630. // Viewport
  2631. engine.setViewport(this.activeCamera.viewport);
  2632. // Camera
  2633. this.resetCachedMaterial();
  2634. this._renderId++;
  2635. this.activeCamera.update();
  2636. this.updateTransformMatrix();
  2637. if (camera._alternateCamera) {
  2638. this.updateAlternateTransformMatrix(camera._alternateCamera);
  2639. this._alternateRendering = true;
  2640. }
  2641. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  2642. // Meshes
  2643. this._evaluateActiveMeshes();
  2644. // Software skinning
  2645. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  2646. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  2647. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  2648. }
  2649. // Render targets
  2650. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  2651. var needsRestoreFrameBuffer = false;
  2652. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  2653. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  2654. }
  2655. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  2656. this._intermediateRendering = true;
  2657. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2658. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  2659. let renderTarget = this._renderTargets.data[renderIndex];
  2660. if (renderTarget._shouldRender()) {
  2661. this._renderId++;
  2662. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  2663. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  2664. }
  2665. }
  2666. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2667. this._intermediateRendering = false;
  2668. this._renderId++;
  2669. needsRestoreFrameBuffer = true; // Restore back buffer
  2670. }
  2671. // Render HighlightLayer Texture
  2672. var stencilState = this._engine.getStencilBuffer();
  2673. var renderhighlights = false;
  2674. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  2675. this._intermediateRendering = true;
  2676. for (let i = 0; i < this.highlightLayers.length; i++) {
  2677. let highlightLayer = this.highlightLayers[i];
  2678. if (highlightLayer.shouldRender() &&
  2679. (!highlightLayer.camera ||
  2680. (highlightLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  2681. (highlightLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  2682. renderhighlights = true;
  2683. let renderTarget = (<RenderTargetTexture>(<any>highlightLayer)._mainTexture);
  2684. if (renderTarget._shouldRender()) {
  2685. this._renderId++;
  2686. renderTarget.render(false, false);
  2687. needsRestoreFrameBuffer = true;
  2688. }
  2689. }
  2690. }
  2691. this._intermediateRendering = false;
  2692. this._renderId++;
  2693. }
  2694. if (needsRestoreFrameBuffer) {
  2695. engine.restoreDefaultFramebuffer(); // Restore back buffer
  2696. }
  2697. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  2698. // Prepare Frame
  2699. this.postProcessManager._prepareFrame();
  2700. // Backgrounds
  2701. var layerIndex;
  2702. var layer;
  2703. if (this.layers.length) {
  2704. engine.setDepthBuffer(false);
  2705. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2706. layer = this.layers[layerIndex];
  2707. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2708. layer.render();
  2709. }
  2710. }
  2711. engine.setDepthBuffer(true);
  2712. }
  2713. // Activate HighlightLayer stencil
  2714. if (renderhighlights) {
  2715. this._engine.setStencilBuffer(true);
  2716. }
  2717. // Render
  2718. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  2719. this._renderingManager.render(null, null, true, true);
  2720. this.onAfterDrawPhaseObservable.notifyObservers(this);
  2721. // Restore HighlightLayer stencil
  2722. if (renderhighlights) {
  2723. this._engine.setStencilBuffer(stencilState);
  2724. }
  2725. // Bounding boxes
  2726. if (this._boundingBoxRenderer) {
  2727. this._boundingBoxRenderer.render();
  2728. }
  2729. // Lens flares
  2730. if (this.lensFlaresEnabled) {
  2731. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2732. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  2733. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  2734. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  2735. lensFlareSystem.render();
  2736. }
  2737. }
  2738. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2739. }
  2740. // Foregrounds
  2741. if (this.layers.length) {
  2742. engine.setDepthBuffer(false);
  2743. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2744. layer = this.layers[layerIndex];
  2745. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2746. layer.render();
  2747. }
  2748. }
  2749. engine.setDepthBuffer(true);
  2750. }
  2751. // Highlight Layer
  2752. if (renderhighlights) {
  2753. engine.setDepthBuffer(false);
  2754. for (let i = 0; i < this.highlightLayers.length; i++) {
  2755. if (this.highlightLayers[i].shouldRender()) {
  2756. this.highlightLayers[i].render();
  2757. }
  2758. }
  2759. engine.setDepthBuffer(true);
  2760. }
  2761. // Finalize frame
  2762. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  2763. // Reset some special arrays
  2764. this._renderTargets.reset();
  2765. this._alternateRendering = false;
  2766. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  2767. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2768. }
  2769. private _processSubCameras(camera: Camera): void {
  2770. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  2771. this._renderForCamera(camera);
  2772. return;
  2773. }
  2774. // Update camera
  2775. if (this.activeCamera) {
  2776. this.activeCamera.update();
  2777. }
  2778. // rig cameras
  2779. for (var index = 0; index < camera._rigCameras.length; index++) {
  2780. this._renderForCamera(camera._rigCameras[index]);
  2781. }
  2782. this.activeCamera = camera;
  2783. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  2784. }
  2785. private _checkIntersections(): void {
  2786. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  2787. var sourceMesh = this._meshesForIntersections.data[index];
  2788. if (!sourceMesh.actionManager) {
  2789. continue;
  2790. }
  2791. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  2792. var action = sourceMesh.actionManager.actions[actionIndex];
  2793. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2794. var parameters = action.getTriggerParameter();
  2795. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  2796. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  2797. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  2798. if (areIntersecting && currentIntersectionInProgress === -1) {
  2799. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  2800. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  2801. sourceMesh._intersectionsInProgress.push(otherMesh);
  2802. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2803. sourceMesh._intersectionsInProgress.push(otherMesh);
  2804. }
  2805. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  2806. //They intersected, and now they don't.
  2807. //is this trigger an exit trigger? execute an event.
  2808. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2809. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  2810. }
  2811. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  2812. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2813. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  2814. }
  2815. }
  2816. }
  2817. }
  2818. }
  2819. }
  2820. public render(): void {
  2821. if (this.isDisposed) {
  2822. return;
  2823. }
  2824. this._activeParticles.fetchNewFrame();
  2825. this._totalVertices.fetchNewFrame();
  2826. this._activeIndices.fetchNewFrame();
  2827. this._activeBones.fetchNewFrame();
  2828. this._meshesForIntersections.reset();
  2829. this.resetCachedMaterial();
  2830. this.onBeforeAnimationsObservable.notifyObservers(this);
  2831. // Actions
  2832. if (this.actionManager) {
  2833. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger);
  2834. }
  2835. //Simplification Queue
  2836. if (this.simplificationQueue && !this.simplificationQueue.running) {
  2837. this.simplificationQueue.executeNext();
  2838. }
  2839. if (this._engine.isDeterministicLockStep()) {
  2840. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  2841. var defaultFPS = (60.0 / 1000.0);
  2842. let defaultFrameTime = 1000 / 60; // frame time in MS
  2843. if (this._physicsEngine) {
  2844. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  2845. }
  2846. let stepsTaken = 0;
  2847. var maxSubSteps = this._engine.getLockstepMaxSteps();
  2848. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  2849. internalSteps = Math.min(internalSteps, maxSubSteps);
  2850. do {
  2851. this.onBeforeStepObservable.notifyObservers(this);
  2852. // Animations
  2853. this._animationRatio = defaultFrameTime * defaultFPS;
  2854. this._animate();
  2855. this.onAfterAnimationsObservable.notifyObservers(this);
  2856. // Physics
  2857. if (this._physicsEngine) {
  2858. this.onBeforePhysicsObservable.notifyObservers(this);
  2859. this._physicsEngine._step(defaultFrameTime / 1000);
  2860. this.onAfterPhysicsObservable.notifyObservers(this);
  2861. }
  2862. this.onAfterStepObservable.notifyObservers(this);
  2863. this._currentStepId++;
  2864. stepsTaken++;
  2865. deltaTime -= defaultFrameTime;
  2866. } while (deltaTime > 0 && stepsTaken < internalSteps);
  2867. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  2868. }
  2869. else {
  2870. // Animations
  2871. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  2872. this._animationRatio = deltaTime * (60.0 / 1000.0);
  2873. this._animate();
  2874. this.onAfterAnimationsObservable.notifyObservers(this);
  2875. // Physics
  2876. if (this._physicsEngine) {
  2877. this.onBeforePhysicsObservable.notifyObservers(this);
  2878. this._physicsEngine._step(deltaTime / 1000.0);
  2879. this.onAfterPhysicsObservable.notifyObservers(this);
  2880. }
  2881. }
  2882. // update gamepad manager
  2883. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  2884. this._gamepadManager._checkGamepadsStatus();
  2885. }
  2886. // Before render
  2887. this.onBeforeRenderObservable.notifyObservers(this);
  2888. // Customs render targets
  2889. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  2890. var engine = this.getEngine();
  2891. var currentActiveCamera = this.activeCamera;
  2892. if (this.renderTargetsEnabled) {
  2893. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  2894. this._intermediateRendering = true;
  2895. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  2896. var renderTarget = this.customRenderTargets[customIndex];
  2897. if (renderTarget._shouldRender()) {
  2898. this._renderId++;
  2899. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  2900. if (!this.activeCamera)
  2901. throw new Error("Active camera not set");
  2902. // Viewport
  2903. engine.setViewport(this.activeCamera.viewport);
  2904. // Camera
  2905. this.updateTransformMatrix();
  2906. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  2907. }
  2908. }
  2909. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  2910. this._intermediateRendering = false;
  2911. this._renderId++;
  2912. }
  2913. // Restore back buffer
  2914. if (this.customRenderTargets.length > 0) {
  2915. engine.restoreDefaultFramebuffer();
  2916. }
  2917. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  2918. this.activeCamera = currentActiveCamera;
  2919. // Procedural textures
  2920. if (this.proceduralTexturesEnabled) {
  2921. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  2922. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  2923. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  2924. if (proceduralTexture._shouldRender()) {
  2925. proceduralTexture.render();
  2926. }
  2927. }
  2928. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  2929. }
  2930. // Clear
  2931. if (this.autoClearDepthAndStencil || this.autoClear) {
  2932. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  2933. }
  2934. // Shadows
  2935. if (this.shadowsEnabled) {
  2936. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  2937. var light = this.lights[lightIndex];
  2938. var shadowGenerator = light.getShadowGenerator();
  2939. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  2940. var shadowMap = <RenderTargetTexture>(shadowGenerator.getShadowMap());
  2941. if (this.textures.indexOf(shadowMap) !== -1) {
  2942. this._renderTargets.push(shadowMap);
  2943. }
  2944. }
  2945. }
  2946. }
  2947. // Depth renderer
  2948. if (this._depthRenderer) {
  2949. this._renderTargets.push(this._depthRenderer.getDepthMap());
  2950. }
  2951. // Geometry renderer
  2952. if (this._geometryBufferRenderer) {
  2953. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  2954. }
  2955. // RenderPipeline
  2956. if (this._postProcessRenderPipelineManager) {
  2957. this._postProcessRenderPipelineManager.update();
  2958. }
  2959. // Multi-cameras?
  2960. if (this.activeCameras.length > 0) {
  2961. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  2962. if (cameraIndex > 0) {
  2963. this._engine.clear(null, false, true, true);
  2964. }
  2965. this._processSubCameras(this.activeCameras[cameraIndex]);
  2966. }
  2967. } else {
  2968. if (!this.activeCamera) {
  2969. throw new Error("No camera defined");
  2970. }
  2971. this._processSubCameras(this.activeCamera);
  2972. }
  2973. // Intersection checks
  2974. this._checkIntersections();
  2975. // Update the audio listener attached to the camera
  2976. if (AudioEngine) {
  2977. this._updateAudioParameters();
  2978. }
  2979. // After render
  2980. if (this.afterRender) {
  2981. this.afterRender();
  2982. }
  2983. this.onAfterRenderObservable.notifyObservers(this);
  2984. // Cleaning
  2985. for (var index = 0; index < this._toBeDisposed.length; index++) {
  2986. var data = this._toBeDisposed.data[index];
  2987. if (data) {
  2988. data.dispose();
  2989. }
  2990. this._toBeDisposed[index] = null;
  2991. }
  2992. this._toBeDisposed.reset();
  2993. if (this.dumpNextRenderTargets) {
  2994. this.dumpNextRenderTargets = false;
  2995. }
  2996. this._activeBones.addCount(0, true);
  2997. this._activeIndices.addCount(0, true);
  2998. this._activeParticles.addCount(0, true);
  2999. }
  3000. private _updateAudioParameters() {
  3001. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  3002. return;
  3003. }
  3004. var listeningCamera: Nullable<Camera>;
  3005. var audioEngine = Engine.audioEngine;
  3006. if (this.activeCameras.length > 0) {
  3007. listeningCamera = this.activeCameras[0];
  3008. } else {
  3009. listeningCamera = this.activeCamera;
  3010. }
  3011. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  3012. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  3013. // for VR cameras
  3014. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  3015. listeningCamera = listeningCamera.rigCameras[0];
  3016. }
  3017. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  3018. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  3019. cameraDirection.normalize();
  3020. // To avoid some errors on GearVR
  3021. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  3022. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  3023. }
  3024. var i: number;
  3025. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3026. var sound = this.mainSoundTrack.soundCollection[i];
  3027. if (sound.useCustomAttenuation) {
  3028. sound.updateDistanceFromListener();
  3029. }
  3030. }
  3031. for (i = 0; i < this.soundTracks.length; i++) {
  3032. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3033. sound = this.soundTracks[i].soundCollection[j];
  3034. if (sound.useCustomAttenuation) {
  3035. sound.updateDistanceFromListener();
  3036. }
  3037. }
  3038. }
  3039. }
  3040. }
  3041. // Audio
  3042. public get audioEnabled(): boolean {
  3043. return this._audioEnabled;
  3044. }
  3045. public set audioEnabled(value: boolean) {
  3046. this._audioEnabled = value;
  3047. if (AudioEngine) {
  3048. if (this._audioEnabled) {
  3049. this._enableAudio();
  3050. }
  3051. else {
  3052. this._disableAudio();
  3053. }
  3054. }
  3055. }
  3056. private _disableAudio() {
  3057. var i: number;
  3058. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3059. this.mainSoundTrack.soundCollection[i].pause();
  3060. }
  3061. for (i = 0; i < this.soundTracks.length; i++) {
  3062. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3063. this.soundTracks[i].soundCollection[j].pause();
  3064. }
  3065. }
  3066. }
  3067. private _enableAudio() {
  3068. var i: number;
  3069. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3070. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  3071. this.mainSoundTrack.soundCollection[i].play();
  3072. }
  3073. }
  3074. for (i = 0; i < this.soundTracks.length; i++) {
  3075. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3076. if (this.soundTracks[i].soundCollection[j].isPaused) {
  3077. this.soundTracks[i].soundCollection[j].play();
  3078. }
  3079. }
  3080. }
  3081. }
  3082. public get headphone(): boolean {
  3083. return this._headphone;
  3084. }
  3085. public set headphone(value: boolean) {
  3086. this._headphone = value;
  3087. if (AudioEngine) {
  3088. if (this._headphone) {
  3089. this._switchAudioModeForHeadphones();
  3090. }
  3091. else {
  3092. this._switchAudioModeForNormalSpeakers();
  3093. }
  3094. }
  3095. }
  3096. private _switchAudioModeForHeadphones() {
  3097. this.mainSoundTrack.switchPanningModelToHRTF();
  3098. for (var i = 0; i < this.soundTracks.length; i++) {
  3099. this.soundTracks[i].switchPanningModelToHRTF();
  3100. }
  3101. }
  3102. private _switchAudioModeForNormalSpeakers() {
  3103. this.mainSoundTrack.switchPanningModelToEqualPower();
  3104. for (var i = 0; i < this.soundTracks.length; i++) {
  3105. this.soundTracks[i].switchPanningModelToEqualPower();
  3106. }
  3107. }
  3108. public enableDepthRenderer(): DepthRenderer {
  3109. if (this._depthRenderer) {
  3110. return this._depthRenderer;
  3111. }
  3112. this._depthRenderer = new DepthRenderer(this);
  3113. return this._depthRenderer;
  3114. }
  3115. public disableDepthRenderer(): void {
  3116. if (!this._depthRenderer) {
  3117. return;
  3118. }
  3119. this._depthRenderer.dispose();
  3120. this._depthRenderer = null;
  3121. }
  3122. public enableGeometryBufferRenderer(ratio: number = 1): Nullable<GeometryBufferRenderer> {
  3123. if (this._geometryBufferRenderer) {
  3124. return this._geometryBufferRenderer;
  3125. }
  3126. this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio);
  3127. if (!this._geometryBufferRenderer.isSupported) {
  3128. this._geometryBufferRenderer = null;
  3129. }
  3130. return this._geometryBufferRenderer;
  3131. }
  3132. public disableGeometryBufferRenderer(): void {
  3133. if (!this._geometryBufferRenderer) {
  3134. return;
  3135. }
  3136. this._geometryBufferRenderer.dispose();
  3137. this._geometryBufferRenderer = null;
  3138. }
  3139. public freezeMaterials(): void {
  3140. for (var i = 0; i < this.materials.length; i++) {
  3141. this.materials[i].freeze();
  3142. }
  3143. }
  3144. public unfreezeMaterials(): void {
  3145. for (var i = 0; i < this.materials.length; i++) {
  3146. this.materials[i].unfreeze();
  3147. }
  3148. }
  3149. public dispose(): void {
  3150. this.beforeRender = null;
  3151. this.afterRender = null;
  3152. this.skeletons = [];
  3153. this.morphTargetManagers = [];
  3154. this.importedMeshesFiles = new Array<string>();
  3155. this.stopAllAnimations();
  3156. this.resetCachedMaterial();
  3157. if (this._depthRenderer) {
  3158. this._depthRenderer.dispose();
  3159. }
  3160. if (this._gamepadManager) {
  3161. this._gamepadManager.dispose();
  3162. this._gamepadManager = null;
  3163. }
  3164. // Smart arrays
  3165. if (this.activeCamera) {
  3166. this.activeCamera._activeMeshes.dispose();
  3167. this.activeCamera = null;
  3168. }
  3169. this._activeMeshes.dispose();
  3170. this._renderingManager.dispose();
  3171. this._processedMaterials.dispose();
  3172. this._activeParticleSystems.dispose();
  3173. this._activeSkeletons.dispose();
  3174. this._softwareSkinnedMeshes.dispose();
  3175. this._renderTargets.dispose();
  3176. if (this._boundingBoxRenderer) {
  3177. this._boundingBoxRenderer.dispose();
  3178. }
  3179. this._meshesForIntersections.dispose();
  3180. this._toBeDisposed.dispose();
  3181. // Abort active requests
  3182. for (let request of this._activeRequests) {
  3183. request.abort();
  3184. }
  3185. // Debug layer
  3186. if (this._debugLayer) {
  3187. this._debugLayer.hide();
  3188. }
  3189. // Events
  3190. this.onDisposeObservable.notifyObservers(this);
  3191. this.onDisposeObservable.clear();
  3192. this.onBeforeRenderObservable.clear();
  3193. this.onAfterRenderObservable.clear();
  3194. this.OnBeforeRenderTargetsRenderObservable.clear();
  3195. this.OnAfterRenderTargetsRenderObservable.clear();
  3196. this.onAfterStepObservable.clear();
  3197. this.onBeforeStepObservable.clear();
  3198. this.onBeforeActiveMeshesEvaluationObservable.clear();
  3199. this.onAfterActiveMeshesEvaluationObservable.clear();
  3200. this.onBeforeParticlesRenderingObservable.clear();
  3201. this.onAfterParticlesRenderingObservable.clear();
  3202. this.onBeforeSpritesRenderingObservable.clear();
  3203. this.onAfterSpritesRenderingObservable.clear();
  3204. this.onBeforeDrawPhaseObservable.clear();
  3205. this.onAfterDrawPhaseObservable.clear();
  3206. this.onBeforePhysicsObservable.clear();
  3207. this.onAfterPhysicsObservable.clear();
  3208. this.onBeforeAnimationsObservable.clear();
  3209. this.onAfterAnimationsObservable.clear();
  3210. this.onDataLoadedObservable.clear();
  3211. this.detachControl();
  3212. // Release sounds & sounds tracks
  3213. if (AudioEngine) {
  3214. this.disposeSounds();
  3215. }
  3216. // VR Helper
  3217. if (this.VRHelper) {
  3218. this.VRHelper.dispose();
  3219. }
  3220. // Detach cameras
  3221. var canvas = this._engine.getRenderingCanvas();
  3222. if (canvas) {
  3223. var index;
  3224. for (index = 0; index < this.cameras.length; index++) {
  3225. this.cameras[index].detachControl(canvas);
  3226. }
  3227. }
  3228. // Release animation groups
  3229. while (this.animationGroups.length) {
  3230. this.animationGroups[0].dispose();
  3231. }
  3232. // Release lights
  3233. while (this.lights.length) {
  3234. this.lights[0].dispose();
  3235. }
  3236. // Release meshes
  3237. while (this.meshes.length) {
  3238. this.meshes[0].dispose(true);
  3239. }
  3240. while (this.transformNodes.length) {
  3241. this.removeTransformNode(this.transformNodes[0]);
  3242. }
  3243. // Release cameras
  3244. while (this.cameras.length) {
  3245. this.cameras[0].dispose();
  3246. }
  3247. // Release materials
  3248. if (this.defaultMaterial) {
  3249. this.defaultMaterial.dispose()
  3250. }
  3251. while (this.multiMaterials.length) {
  3252. this.multiMaterials[0].dispose();
  3253. }
  3254. while (this.materials.length) {
  3255. this.materials[0].dispose();
  3256. }
  3257. // Release particles
  3258. while (this.particleSystems.length) {
  3259. this.particleSystems[0].dispose();
  3260. }
  3261. // Release sprites
  3262. while (this.spriteManagers.length) {
  3263. this.spriteManagers[0].dispose();
  3264. }
  3265. // Release postProcesses
  3266. while (this.postProcesses.length) {
  3267. this.postProcesses[0].dispose();
  3268. }
  3269. // Release layers
  3270. while (this.layers.length) {
  3271. this.layers[0].dispose();
  3272. }
  3273. while (this.highlightLayers.length) {
  3274. this.highlightLayers[0].dispose();
  3275. }
  3276. // Release textures
  3277. while (this.textures.length) {
  3278. this.textures[0].dispose();
  3279. }
  3280. // Release UBO
  3281. this._sceneUbo.dispose();
  3282. if (this._alternateSceneUbo) {
  3283. this._alternateSceneUbo.dispose();
  3284. }
  3285. // Post-processes
  3286. this.postProcessManager.dispose();
  3287. if (this._postProcessRenderPipelineManager) {
  3288. this._postProcessRenderPipelineManager.dispose();
  3289. }
  3290. // Physics
  3291. if (this._physicsEngine) {
  3292. this.disablePhysicsEngine();
  3293. }
  3294. // Remove from engine
  3295. index = this._engine.scenes.indexOf(this);
  3296. if (index > -1) {
  3297. this._engine.scenes.splice(index, 1);
  3298. }
  3299. this._engine.wipeCaches(true);
  3300. this._isDisposed = true;
  3301. }
  3302. public get isDisposed(): boolean {
  3303. return this._isDisposed;
  3304. }
  3305. // Release sounds & sounds tracks
  3306. public disposeSounds() {
  3307. if (!this._mainSoundTrack) {
  3308. return;
  3309. }
  3310. this.mainSoundTrack.dispose();
  3311. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  3312. this.soundTracks[scIndex].dispose();
  3313. }
  3314. }
  3315. // Octrees
  3316. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  3317. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3318. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3319. for (var index = 0; index < this.meshes.length; index++) {
  3320. var mesh = this.meshes[index];
  3321. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  3322. continue;
  3323. }
  3324. mesh.computeWorldMatrix(true);
  3325. let boundingInfo = mesh.getBoundingInfo();
  3326. var minBox = boundingInfo.boundingBox.minimumWorld;
  3327. var maxBox = boundingInfo.boundingBox.maximumWorld;
  3328. Tools.CheckExtends(minBox, min, max);
  3329. Tools.CheckExtends(maxBox, min, max);
  3330. }
  3331. return {
  3332. min: min,
  3333. max: max
  3334. };
  3335. }
  3336. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  3337. if (!this._selectionOctree) {
  3338. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  3339. }
  3340. var worldExtends = this.getWorldExtends();
  3341. // Update octree
  3342. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  3343. return this._selectionOctree;
  3344. }
  3345. // Picking
  3346. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  3347. let result = Ray.Zero();
  3348. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  3349. return result;
  3350. }
  3351. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  3352. var engine = this._engine;
  3353. if (!camera) {
  3354. if (!this.activeCamera)
  3355. throw new Error("Active camera not set");
  3356. camera = this.activeCamera;
  3357. }
  3358. var cameraViewport = camera.viewport;
  3359. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3360. // Moving coordinates to local viewport world
  3361. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3362. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3363. result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  3364. return this;
  3365. }
  3366. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  3367. let result = Ray.Zero();
  3368. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  3369. return result;
  3370. }
  3371. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  3372. if (!PickingInfo) {
  3373. return this;
  3374. }
  3375. var engine = this._engine;
  3376. if (!camera) {
  3377. if (!this.activeCamera)
  3378. throw new Error("Active camera not set");
  3379. camera = this.activeCamera;
  3380. }
  3381. var cameraViewport = camera.viewport;
  3382. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3383. var identity = Matrix.Identity();
  3384. // Moving coordinates to local viewport world
  3385. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3386. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3387. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  3388. return this;
  3389. }
  3390. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  3391. if (!PickingInfo) {
  3392. return null;
  3393. }
  3394. var pickingInfo = null;
  3395. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3396. var mesh = this.meshes[meshIndex];
  3397. if (predicate) {
  3398. if (!predicate(mesh)) {
  3399. continue;
  3400. }
  3401. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3402. continue;
  3403. }
  3404. var world = mesh.getWorldMatrix();
  3405. var ray = rayFunction(world);
  3406. var result = mesh.intersects(ray, fastCheck);
  3407. if (!result || !result.hit)
  3408. continue;
  3409. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3410. continue;
  3411. pickingInfo = result;
  3412. if (fastCheck) {
  3413. break;
  3414. }
  3415. }
  3416. return pickingInfo || new PickingInfo();
  3417. }
  3418. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  3419. if (!PickingInfo) {
  3420. return null;
  3421. }
  3422. var pickingInfos = new Array<PickingInfo>();
  3423. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3424. var mesh = this.meshes[meshIndex];
  3425. if (predicate) {
  3426. if (!predicate(mesh)) {
  3427. continue;
  3428. }
  3429. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3430. continue;
  3431. }
  3432. var world = mesh.getWorldMatrix();
  3433. var ray = rayFunction(world);
  3434. var result = mesh.intersects(ray, false);
  3435. if (!result || !result.hit)
  3436. continue;
  3437. pickingInfos.push(result);
  3438. }
  3439. return pickingInfos;
  3440. }
  3441. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  3442. if (!PickingInfo) {
  3443. return null;
  3444. }
  3445. var pickingInfo = null;
  3446. if (!camera) {
  3447. if (!this.activeCamera) {
  3448. return null;
  3449. }
  3450. camera = this.activeCamera;
  3451. }
  3452. if (this.spriteManagers.length > 0) {
  3453. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  3454. var spriteManager = this.spriteManagers[spriteIndex];
  3455. if (!spriteManager.isPickable) {
  3456. continue;
  3457. }
  3458. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  3459. if (!result || !result.hit)
  3460. continue;
  3461. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3462. continue;
  3463. pickingInfo = result;
  3464. if (fastCheck) {
  3465. break;
  3466. }
  3467. }
  3468. }
  3469. return pickingInfo || new PickingInfo();
  3470. }
  3471. private _tempPickingRay: Nullable<Ray> = Ray ? Ray.Zero() : null;
  3472. /** Launch a ray to try to pick a mesh in the scene
  3473. * @param x position on screen
  3474. * @param y position on screen
  3475. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  3476. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3477. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3478. */
  3479. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  3480. if (!PickingInfo) {
  3481. return null;
  3482. }
  3483. return this._internalPick(world => {
  3484. this.createPickingRayToRef(x, y, world, this._tempPickingRay!, camera || null);
  3485. return this._tempPickingRay!;
  3486. }, predicate, fastCheck);
  3487. }
  3488. /** Launch a ray to try to pick a sprite in the scene
  3489. * @param x position on screen
  3490. * @param y position on screen
  3491. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  3492. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3493. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3494. */
  3495. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  3496. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay!, camera);
  3497. return this._internalPickSprites(this._tempPickingRay!, predicate, fastCheck, camera);
  3498. }
  3499. private _cachedRayForTransform: Ray;
  3500. /** Use the given ray to pick a mesh in the scene
  3501. * @param ray The ray to use to pick meshes
  3502. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  3503. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3504. */
  3505. public pickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  3506. return this._internalPick(world => {
  3507. if (!this._pickWithRayInverseMatrix) {
  3508. this._pickWithRayInverseMatrix = Matrix.Identity();
  3509. }
  3510. world.invertToRef(this._pickWithRayInverseMatrix);
  3511. if (!this._cachedRayForTransform) {
  3512. this._cachedRayForTransform = Ray.Zero();
  3513. }
  3514. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  3515. return this._cachedRayForTransform;
  3516. }, predicate, fastCheck);
  3517. }
  3518. /**
  3519. * Launch a ray to try to pick a mesh in the scene
  3520. * @param x X position on screen
  3521. * @param y Y position on screen
  3522. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  3523. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3524. */
  3525. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): Nullable<PickingInfo[]> {
  3526. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera || null), predicate);
  3527. }
  3528. /**
  3529. * Launch a ray to try to pick a mesh in the scene
  3530. * @param ray Ray to use
  3531. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  3532. */
  3533. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  3534. return this._internalMultiPick(world => {
  3535. if (!this._pickWithRayInverseMatrix) {
  3536. this._pickWithRayInverseMatrix = Matrix.Identity();
  3537. }
  3538. world.invertToRef(this._pickWithRayInverseMatrix);
  3539. if (!this._cachedRayForTransform) {
  3540. this._cachedRayForTransform = Ray.Zero();
  3541. }
  3542. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  3543. return this._cachedRayForTransform;
  3544. }, predicate);
  3545. }
  3546. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  3547. if (this._pointerOverMesh === mesh) {
  3548. return;
  3549. }
  3550. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3551. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3552. }
  3553. this._pointerOverMesh = mesh;
  3554. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3555. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3556. }
  3557. }
  3558. public getPointerOverMesh(): Nullable<AbstractMesh> {
  3559. return this._pointerOverMesh;
  3560. }
  3561. public setPointerOverSprite(sprite: Nullable<Sprite>): void {
  3562. if (this._pointerOverSprite === sprite) {
  3563. return;
  3564. }
  3565. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3566. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3567. }
  3568. this._pointerOverSprite = sprite;
  3569. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3570. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3571. }
  3572. }
  3573. public getPointerOverSprite(): Nullable<Sprite> {
  3574. return this._pointerOverSprite;
  3575. }
  3576. // Physics
  3577. public getPhysicsEngine(): Nullable<PhysicsEngine> {
  3578. return this._physicsEngine;
  3579. }
  3580. /**
  3581. * Enables physics to the current scene
  3582. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  3583. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  3584. * @return {boolean} was the physics engine initialized
  3585. */
  3586. public enablePhysics(gravity: Nullable<Vector3> = null, plugin?: IPhysicsEnginePlugin): boolean {
  3587. if (this._physicsEngine) {
  3588. return true;
  3589. }
  3590. try {
  3591. this._physicsEngine = new PhysicsEngine(gravity, plugin);
  3592. return true;
  3593. } catch (e) {
  3594. Tools.Error(e.message);
  3595. return false;
  3596. }
  3597. }
  3598. public disablePhysicsEngine(): void {
  3599. if (!this._physicsEngine) {
  3600. return;
  3601. }
  3602. this._physicsEngine.dispose();
  3603. this._physicsEngine = null;
  3604. }
  3605. public isPhysicsEnabled(): boolean {
  3606. return this._physicsEngine !== undefined;
  3607. }
  3608. public deleteCompoundImpostor(compound: any): void {
  3609. var mesh: AbstractMesh = compound.parts[0].mesh;
  3610. if (mesh.physicsImpostor) {
  3611. mesh.physicsImpostor.dispose(/*true*/);
  3612. mesh.physicsImpostor = null;
  3613. }
  3614. }
  3615. // Misc.
  3616. public _rebuildGeometries(): void {
  3617. for (var geometry of this._geometries) {
  3618. geometry._rebuild();
  3619. }
  3620. for (var mesh of this.meshes) {
  3621. mesh._rebuild();
  3622. }
  3623. if (this.postProcessManager) {
  3624. this.postProcessManager._rebuild();
  3625. }
  3626. for (var layer of this.layers) {
  3627. layer._rebuild();
  3628. }
  3629. for (var highlightLayer of this.highlightLayers) {
  3630. highlightLayer._rebuild();
  3631. }
  3632. if (this._boundingBoxRenderer) {
  3633. this._boundingBoxRenderer._rebuild();
  3634. }
  3635. for (var system of this.particleSystems) {
  3636. system.rebuild();
  3637. }
  3638. if (this._postProcessRenderPipelineManager) {
  3639. this._postProcessRenderPipelineManager._rebuild();
  3640. }
  3641. }
  3642. public _rebuildTextures(): void {
  3643. for (var texture of this.textures) {
  3644. texture._rebuild();
  3645. }
  3646. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  3647. }
  3648. public createDefaultCameraOrLight(createArcRotateCamera = false, replace = false, attachCameraControls = false) {
  3649. // Dispose existing camera or light in replace mode.
  3650. if (replace) {
  3651. if (this.activeCamera) {
  3652. this.activeCamera.dispose();
  3653. this.activeCamera = null;
  3654. }
  3655. if (this.lights) {
  3656. for (var i = 0; i < this.lights.length; i++) {
  3657. this.lights[i].dispose();
  3658. }
  3659. }
  3660. }
  3661. // Light
  3662. if (this.lights.length === 0) {
  3663. new HemisphericLight("default light", Vector3.Up(), this);
  3664. }
  3665. // Camera
  3666. if (!this.activeCamera) {
  3667. var worldExtends = this.getWorldExtends();
  3668. var worldSize = worldExtends.max.subtract(worldExtends.min);
  3669. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  3670. var camera: TargetCamera;
  3671. var radius = worldSize.length() * 1.5;
  3672. if (createArcRotateCamera) {
  3673. var arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  3674. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  3675. arcRotateCamera.wheelPrecision = 100 / radius;
  3676. camera = arcRotateCamera;
  3677. }
  3678. else {
  3679. var freeCamera = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this);
  3680. freeCamera.setTarget(worldCenter);
  3681. camera = freeCamera;
  3682. }
  3683. camera.minZ = radius * 0.01;
  3684. camera.maxZ = radius * 1000;
  3685. camera.speed = radius * 0.2;
  3686. this.activeCamera = camera;
  3687. let canvas = this.getEngine().getRenderingCanvas();
  3688. if (attachCameraControls && canvas) {
  3689. camera.attachControl(canvas);
  3690. }
  3691. }
  3692. }
  3693. public createDefaultSkybox(environmentTexture?: BaseTexture, pbr = false, scale = 1000, blur = 0): Nullable<Mesh> {
  3694. if (environmentTexture) {
  3695. this.environmentTexture = environmentTexture;
  3696. }
  3697. if (!this.environmentTexture) {
  3698. Tools.Warn("Can not create default skybox without environment texture.");
  3699. return null;
  3700. }
  3701. // Skybox
  3702. var hdrSkybox = Mesh.CreateBox("hdrSkyBox", scale, this);
  3703. if (pbr) {
  3704. let hdrSkyboxMaterial = new PBRMaterial("skyBox", this);
  3705. hdrSkyboxMaterial.backFaceCulling = false;
  3706. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  3707. if (hdrSkyboxMaterial.reflectionTexture) {
  3708. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  3709. }
  3710. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  3711. hdrSkyboxMaterial.disableLighting = true;
  3712. hdrSkyboxMaterial.twoSidedLighting = true;
  3713. hdrSkybox.infiniteDistance = true;
  3714. hdrSkybox.material = hdrSkyboxMaterial;
  3715. }
  3716. else {
  3717. let skyboxMaterial = new StandardMaterial("skyBox", this);
  3718. skyboxMaterial.backFaceCulling = false;
  3719. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  3720. if (skyboxMaterial.reflectionTexture) {
  3721. skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  3722. }
  3723. skyboxMaterial.disableLighting = true;
  3724. hdrSkybox.infiniteDistance = true;
  3725. hdrSkybox.material = skyboxMaterial;
  3726. }
  3727. return hdrSkybox;
  3728. }
  3729. public createDefaultEnvironment(options: Partial<IEnvironmentHelperOptions>): Nullable<EnvironmentHelper> {
  3730. if (EnvironmentHelper) {
  3731. return new EnvironmentHelper(options, this);
  3732. }
  3733. return null;
  3734. }
  3735. public createDefaultVRExperience(webVROptions: VRExperienceHelperOptions = {}): VRExperienceHelper {
  3736. return new VRExperienceHelper(this, webVROptions);
  3737. }
  3738. // Tags
  3739. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  3740. if (tagsQuery === undefined) {
  3741. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  3742. return list;
  3743. }
  3744. var listByTags = [];
  3745. forEach = forEach || ((item: any) => { return; });
  3746. for (var i in list) {
  3747. var item = list[i];
  3748. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  3749. listByTags.push(item);
  3750. forEach(item);
  3751. }
  3752. }
  3753. return listByTags;
  3754. }
  3755. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  3756. return this._getByTags(this.meshes, tagsQuery, forEach);
  3757. }
  3758. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  3759. return this._getByTags(this.cameras, tagsQuery, forEach);
  3760. }
  3761. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  3762. return this._getByTags(this.lights, tagsQuery, forEach);
  3763. }
  3764. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  3765. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  3766. }
  3767. /**
  3768. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  3769. * This allowed control for front to back rendering or reversly depending of the special needs.
  3770. *
  3771. * @param renderingGroupId The rendering group id corresponding to its index
  3772. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  3773. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  3774. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  3775. */
  3776. public setRenderingOrder(renderingGroupId: number,
  3777. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  3778. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  3779. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  3780. this._renderingManager.setRenderingOrder(renderingGroupId,
  3781. opaqueSortCompareFn,
  3782. alphaTestSortCompareFn,
  3783. transparentSortCompareFn);
  3784. }
  3785. /**
  3786. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  3787. *
  3788. * @param renderingGroupId The rendering group id corresponding to its index
  3789. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  3790. * @param depth Automatically clears depth between groups if true and autoClear is true.
  3791. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  3792. */
  3793. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  3794. depth = true,
  3795. stencil = true): void {
  3796. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  3797. }
  3798. /**
  3799. * Will flag all materials as dirty to trigger new shader compilation
  3800. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  3801. */
  3802. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  3803. for (var material of this.materials) {
  3804. if (predicate && !predicate(material)) {
  3805. continue;
  3806. }
  3807. material.markAsDirty(flag);
  3808. }
  3809. }
  3810. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, useDatabase?: boolean, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  3811. let request = Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  3812. this._activeRequests.push(request);
  3813. request.onCompleteObservable.add(request => {
  3814. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  3815. });
  3816. return request;
  3817. }
  3818. }
  3819. }