babylon.scene.ts 201 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990
  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. /**
  636. * The list of layers (background and foreground) of the scene.
  637. */
  638. public layers = new Array<Layer>();
  639. /**
  640. * The list of effect layers (highlights/glow) contained in the scene.
  641. */
  642. public effectLayers = new Array<EffectLayer>();
  643. // Skeletons
  644. private _skeletonsEnabled = true;
  645. public set skeletonsEnabled(value: boolean) {
  646. if (this._skeletonsEnabled === value) {
  647. return;
  648. }
  649. this._skeletonsEnabled = value;
  650. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  651. }
  652. public get skeletonsEnabled(): boolean {
  653. return this._skeletonsEnabled;
  654. }
  655. public skeletons = new Array<Skeleton>();
  656. // Morph targets
  657. public morphTargetManagers = new Array<MorphTargetManager>();
  658. // Lens flares
  659. public lensFlaresEnabled = true;
  660. public lensFlareSystems = new Array<LensFlareSystem>();
  661. // Collisions
  662. public collisionsEnabled = true;
  663. private _workerCollisions: boolean;
  664. public collisionCoordinator: ICollisionCoordinator;
  665. /** Defines the gravity applied to this scene */
  666. public gravity = new Vector3(0, -9.807, 0);
  667. // Postprocesses
  668. public postProcesses = new Array<PostProcess>();
  669. public postProcessesEnabled = true;
  670. public postProcessManager: PostProcessManager;
  671. private _postProcessRenderPipelineManager: PostProcessRenderPipelineManager
  672. public get postProcessRenderPipelineManager(): PostProcessRenderPipelineManager {
  673. if (!this._postProcessRenderPipelineManager) {
  674. this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  675. }
  676. return this._postProcessRenderPipelineManager;
  677. }
  678. // Customs render targets
  679. public renderTargetsEnabled = true;
  680. public dumpNextRenderTargets = false;
  681. public customRenderTargets = new Array<RenderTargetTexture>();
  682. // Delay loading
  683. public useDelayedTextureLoading: boolean;
  684. // Imported meshes
  685. public importedMeshesFiles = new Array<String>();
  686. // Probes
  687. public probesEnabled = true;
  688. public reflectionProbes = new Array<ReflectionProbe>();
  689. // Database
  690. public database: Database;
  691. /**
  692. * This scene's action manager
  693. * @type {BABYLON.ActionManager}
  694. */
  695. public actionManager: ActionManager;
  696. public _actionManagers = new Array<ActionManager>();
  697. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  698. // Procedural textures
  699. public proceduralTexturesEnabled = true;
  700. public _proceduralTextures = new Array<ProceduralTexture>();
  701. // Sound Tracks
  702. private _mainSoundTrack: SoundTrack;
  703. public soundTracks = new Array<SoundTrack>();
  704. private _audioEnabled = true;
  705. private _headphone = false;
  706. public get mainSoundTrack(): SoundTrack {
  707. if (!this._mainSoundTrack) {
  708. this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  709. }
  710. return this._mainSoundTrack;
  711. }
  712. // VR Helper
  713. public VRHelper: VRExperienceHelper;
  714. //Simplification Queue
  715. public simplificationQueue: SimplificationQueue;
  716. // Private
  717. private _engine: Engine;
  718. // Performance counters
  719. private _totalVertices = new PerfCounter();
  720. public _activeIndices = new PerfCounter();
  721. public _activeParticles = new PerfCounter();
  722. public _activeBones = new PerfCounter();
  723. private _animationRatio: number;
  724. private _animationTimeLast: number;
  725. private _animationTime: number = 0;
  726. public animationTimeScale: number = 1;
  727. public _cachedMaterial: Nullable<Material>;
  728. public _cachedEffect: Nullable<Effect>;
  729. public _cachedVisibility: Nullable<number>;
  730. private _renderId = 0;
  731. private _executeWhenReadyTimeoutId = -1;
  732. private _intermediateRendering = false;
  733. private _viewUpdateFlag = -1;
  734. private _projectionUpdateFlag = -1;
  735. private _alternateViewUpdateFlag = -1;
  736. private _alternateProjectionUpdateFlag = -1;
  737. public _toBeDisposed = new SmartArray<Nullable<IDisposable>>(256);
  738. private _activeRequests = new Array<IFileRequest>();
  739. private _pendingData = new Array();
  740. private _isDisposed = false;
  741. public dispatchAllSubMeshesOfActiveMeshes: boolean = false;
  742. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  743. private _processedMaterials = new SmartArray<Material>(256);
  744. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  745. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  746. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  747. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  748. private _renderingManager: RenderingManager;
  749. private _physicsEngine: Nullable<PhysicsEngine>;
  750. public _activeAnimatables = new Array<Animatable>();
  751. private _transformMatrix = Matrix.Zero();
  752. private _sceneUbo: UniformBuffer;
  753. private _alternateSceneUbo: UniformBuffer;
  754. private _pickWithRayInverseMatrix: Matrix;
  755. private _boundingBoxRenderer: BoundingBoxRenderer;
  756. private _outlineRenderer: OutlineRenderer;
  757. private _viewMatrix: Matrix;
  758. private _projectionMatrix: Matrix;
  759. private _alternateViewMatrix: Matrix;
  760. private _alternateProjectionMatrix: Matrix;
  761. private _alternateTransformMatrix: Matrix;
  762. private _useAlternateCameraConfiguration = false;
  763. private _alternateRendering = false;
  764. public _forcedViewPosition: Nullable<Vector3>;
  765. public get _isAlternateRenderingEnabled(): boolean {
  766. return this._alternateRendering;
  767. }
  768. private _frustumPlanes: Plane[];
  769. public get frustumPlanes(): Plane[] {
  770. return this._frustumPlanes;
  771. }
  772. public requireLightSorting = false;
  773. private _selectionOctree: Octree<AbstractMesh>;
  774. private _pointerOverMesh: Nullable<AbstractMesh>;
  775. private _pointerOverSprite: Nullable<Sprite>;
  776. private _debugLayer: DebugLayer;
  777. private _depthRenderer: { [id: string]: DepthRenderer } = {};
  778. private _geometryBufferRenderer: Nullable<GeometryBufferRenderer>;
  779. /**
  780. * Gets the current geometry buffer associated to the scene.
  781. */
  782. public get geometryBufferRenderer(): Nullable<GeometryBufferRenderer> {
  783. return this._geometryBufferRenderer;
  784. }
  785. /**
  786. * Sets the current geometry buffer for the scene.
  787. */
  788. public set geometryBufferRenderer(geometryBufferRenderer: Nullable<GeometryBufferRenderer>) {
  789. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  790. this._geometryBufferRenderer = geometryBufferRenderer;
  791. }
  792. }
  793. private _pickedDownMesh: Nullable<AbstractMesh>;
  794. private _pickedUpMesh: Nullable<AbstractMesh>;
  795. private _pickedDownSprite: Nullable<Sprite>;
  796. private _externalData: StringDictionary<Object>;
  797. private _uid: Nullable<string>;
  798. /**
  799. * @constructor
  800. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  801. */
  802. constructor(engine: Engine) {
  803. this._engine = engine || Engine.LastCreatedEngine;
  804. this._engine.scenes.push(this);
  805. this._uid = null;
  806. this._renderingManager = new RenderingManager(this);
  807. this.postProcessManager = new PostProcessManager(this);
  808. if (OutlineRenderer) {
  809. this._outlineRenderer = new OutlineRenderer(this);
  810. }
  811. if (Tools.IsWindowObjectExist()) {
  812. this.attachControl();
  813. }
  814. //simplification queue
  815. if (SimplificationQueue) {
  816. this.simplificationQueue = new SimplificationQueue();
  817. }
  818. //collision coordinator initialization. For now legacy per default.
  819. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  820. // Uniform Buffer
  821. this._createUbo();
  822. // Default Image processing definition.
  823. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  824. }
  825. // Properties
  826. public get debugLayer(): DebugLayer {
  827. if (!this._debugLayer) {
  828. this._debugLayer = new DebugLayer(this);
  829. }
  830. return this._debugLayer;
  831. }
  832. public set workerCollisions(enabled: boolean) {
  833. if (!CollisionCoordinatorLegacy) {
  834. return;
  835. }
  836. enabled = (enabled && !!Worker && !!CollisionWorker);
  837. this._workerCollisions = enabled;
  838. if (this.collisionCoordinator) {
  839. this.collisionCoordinator.destroy();
  840. }
  841. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  842. this.collisionCoordinator.init(this);
  843. }
  844. public get workerCollisions(): boolean {
  845. return this._workerCollisions;
  846. }
  847. public get selectionOctree(): Octree<AbstractMesh> {
  848. return this._selectionOctree;
  849. }
  850. /**
  851. * The mesh that is currently under the pointer.
  852. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  853. */
  854. public get meshUnderPointer(): Nullable<AbstractMesh> {
  855. return this._pointerOverMesh;
  856. }
  857. /**
  858. * Current on-screen X position of the pointer
  859. * @return {number} X position of the pointer
  860. */
  861. public get pointerX(): number {
  862. return this._pointerX;
  863. }
  864. /**
  865. * Current on-screen Y position of the pointer
  866. * @return {number} Y position of the pointer
  867. */
  868. public get pointerY(): number {
  869. return this._pointerY;
  870. }
  871. public getCachedMaterial(): Nullable<Material> {
  872. return this._cachedMaterial;
  873. }
  874. public getCachedEffect(): Nullable<Effect> {
  875. return this._cachedEffect;
  876. }
  877. public getCachedVisibility(): Nullable<number> {
  878. return this._cachedVisibility;
  879. }
  880. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  881. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  882. }
  883. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  884. if (!this._boundingBoxRenderer) {
  885. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  886. }
  887. return this._boundingBoxRenderer;
  888. }
  889. public getOutlineRenderer(): OutlineRenderer {
  890. return this._outlineRenderer;
  891. }
  892. public getEngine(): Engine {
  893. return this._engine;
  894. }
  895. public getTotalVertices(): number {
  896. return this._totalVertices.current;
  897. }
  898. public get totalVerticesPerfCounter(): PerfCounter {
  899. return this._totalVertices;
  900. }
  901. public getActiveIndices(): number {
  902. return this._activeIndices.current;
  903. }
  904. public get totalActiveIndicesPerfCounter(): PerfCounter {
  905. return this._activeIndices;
  906. }
  907. public getActiveParticles(): number {
  908. return this._activeParticles.current;
  909. }
  910. public get activeParticlesPerfCounter(): PerfCounter {
  911. return this._activeParticles;
  912. }
  913. public getActiveBones(): number {
  914. return this._activeBones.current;
  915. }
  916. public get activeBonesPerfCounter(): PerfCounter {
  917. return this._activeBones;
  918. }
  919. // Stats
  920. public getInterFramePerfCounter(): number {
  921. Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  922. return 0;
  923. }
  924. public get interFramePerfCounter(): Nullable<PerfCounter> {
  925. Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  926. return null;
  927. }
  928. public getLastFrameDuration(): number {
  929. Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  930. return 0;
  931. }
  932. public get lastFramePerfCounter(): Nullable<PerfCounter> {
  933. Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  934. return null;
  935. }
  936. public getEvaluateActiveMeshesDuration(): number {
  937. Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  938. return 0;
  939. }
  940. public get evaluateActiveMeshesDurationPerfCounter(): Nullable<PerfCounter> {
  941. Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  942. return null;
  943. }
  944. public getActiveMeshes(): SmartArray<AbstractMesh> {
  945. return this._activeMeshes;
  946. }
  947. public getRenderTargetsDuration(): number {
  948. Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  949. return 0;
  950. }
  951. public getRenderDuration(): number {
  952. Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  953. return 0;
  954. }
  955. public get renderDurationPerfCounter(): Nullable<PerfCounter> {
  956. Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  957. return null;
  958. }
  959. public getParticlesDuration(): number {
  960. Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  961. return 0;
  962. }
  963. public get particlesDurationPerfCounter(): Nullable<PerfCounter> {
  964. Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  965. return null;
  966. }
  967. public getSpritesDuration(): number {
  968. Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  969. return 0;
  970. }
  971. public get spriteDuractionPerfCounter(): Nullable<PerfCounter> {
  972. Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  973. return null;
  974. }
  975. public getAnimationRatio(): number {
  976. return this._animationRatio;
  977. }
  978. public getRenderId(): number {
  979. return this._renderId;
  980. }
  981. public incrementRenderId(): void {
  982. this._renderId++;
  983. }
  984. private _updatePointerPosition(evt: PointerEvent): void {
  985. var canvasRect = this._engine.getRenderingCanvasClientRect();
  986. if (!canvasRect) {
  987. return;
  988. }
  989. this._pointerX = evt.clientX - canvasRect.left;
  990. this._pointerY = evt.clientY - canvasRect.top;
  991. this._unTranslatedPointerX = this._pointerX;
  992. this._unTranslatedPointerY = this._pointerY;
  993. }
  994. private _createUbo(): void {
  995. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  996. this._sceneUbo.addUniform("viewProjection", 16);
  997. this._sceneUbo.addUniform("view", 16);
  998. }
  999. private _createAlternateUbo(): void {
  1000. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  1001. this._alternateSceneUbo.addUniform("viewProjection", 16);
  1002. this._alternateSceneUbo.addUniform("view", 16);
  1003. }
  1004. // Pointers handling
  1005. /**
  1006. * Use this method to simulate a pointer move on a mesh
  1007. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1008. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1009. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1010. */
  1011. public simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1012. let evt = new PointerEvent("pointermove", pointerEventInit);
  1013. return this._processPointerMove(pickResult, evt);
  1014. }
  1015. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1016. var canvas = this._engine.getRenderingCanvas();
  1017. if (!canvas) {
  1018. return this;
  1019. }
  1020. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1021. this.setPointerOverSprite(null);
  1022. this.setPointerOverMesh(pickResult.pickedMesh);
  1023. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  1024. if (this._pointerOverMesh.actionManager.hoverCursor) {
  1025. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  1026. } else {
  1027. canvas.style.cursor = this.hoverCursor;
  1028. }
  1029. } else {
  1030. canvas.style.cursor = this.defaultCursor;
  1031. }
  1032. } else {
  1033. this.setPointerOverMesh(null);
  1034. // Sprites
  1035. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1036. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1037. this.setPointerOverSprite(pickResult.pickedSprite);
  1038. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  1039. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  1040. } else {
  1041. canvas.style.cursor = this.hoverCursor;
  1042. }
  1043. } else {
  1044. this.setPointerOverSprite(null);
  1045. // Restore pointer
  1046. canvas.style.cursor = this.defaultCursor;
  1047. }
  1048. }
  1049. if (pickResult) {
  1050. if (this.onPointerMove) {
  1051. this.onPointerMove(evt, pickResult);
  1052. }
  1053. if (this.onPointerObservable.hasObservers()) {
  1054. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1055. let pi = new PointerInfo(type, evt, pickResult);
  1056. this.onPointerObservable.notifyObservers(pi, type);
  1057. }
  1058. }
  1059. return this;
  1060. }
  1061. /**
  1062. * Use this method to simulate a pointer down on a mesh
  1063. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1064. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1065. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1066. */
  1067. public simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1068. let evt = new PointerEvent("pointerdown", pointerEventInit);
  1069. return this._processPointerDown(pickResult, evt);
  1070. }
  1071. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1072. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1073. this._pickedDownMesh = pickResult.pickedMesh;
  1074. var actionManager = pickResult.pickedMesh.actionManager;
  1075. if (actionManager) {
  1076. if (actionManager.hasPickTriggers) {
  1077. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1078. switch (evt.button) {
  1079. case 0:
  1080. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1081. break;
  1082. case 1:
  1083. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1084. break;
  1085. case 2:
  1086. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1087. break;
  1088. }
  1089. }
  1090. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  1091. window.setTimeout(() => {
  1092. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1093. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1094. false, this.cameraToUseForPointers);
  1095. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1096. if (this._totalPointersPressed !== 0 &&
  1097. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1098. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  1099. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  1100. this._startingPointerTime = 0;
  1101. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1102. }
  1103. }
  1104. }, Scene.LongPressDelay);
  1105. }
  1106. }
  1107. }
  1108. if (pickResult) {
  1109. if (this.onPointerDown) {
  1110. this.onPointerDown(evt, pickResult);
  1111. }
  1112. if (this.onPointerObservable.hasObservers()) {
  1113. let type = PointerEventTypes.POINTERDOWN;
  1114. let pi = new PointerInfo(type, evt, pickResult);
  1115. this.onPointerObservable.notifyObservers(pi, type);
  1116. }
  1117. }
  1118. return this;
  1119. }
  1120. /**
  1121. * Use this method to simulate a pointer up on a mesh
  1122. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1123. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1124. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1125. */
  1126. public simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1127. let evt = new PointerEvent("pointerup", pointerEventInit);
  1128. let clickInfo = new ClickInfo();
  1129. clickInfo.singleClick = true;
  1130. clickInfo.ignore = true;
  1131. return this._processPointerUp(pickResult, evt, clickInfo);
  1132. }
  1133. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1134. if (pickResult && pickResult && pickResult.pickedMesh) {
  1135. this._pickedUpMesh = pickResult.pickedMesh;
  1136. if (this._pickedDownMesh === this._pickedUpMesh) {
  1137. if (this.onPointerPick) {
  1138. this.onPointerPick(evt, pickResult);
  1139. }
  1140. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1141. let type = PointerEventTypes.POINTERPICK;
  1142. let pi = new PointerInfo(type, evt, pickResult);
  1143. this.onPointerObservable.notifyObservers(pi, type);
  1144. }
  1145. }
  1146. if (pickResult.pickedMesh.actionManager) {
  1147. if (clickInfo.ignore) {
  1148. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1149. }
  1150. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  1151. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1152. }
  1153. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1154. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1155. }
  1156. }
  1157. }
  1158. if (this._pickedDownMesh &&
  1159. this._pickedDownMesh.actionManager &&
  1160. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  1161. this._pickedDownMesh !== this._pickedUpMesh) {
  1162. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1163. }
  1164. if (this.onPointerUp) {
  1165. this.onPointerUp(evt, pickResult);
  1166. }
  1167. if (this.onPointerObservable.hasObservers()) {
  1168. if (!clickInfo.ignore) {
  1169. if (!clickInfo.hasSwiped) {
  1170. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1171. let type = PointerEventTypes.POINTERTAP;
  1172. let pi = new PointerInfo(type, evt, pickResult);
  1173. this.onPointerObservable.notifyObservers(pi, type);
  1174. }
  1175. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1176. let type = PointerEventTypes.POINTERDOUBLETAP;
  1177. let pi = new PointerInfo(type, evt, pickResult);
  1178. this.onPointerObservable.notifyObservers(pi, type);
  1179. }
  1180. }
  1181. }
  1182. else {
  1183. let type = PointerEventTypes.POINTERUP;
  1184. let pi = new PointerInfo(type, evt, pickResult);
  1185. this.onPointerObservable.notifyObservers(pi, type);
  1186. }
  1187. }
  1188. return this;
  1189. }
  1190. /**
  1191. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1192. * @param attachUp defines if you want to attach events to pointerup
  1193. * @param attachDown defines if you want to attach events to pointerdown
  1194. * @param attachMove defines if you want to attach events to pointermove
  1195. */
  1196. public attachControl(attachUp = true, attachDown = true, attachMove = true) {
  1197. this._initActionManager = (act: Nullable<ActionManager>, clickInfo: ClickInfo): Nullable<ActionManager> => {
  1198. if (!this._meshPickProceed) {
  1199. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1200. this._currentPickResult = pickResult;
  1201. if (pickResult) {
  1202. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1203. }
  1204. this._meshPickProceed = true;
  1205. }
  1206. return act;
  1207. };
  1208. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1209. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1210. if ((new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1211. btn !== this._previousButtonPressed) {
  1212. this._doubleClickOccured = false;
  1213. clickInfo.singleClick = true;
  1214. clickInfo.ignore = false;
  1215. cb(clickInfo, this._currentPickResult);
  1216. }
  1217. }
  1218. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1219. let clickInfo = new ClickInfo();
  1220. this._currentPickResult = null;
  1221. let act: Nullable<ActionManager> = null;
  1222. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1223. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1224. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1225. if (!checkPicking && ActionManager && ActionManager.HasPickTriggers) {
  1226. act = this._initActionManager(act, clickInfo);
  1227. if (act)
  1228. checkPicking = act.hasPickTriggers;
  1229. }
  1230. if (checkPicking) {
  1231. let btn = evt.button;
  1232. clickInfo.hasSwiped = Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1233. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1234. if (!clickInfo.hasSwiped) {
  1235. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1236. if (!checkSingleClickImmediately) {
  1237. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1238. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1239. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1240. act = this._initActionManager(act, clickInfo);
  1241. if (act)
  1242. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1243. }
  1244. }
  1245. if (checkSingleClickImmediately) {
  1246. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1247. if (new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1248. btn !== this._previousButtonPressed) {
  1249. clickInfo.singleClick = true;
  1250. cb(clickInfo, this._currentPickResult);
  1251. }
  1252. }
  1253. // at least one double click is required to be check and exclusive double click is enabled
  1254. else {
  1255. // wait that no double click has been raised during the double click delay
  1256. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1257. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1258. }
  1259. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1260. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1261. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1262. act = this._initActionManager(act, clickInfo);
  1263. if (act)
  1264. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1265. }
  1266. if (checkDoubleClick) {
  1267. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1268. if (btn === this._previousButtonPressed &&
  1269. new Date().getTime() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1270. !this._doubleClickOccured
  1271. ) {
  1272. // pointer has not moved for 2 clicks, it's a double click
  1273. if (!clickInfo.hasSwiped &&
  1274. Math.abs(this._previousStartingPointerPosition.x - this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  1275. Math.abs(this._previousStartingPointerPosition.y - this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  1276. this._previousStartingPointerTime = 0;
  1277. this._doubleClickOccured = true;
  1278. clickInfo.doubleClick = true;
  1279. clickInfo.ignore = false;
  1280. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1281. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1282. }
  1283. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1284. cb(clickInfo, this._currentPickResult);
  1285. }
  1286. // if the two successive clicks are too far, it's just two simple clicks
  1287. else {
  1288. this._doubleClickOccured = false;
  1289. this._previousStartingPointerTime = this._startingPointerTime;
  1290. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1291. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1292. this._previousButtonPressed = btn;
  1293. if (Scene.ExclusiveDoubleClickMode) {
  1294. if (this._previousDelayedSimpleClickTimeout) {
  1295. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1296. }
  1297. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1298. cb(clickInfo, this._previousPickResult);
  1299. }
  1300. else {
  1301. cb(clickInfo, this._currentPickResult);
  1302. }
  1303. }
  1304. }
  1305. // just the first click of the double has been raised
  1306. else {
  1307. this._doubleClickOccured = false;
  1308. this._previousStartingPointerTime = this._startingPointerTime;
  1309. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1310. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1311. this._previousButtonPressed = btn;
  1312. }
  1313. }
  1314. }
  1315. }
  1316. clickInfo.ignore = true;
  1317. cb(clickInfo, this._currentPickResult);
  1318. };
  1319. this._spritePredicate = (sprite: Sprite): boolean => {
  1320. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  1321. };
  1322. this._onPointerMove = (evt: PointerEvent) => {
  1323. this._updatePointerPosition(evt);
  1324. // PreObservable support
  1325. if (this.onPrePointerObservable.hasObservers()) {
  1326. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1327. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1328. this.onPrePointerObservable.notifyObservers(pi, type);
  1329. if (pi.skipOnPointerObservable) {
  1330. return;
  1331. }
  1332. }
  1333. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1334. return;
  1335. }
  1336. if (!this.pointerMovePredicate) {
  1337. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1338. }
  1339. // Meshes
  1340. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1341. this._processPointerMove(pickResult, evt);
  1342. };
  1343. this._onPointerDown = (evt: PointerEvent) => {
  1344. this._totalPointersPressed++;
  1345. this._pickedDownMesh = null;
  1346. this._meshPickProceed = false;
  1347. this._updatePointerPosition(evt);
  1348. if (this.preventDefaultOnPointerDown && canvas) {
  1349. evt.preventDefault();
  1350. canvas.focus();
  1351. }
  1352. // PreObservable support
  1353. if (this.onPrePointerObservable.hasObservers()) {
  1354. let type = PointerEventTypes.POINTERDOWN;
  1355. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1356. this.onPrePointerObservable.notifyObservers(pi, type);
  1357. if (pi.skipOnPointerObservable) {
  1358. return;
  1359. }
  1360. }
  1361. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1362. return;
  1363. }
  1364. this._startingPointerPosition.x = this._pointerX;
  1365. this._startingPointerPosition.y = this._pointerY;
  1366. this._startingPointerTime = new Date().getTime();
  1367. if (!this.pointerDownPredicate) {
  1368. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1369. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1370. };
  1371. }
  1372. // Meshes
  1373. this._pickedDownMesh = null;
  1374. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1375. this._processPointerDown(pickResult, evt);
  1376. // Sprites
  1377. this._pickedDownSprite = null;
  1378. if (this.spriteManagers.length > 0) {
  1379. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1380. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1381. if (pickResult.pickedSprite.actionManager) {
  1382. this._pickedDownSprite = pickResult.pickedSprite;
  1383. switch (evt.button) {
  1384. case 0:
  1385. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1386. break;
  1387. case 1:
  1388. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1389. break;
  1390. case 2:
  1391. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1392. break;
  1393. }
  1394. if (pickResult.pickedSprite.actionManager) {
  1395. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1396. }
  1397. }
  1398. }
  1399. }
  1400. };
  1401. this._onPointerUp = (evt: PointerEvent) => {
  1402. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1403. return; // So we need to test it the pointer down was pressed before.
  1404. }
  1405. this._totalPointersPressed--;
  1406. this._pickedUpMesh = null;
  1407. this._meshPickProceed = false;
  1408. this._updatePointerPosition(evt);
  1409. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1410. // PreObservable support
  1411. if (this.onPrePointerObservable.hasObservers()) {
  1412. if (!clickInfo.ignore) {
  1413. if (!clickInfo.hasSwiped) {
  1414. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1415. let type = PointerEventTypes.POINTERTAP;
  1416. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1417. this.onPrePointerObservable.notifyObservers(pi, type);
  1418. if (pi.skipOnPointerObservable) {
  1419. return;
  1420. }
  1421. }
  1422. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1423. let type = PointerEventTypes.POINTERDOUBLETAP;
  1424. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1425. this.onPrePointerObservable.notifyObservers(pi, type);
  1426. if (pi.skipOnPointerObservable) {
  1427. return;
  1428. }
  1429. }
  1430. }
  1431. }
  1432. else {
  1433. let type = PointerEventTypes.POINTERUP;
  1434. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1435. this.onPrePointerObservable.notifyObservers(pi, type);
  1436. if (pi.skipOnPointerObservable) {
  1437. return;
  1438. }
  1439. }
  1440. }
  1441. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1442. return;
  1443. }
  1444. if (!this.pointerUpPredicate) {
  1445. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1446. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1447. };
  1448. }
  1449. // Meshes
  1450. if (!this._meshPickProceed && (ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1451. this._initActionManager(null, clickInfo);
  1452. }
  1453. if (!pickResult) {
  1454. pickResult = this._currentPickResult;
  1455. }
  1456. this._processPointerUp(pickResult, evt, clickInfo);
  1457. // Sprites
  1458. if (this.spriteManagers.length > 0) {
  1459. let spritePickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1460. if (spritePickResult) {
  1461. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  1462. if (spritePickResult.pickedSprite.actionManager) {
  1463. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1464. if (spritePickResult.pickedSprite.actionManager) {
  1465. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  1466. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1467. }
  1468. }
  1469. }
  1470. }
  1471. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== spritePickResult.pickedSprite) {
  1472. this._pickedDownSprite.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  1473. }
  1474. }
  1475. }
  1476. this._previousPickResult = this._currentPickResult;
  1477. });
  1478. };
  1479. this._onKeyDown = (evt: KeyboardEvent) => {
  1480. let type = KeyboardEventTypes.KEYDOWN;
  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.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1494. }
  1495. };
  1496. this._onKeyUp = (evt: KeyboardEvent) => {
  1497. let type = KeyboardEventTypes.KEYUP;
  1498. if (this.onPreKeyboardObservable.hasObservers()) {
  1499. let pi = new KeyboardInfoPre(type, evt);
  1500. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1501. if (pi.skipOnPointerObservable) {
  1502. return;
  1503. }
  1504. }
  1505. if (this.onKeyboardObservable.hasObservers()) {
  1506. let pi = new KeyboardInfo(type, evt);
  1507. this.onKeyboardObservable.notifyObservers(pi, type);
  1508. }
  1509. if (this.actionManager) {
  1510. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1511. }
  1512. };
  1513. let engine = this.getEngine();
  1514. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(() => {
  1515. if (!canvas) {
  1516. return;
  1517. }
  1518. canvas.addEventListener("keydown", this._onKeyDown, false);
  1519. canvas.addEventListener("keyup", this._onKeyUp, false);
  1520. });
  1521. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(() => {
  1522. if (!canvas) {
  1523. return;
  1524. }
  1525. canvas.removeEventListener("keydown", this._onKeyDown);
  1526. canvas.removeEventListener("keyup", this._onKeyUp);
  1527. });
  1528. var eventPrefix = Tools.GetPointerPrefix();
  1529. var canvas = this._engine.getRenderingCanvas();
  1530. if (!canvas) {
  1531. return;
  1532. }
  1533. if (attachMove) {
  1534. canvas.addEventListener(eventPrefix + "move", <any>this._onPointerMove, false);
  1535. // Wheel
  1536. canvas.addEventListener('mousewheel', <any>this._onPointerMove, false);
  1537. canvas.addEventListener('DOMMouseScroll', <any>this._onPointerMove, false);
  1538. }
  1539. if (attachDown) {
  1540. canvas.addEventListener(eventPrefix + "down", <any>this._onPointerDown, false);
  1541. }
  1542. if (attachUp) {
  1543. window.addEventListener(eventPrefix + "up", <any>this._onPointerUp, false);
  1544. }
  1545. canvas.tabIndex = 1;
  1546. }
  1547. public detachControl() {
  1548. let engine = this.getEngine();
  1549. var eventPrefix = Tools.GetPointerPrefix();
  1550. var canvas = engine.getRenderingCanvas();
  1551. if (!canvas) {
  1552. return;
  1553. }
  1554. canvas.removeEventListener(eventPrefix + "move", <any>this._onPointerMove);
  1555. canvas.removeEventListener(eventPrefix + "down", <any>this._onPointerDown);
  1556. window.removeEventListener(eventPrefix + "up", <any>this._onPointerUp);
  1557. if (this._onCanvasBlurObserver) {
  1558. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1559. }
  1560. if (this._onCanvasFocusObserver) {
  1561. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1562. }
  1563. // Wheel
  1564. canvas.removeEventListener('mousewheel', <any>this._onPointerMove);
  1565. canvas.removeEventListener('DOMMouseScroll', <any>this._onPointerMove);
  1566. // Keyboard
  1567. canvas.removeEventListener("keydown", this._onKeyDown);
  1568. canvas.removeEventListener("keyup", this._onKeyUp);
  1569. // Observables
  1570. this.onKeyboardObservable.clear();
  1571. this.onPreKeyboardObservable.clear();
  1572. this.onPointerObservable.clear();
  1573. this.onPrePointerObservable.clear();
  1574. }
  1575. /**
  1576. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  1577. * Delay loaded resources are not taking in account
  1578. * @return true if all required resources are ready
  1579. */
  1580. public isReady(): boolean {
  1581. if (this._isDisposed) {
  1582. return false;
  1583. }
  1584. if (this._pendingData.length > 0) {
  1585. return false;
  1586. }
  1587. let index: number;
  1588. let engine = this.getEngine();
  1589. // Geometries
  1590. for (index = 0; index < this._geometries.length; index++) {
  1591. var geometry = this._geometries[index];
  1592. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1593. return false;
  1594. }
  1595. }
  1596. // Meshes
  1597. for (index = 0; index < this.meshes.length; index++) {
  1598. var mesh = this.meshes[index];
  1599. if (!mesh.isEnabled()) {
  1600. continue;
  1601. }
  1602. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1603. continue;
  1604. }
  1605. if (!mesh.isReady(true)) {
  1606. return false;
  1607. }
  1608. // Effect layers
  1609. let hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && (<Mesh>mesh).instances.length > 0;
  1610. for (var layer of this.effectLayers) {
  1611. if (!layer.hasMesh(mesh)) {
  1612. continue;
  1613. }
  1614. for (var subMesh of mesh.subMeshes) {
  1615. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  1616. return false;
  1617. }
  1618. }
  1619. }
  1620. }
  1621. // Particles
  1622. for (var particleSystem of this.particleSystems) {
  1623. if (!particleSystem.isReady()) {
  1624. return false;
  1625. }
  1626. }
  1627. return true;
  1628. }
  1629. public resetCachedMaterial(): void {
  1630. this._cachedMaterial = null;
  1631. this._cachedEffect = null;
  1632. this._cachedVisibility = null;
  1633. }
  1634. public registerBeforeRender(func: () => void): void {
  1635. this.onBeforeRenderObservable.add(func);
  1636. }
  1637. public unregisterBeforeRender(func: () => void): void {
  1638. this.onBeforeRenderObservable.removeCallback(func);
  1639. }
  1640. public registerAfterRender(func: () => void): void {
  1641. this.onAfterRenderObservable.add(func);
  1642. }
  1643. public unregisterAfterRender(func: () => void): void {
  1644. this.onAfterRenderObservable.removeCallback(func);
  1645. }
  1646. private _executeOnceBeforeRender(func: () => void): void {
  1647. let execFunc = () => {
  1648. func();
  1649. setTimeout(() => {
  1650. this.unregisterBeforeRender(execFunc);
  1651. });
  1652. }
  1653. this.registerBeforeRender(execFunc);
  1654. }
  1655. /**
  1656. * The provided function will run before render once and will be disposed afterwards.
  1657. * A timeout delay can be provided so that the function will be executed in N ms.
  1658. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  1659. * @param func The function to be executed.
  1660. * @param timeout optional delay in ms
  1661. */
  1662. public executeOnceBeforeRender(func: () => void, timeout?: number): void {
  1663. if (timeout !== undefined) {
  1664. setTimeout(() => {
  1665. this._executeOnceBeforeRender(func);
  1666. }, timeout);
  1667. } else {
  1668. this._executeOnceBeforeRender(func);
  1669. }
  1670. }
  1671. public _addPendingData(data: any): void {
  1672. this._pendingData.push(data);
  1673. }
  1674. public _removePendingData(data: any): void {
  1675. var wasLoading = this.isLoading;
  1676. var index = this._pendingData.indexOf(data);
  1677. if (index !== -1) {
  1678. this._pendingData.splice(index, 1);
  1679. }
  1680. if (wasLoading && !this.isLoading) {
  1681. this.onDataLoadedObservable.notifyObservers(this);
  1682. }
  1683. }
  1684. public getWaitingItemsCount(): number {
  1685. return this._pendingData.length;
  1686. }
  1687. public get isLoading(): boolean {
  1688. return this._pendingData.length > 0;
  1689. }
  1690. /**
  1691. * Registers a function to be executed when the scene is ready.
  1692. * @param {Function} func - the function to be executed.
  1693. */
  1694. public executeWhenReady(func: () => void): void {
  1695. this.onReadyObservable.add(func);
  1696. if (this._executeWhenReadyTimeoutId !== -1) {
  1697. return;
  1698. }
  1699. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1700. this._checkIsReady();
  1701. }, 150);
  1702. }
  1703. /**
  1704. * Returns a promise that resolves when the scene is ready.
  1705. * @returns A promise that resolves when the scene is ready.
  1706. */
  1707. public whenReadyAsync(): Promise<void> {
  1708. return new Promise(resolve => {
  1709. this.executeWhenReady(() => {
  1710. resolve();
  1711. });
  1712. });
  1713. }
  1714. public _checkIsReady() {
  1715. if (this.isReady()) {
  1716. this.onReadyObservable.notifyObservers(this);
  1717. this.onReadyObservable.clear();
  1718. this._executeWhenReadyTimeoutId = -1;
  1719. return;
  1720. }
  1721. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1722. this._checkIsReady();
  1723. }, 150);
  1724. }
  1725. // Animations
  1726. /**
  1727. * Will start the animation sequence of a given target
  1728. * @param target - the target
  1729. * @param {number} from - from which frame should animation start
  1730. * @param {number} to - till which frame should animation run.
  1731. * @param {boolean} [loop] - should the animation loop
  1732. * @param {number} [speedRatio] - the speed in which to run the animation
  1733. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  1734. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  1735. * Returns {BABYLON.Animatable} the animatable object created for this animation
  1736. * See BABYLON.Animatable
  1737. */
  1738. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  1739. if (from > to && speedRatio > 0) {
  1740. speedRatio *= -1;
  1741. }
  1742. this.stopAnimation(target);
  1743. if (!animatable) {
  1744. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  1745. }
  1746. // Local animations
  1747. if (target.animations) {
  1748. animatable.appendAnimations(target, target.animations);
  1749. }
  1750. // Children animations
  1751. if (target.getAnimatables) {
  1752. var animatables = target.getAnimatables();
  1753. for (var index = 0; index < animatables.length; index++) {
  1754. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  1755. }
  1756. }
  1757. animatable.reset();
  1758. return animatable;
  1759. }
  1760. /**
  1761. * Begin a new animation on a given node
  1762. * @param {BABYLON.Node} node defines the root node where the animation will take place
  1763. * @param {BABYLON.Animation[]} defines the list of animations to start
  1764. * @param {number} from defines the initial value
  1765. * @param {number} to defines the final value
  1766. * @param {boolean} loop defines if you want animation to loop (off by default)
  1767. * @param {number} speedRatio defines the speed ratio to apply to all animations
  1768. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  1769. * @returns the list of created animatables
  1770. */
  1771. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  1772. if (speedRatio === undefined) {
  1773. speedRatio = 1.0;
  1774. }
  1775. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  1776. return animatable;
  1777. }
  1778. /**
  1779. * Begin a new animation on a given node and its hierarchy
  1780. * @param {BABYLON.Node} node defines the root node where the animation will take place
  1781. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  1782. * @param {BABYLON.Animation[]} defines the list of animations to start
  1783. * @param {number} from defines the initial value
  1784. * @param {number} to defines the final value
  1785. * @param {boolean} loop defines if you want animation to loop (off by default)
  1786. * @param {number} speedRatio defines the speed ratio to apply to all animations
  1787. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  1788. * @returns the list of animatables created for all nodes
  1789. */
  1790. public beginDirectHierarchyAnimation(target: Node, directDescendantsOnly: boolean, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable[] {
  1791. let children = target.getDescendants(directDescendantsOnly);
  1792. let result = [];
  1793. for (var child of children) {
  1794. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  1795. }
  1796. return result;
  1797. }
  1798. public getAnimatableByTarget(target: any): Nullable<Animatable> {
  1799. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1800. if (this._activeAnimatables[index].target === target) {
  1801. return this._activeAnimatables[index];
  1802. }
  1803. }
  1804. return null;
  1805. }
  1806. public get animatables(): Animatable[] {
  1807. return this._activeAnimatables;
  1808. }
  1809. /**
  1810. * Will stop the animation of the given target
  1811. * @param target - the target
  1812. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  1813. * @see beginAnimation
  1814. */
  1815. public stopAnimation(target: any, animationName?: string): void {
  1816. var animatable = this.getAnimatableByTarget(target);
  1817. if (animatable) {
  1818. animatable.stop(animationName);
  1819. }
  1820. }
  1821. /**
  1822. * Stops and removes all animations that have been applied to the scene
  1823. */
  1824. public stopAllAnimations(): void {
  1825. if (this._activeAnimatables) {
  1826. for (let i = 0; i < this._activeAnimatables.length; i++) {
  1827. this._activeAnimatables[i].stop();
  1828. }
  1829. this._activeAnimatables = [];
  1830. }
  1831. }
  1832. private _animate(): void {
  1833. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  1834. return;
  1835. }
  1836. // Getting time
  1837. var now = Tools.Now;
  1838. if (!this._animationTimeLast) {
  1839. if (this._pendingData.length > 0) {
  1840. return;
  1841. }
  1842. this._animationTimeLast = now;
  1843. }
  1844. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  1845. this._animationTime += deltaTime;
  1846. this._animationTimeLast = now;
  1847. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1848. this._activeAnimatables[index]._animate(this._animationTime);
  1849. }
  1850. }
  1851. // Matrix
  1852. public _switchToAlternateCameraConfiguration(active: boolean): void {
  1853. this._useAlternateCameraConfiguration = active;
  1854. }
  1855. public getViewMatrix(): Matrix {
  1856. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  1857. }
  1858. public getProjectionMatrix(): Matrix {
  1859. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  1860. }
  1861. public getTransformMatrix(): Matrix {
  1862. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  1863. }
  1864. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  1865. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  1866. return;
  1867. }
  1868. this._viewUpdateFlag = view.updateFlag;
  1869. this._projectionUpdateFlag = projection.updateFlag;
  1870. this._viewMatrix = view;
  1871. this._projectionMatrix = projection;
  1872. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1873. // Update frustum
  1874. if (!this._frustumPlanes) {
  1875. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1876. } else {
  1877. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1878. }
  1879. if (this.activeCamera && this.activeCamera._alternateCamera) {
  1880. let otherCamera = this.activeCamera._alternateCamera;
  1881. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  1882. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  1883. }
  1884. if (this._sceneUbo.useUbo) {
  1885. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  1886. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  1887. this._sceneUbo.update();
  1888. }
  1889. }
  1890. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  1891. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  1892. return;
  1893. }
  1894. this._alternateViewUpdateFlag = view.updateFlag;
  1895. this._alternateProjectionUpdateFlag = projection.updateFlag;
  1896. this._alternateViewMatrix = view;
  1897. this._alternateProjectionMatrix = projection;
  1898. if (!this._alternateTransformMatrix) {
  1899. this._alternateTransformMatrix = Matrix.Zero();
  1900. }
  1901. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  1902. if (!this._alternateSceneUbo) {
  1903. this._createAlternateUbo();
  1904. }
  1905. if (this._alternateSceneUbo.useUbo) {
  1906. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  1907. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  1908. this._alternateSceneUbo.update();
  1909. }
  1910. }
  1911. public getSceneUniformBuffer(): UniformBuffer {
  1912. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  1913. }
  1914. // Methods
  1915. public getUniqueId() {
  1916. var result = Scene._uniqueIdCounter;
  1917. Scene._uniqueIdCounter++;
  1918. return result;
  1919. }
  1920. public addMesh(newMesh: AbstractMesh) {
  1921. this.meshes.push(newMesh);
  1922. //notify the collision coordinator
  1923. if (this.collisionCoordinator) {
  1924. this.collisionCoordinator.onMeshAdded(newMesh);
  1925. }
  1926. newMesh._resyncLightSources();
  1927. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  1928. }
  1929. public removeMesh(toRemove: AbstractMesh): number {
  1930. var index = this.meshes.indexOf(toRemove);
  1931. if (index !== -1) {
  1932. // Remove from the scene if mesh found
  1933. this.meshes.splice(index, 1);
  1934. }
  1935. this.onMeshRemovedObservable.notifyObservers(toRemove);
  1936. return index;
  1937. }
  1938. public addTransformNode(newTransformNode: TransformNode) {
  1939. this.transformNodes.push(newTransformNode);
  1940. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  1941. }
  1942. public removeTransformNode(toRemove: TransformNode): number {
  1943. var index = this.transformNodes.indexOf(toRemove);
  1944. if (index !== -1) {
  1945. // Remove from the scene if found
  1946. this.transformNodes.splice(index, 1);
  1947. }
  1948. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  1949. return index;
  1950. }
  1951. public removeSkeleton(toRemove: Skeleton): number {
  1952. var index = this.skeletons.indexOf(toRemove);
  1953. if (index !== -1) {
  1954. // Remove from the scene if found
  1955. this.skeletons.splice(index, 1);
  1956. }
  1957. return index;
  1958. }
  1959. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  1960. var index = this.morphTargetManagers.indexOf(toRemove);
  1961. if (index !== -1) {
  1962. // Remove from the scene if found
  1963. this.morphTargetManagers.splice(index, 1);
  1964. }
  1965. return index;
  1966. }
  1967. public removeLight(toRemove: Light): number {
  1968. var index = this.lights.indexOf(toRemove);
  1969. if (index !== -1) {
  1970. // Remove from meshes
  1971. for (var mesh of this.meshes) {
  1972. mesh._removeLightSource(toRemove);
  1973. }
  1974. // Remove from the scene if mesh found
  1975. this.lights.splice(index, 1);
  1976. this.sortLightsByPriority();
  1977. }
  1978. this.onLightRemovedObservable.notifyObservers(toRemove);
  1979. return index;
  1980. }
  1981. public removeCamera(toRemove: Camera): number {
  1982. var index = this.cameras.indexOf(toRemove);
  1983. if (index !== -1) {
  1984. // Remove from the scene if mesh found
  1985. this.cameras.splice(index, 1);
  1986. }
  1987. // Remove from activeCameras
  1988. var index2 = this.activeCameras.indexOf(toRemove);
  1989. if (index2 !== -1) {
  1990. // Remove from the scene if mesh found
  1991. this.activeCameras.splice(index2, 1);
  1992. }
  1993. // Reset the activeCamera
  1994. if (this.activeCamera === toRemove) {
  1995. if (this.cameras.length > 0) {
  1996. this.activeCamera = this.cameras[0];
  1997. } else {
  1998. this.activeCamera = null;
  1999. }
  2000. }
  2001. this.onCameraRemovedObservable.notifyObservers(toRemove);
  2002. return index;
  2003. }
  2004. public removeParticleSystem(toRemove: IParticleSystem): number {
  2005. var index = this.particleSystems.indexOf(toRemove);
  2006. if (index !== -1) {
  2007. this.particleSystems.splice(index, 1);
  2008. }
  2009. return index;
  2010. };
  2011. public removeAnimation(toRemove: Animation): number {
  2012. var index = this.animations.indexOf(toRemove);
  2013. if (index !== -1) {
  2014. this.animations.splice(index, 1);
  2015. }
  2016. return index;
  2017. };
  2018. public removeMultiMaterial(toRemove: MultiMaterial): number {
  2019. var index = this.multiMaterials.indexOf(toRemove);
  2020. if (index !== -1) {
  2021. this.multiMaterials.splice(index, 1);
  2022. }
  2023. return index;
  2024. };
  2025. public removeMaterial(toRemove: Material): number {
  2026. var index = this.materials.indexOf(toRemove);
  2027. if (index !== -1) {
  2028. this.materials.splice(index, 1);
  2029. }
  2030. return index;
  2031. };
  2032. public removeLensFlareSystem(toRemove: LensFlareSystem) {
  2033. var index = this.lensFlareSystems.indexOf(toRemove);
  2034. if (index !== -1) {
  2035. this.lensFlareSystems.splice(index, 1);
  2036. }
  2037. return index;
  2038. };
  2039. public removeActionManager(toRemove: ActionManager) {
  2040. var index = this._actionManagers.indexOf(toRemove);
  2041. if (index !== -1) {
  2042. this._actionManagers.splice(index, 1);
  2043. }
  2044. return index;
  2045. };
  2046. public addLight(newLight: Light) {
  2047. this.lights.push(newLight);
  2048. this.sortLightsByPriority();
  2049. // Add light to all meshes (To support if the light is removed and then readded)
  2050. for (var mesh of this.meshes) {
  2051. if (mesh._lightSources.indexOf(newLight) === -1) {
  2052. mesh._lightSources.push(newLight);
  2053. mesh._resyncLightSources();
  2054. }
  2055. }
  2056. this.onNewLightAddedObservable.notifyObservers(newLight);
  2057. }
  2058. public sortLightsByPriority(): void {
  2059. if (this.requireLightSorting) {
  2060. this.lights.sort(Light.CompareLightsPriority);
  2061. }
  2062. }
  2063. public addCamera(newCamera: Camera) {
  2064. this.cameras.push(newCamera);
  2065. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  2066. }
  2067. public addSkeleton(newSkeleton: Skeleton) {
  2068. this.skeletons.push(newSkeleton)
  2069. }
  2070. public addParticleSystem(newParticleSystem: IParticleSystem) {
  2071. this.particleSystems.push(newParticleSystem)
  2072. }
  2073. public addAnimation(newAnimation: Animation) {
  2074. this.animations.push(newAnimation)
  2075. }
  2076. public addMultiMaterial(newMultiMaterial: MultiMaterial) {
  2077. this.multiMaterials.push(newMultiMaterial)
  2078. }
  2079. public addMaterial(newMaterial: Material) {
  2080. this.materials.push(newMaterial)
  2081. }
  2082. public addMorphTargetManager(newMorphTargetManager: MorphTargetManager) {
  2083. this.morphTargetManagers.push(newMorphTargetManager)
  2084. }
  2085. public addGeometry(newGeometrie: Geometry) {
  2086. this._geometries.push(newGeometrie)
  2087. }
  2088. public addLensFlareSystem(newLensFlareSystem: LensFlareSystem) {
  2089. this.lensFlareSystems.push(newLensFlareSystem)
  2090. }
  2091. public addActionManager(newActionManager: ActionManager) {
  2092. this._actionManagers.push(newActionManager)
  2093. }
  2094. /**
  2095. * Switch active camera
  2096. * @param {Camera} newCamera - new active camera
  2097. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  2098. */
  2099. public switchActiveCamera(newCamera: Camera, attachControl = true) {
  2100. var canvas = this._engine.getRenderingCanvas();
  2101. if (!canvas) {
  2102. return;
  2103. }
  2104. if (this.activeCamera) {
  2105. this.activeCamera.detachControl(canvas);
  2106. }
  2107. this.activeCamera = newCamera;
  2108. if (attachControl) {
  2109. newCamera.attachControl(canvas);
  2110. }
  2111. }
  2112. /**
  2113. * sets the active camera of the scene using its ID
  2114. * @param {string} id - the camera's ID
  2115. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  2116. * @see activeCamera
  2117. */
  2118. public setActiveCameraByID(id: string): Nullable<Camera> {
  2119. var camera = this.getCameraByID(id);
  2120. if (camera) {
  2121. this.activeCamera = camera;
  2122. return camera;
  2123. }
  2124. return null;
  2125. }
  2126. /**
  2127. * sets the active camera of the scene using its name
  2128. * @param {string} name - the camera's name
  2129. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  2130. * @see activeCamera
  2131. */
  2132. public setActiveCameraByName(name: string): Nullable<Camera> {
  2133. var camera = this.getCameraByName(name);
  2134. if (camera) {
  2135. this.activeCamera = camera;
  2136. return camera;
  2137. }
  2138. return null;
  2139. }
  2140. /**
  2141. * get an animation group using its name
  2142. * @param {string} the material's name
  2143. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  2144. */
  2145. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  2146. for (var index = 0; index < this.animationGroups.length; index++) {
  2147. if (this.animationGroups[index].name === name) {
  2148. return this.animationGroups[index];
  2149. }
  2150. }
  2151. return null;
  2152. }
  2153. /**
  2154. * get a material using its id
  2155. * @param {string} the material's ID
  2156. * @return {BABYLON.Material|null} the material or null if none found.
  2157. */
  2158. public getMaterialByID(id: string): Nullable<Material> {
  2159. for (var index = 0; index < this.materials.length; index++) {
  2160. if (this.materials[index].id === id) {
  2161. return this.materials[index];
  2162. }
  2163. }
  2164. return null;
  2165. }
  2166. /**
  2167. * get a material using its name
  2168. * @param {string} the material's name
  2169. * @return {BABYLON.Material|null} the material or null if none found.
  2170. */
  2171. public getMaterialByName(name: string): Nullable<Material> {
  2172. for (var index = 0; index < this.materials.length; index++) {
  2173. if (this.materials[index].name === name) {
  2174. return this.materials[index];
  2175. }
  2176. }
  2177. return null;
  2178. }
  2179. public getLensFlareSystemByName(name: string): Nullable<LensFlareSystem> {
  2180. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  2181. if (this.lensFlareSystems[index].name === name) {
  2182. return this.lensFlareSystems[index];
  2183. }
  2184. }
  2185. return null;
  2186. }
  2187. public getLensFlareSystemByID(id: string): Nullable<LensFlareSystem> {
  2188. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  2189. if (this.lensFlareSystems[index].id === id) {
  2190. return this.lensFlareSystems[index];
  2191. }
  2192. }
  2193. return null;
  2194. }
  2195. public getCameraByID(id: string): Nullable<Camera> {
  2196. for (var index = 0; index < this.cameras.length; index++) {
  2197. if (this.cameras[index].id === id) {
  2198. return this.cameras[index];
  2199. }
  2200. }
  2201. return null;
  2202. }
  2203. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  2204. for (var index = 0; index < this.cameras.length; index++) {
  2205. if (this.cameras[index].uniqueId === uniqueId) {
  2206. return this.cameras[index];
  2207. }
  2208. }
  2209. return null;
  2210. }
  2211. /**
  2212. * get a camera using its name
  2213. * @param {string} the camera's name
  2214. * @return {BABYLON.Camera|null} the camera or null if none found.
  2215. */
  2216. public getCameraByName(name: string): Nullable<Camera> {
  2217. for (var index = 0; index < this.cameras.length; index++) {
  2218. if (this.cameras[index].name === name) {
  2219. return this.cameras[index];
  2220. }
  2221. }
  2222. return null;
  2223. }
  2224. /**
  2225. * get a bone using its id
  2226. * @param {string} the bone's id
  2227. * @return {BABYLON.Bone|null} the bone or null if not found
  2228. */
  2229. public getBoneByID(id: string): Nullable<Bone> {
  2230. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2231. var skeleton = this.skeletons[skeletonIndex];
  2232. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2233. if (skeleton.bones[boneIndex].id === id) {
  2234. return skeleton.bones[boneIndex];
  2235. }
  2236. }
  2237. }
  2238. return null;
  2239. }
  2240. /**
  2241. * get a bone using its id
  2242. * @param {string} the bone's name
  2243. * @return {BABYLON.Bone|null} the bone or null if not found
  2244. */
  2245. public getBoneByName(name: string): Nullable<Bone> {
  2246. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2247. var skeleton = this.skeletons[skeletonIndex];
  2248. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2249. if (skeleton.bones[boneIndex].name === name) {
  2250. return skeleton.bones[boneIndex];
  2251. }
  2252. }
  2253. }
  2254. return null;
  2255. }
  2256. /**
  2257. * get a light node using its name
  2258. * @param {string} the light's name
  2259. * @return {BABYLON.Light|null} the light or null if none found.
  2260. */
  2261. public getLightByName(name: string): Nullable<Light> {
  2262. for (var index = 0; index < this.lights.length; index++) {
  2263. if (this.lights[index].name === name) {
  2264. return this.lights[index];
  2265. }
  2266. }
  2267. return null;
  2268. }
  2269. /**
  2270. * get a light node using its ID
  2271. * @param {string} the light's id
  2272. * @return {BABYLON.Light|null} the light or null if none found.
  2273. */
  2274. public getLightByID(id: string): Nullable<Light> {
  2275. for (var index = 0; index < this.lights.length; index++) {
  2276. if (this.lights[index].id === id) {
  2277. return this.lights[index];
  2278. }
  2279. }
  2280. return null;
  2281. }
  2282. /**
  2283. * get a light node using its scene-generated unique ID
  2284. * @param {number} the light's unique id
  2285. * @return {BABYLON.Light|null} the light or null if none found.
  2286. */
  2287. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  2288. for (var index = 0; index < this.lights.length; index++) {
  2289. if (this.lights[index].uniqueId === uniqueId) {
  2290. return this.lights[index];
  2291. }
  2292. }
  2293. return null;
  2294. }
  2295. /**
  2296. * get a particle system by id
  2297. * @param id {number} the particle system id
  2298. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  2299. */
  2300. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  2301. for (var index = 0; index < this.particleSystems.length; index++) {
  2302. if (this.particleSystems[index].id === id) {
  2303. return this.particleSystems[index];
  2304. }
  2305. }
  2306. return null;
  2307. }
  2308. /**
  2309. * get a geometry using its ID
  2310. * @param {string} the geometry's id
  2311. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  2312. */
  2313. public getGeometryByID(id: string): Nullable<Geometry> {
  2314. for (var index = 0; index < this._geometries.length; index++) {
  2315. if (this._geometries[index].id === id) {
  2316. return this._geometries[index];
  2317. }
  2318. }
  2319. return null;
  2320. }
  2321. /**
  2322. * add a new geometry to this scene.
  2323. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  2324. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  2325. * @return {boolean} was the geometry added or not
  2326. */
  2327. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  2328. if (!force && this.getGeometryByID(geometry.id)) {
  2329. return false;
  2330. }
  2331. this._geometries.push(geometry);
  2332. //notify the collision coordinator
  2333. if (this.collisionCoordinator) {
  2334. this.collisionCoordinator.onGeometryAdded(geometry);
  2335. }
  2336. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  2337. return true;
  2338. }
  2339. /**
  2340. * Removes an existing geometry
  2341. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  2342. * @return {boolean} was the geometry removed or not
  2343. */
  2344. public removeGeometry(geometry: Geometry): boolean {
  2345. var index = this._geometries.indexOf(geometry);
  2346. if (index > -1) {
  2347. this._geometries.splice(index, 1);
  2348. //notify the collision coordinator
  2349. if (this.collisionCoordinator) {
  2350. this.collisionCoordinator.onGeometryDeleted(geometry);
  2351. }
  2352. this.onGeometryRemovedObservable.notifyObservers(geometry);
  2353. return true;
  2354. }
  2355. return false;
  2356. }
  2357. public getGeometries(): Geometry[] {
  2358. return this._geometries;
  2359. }
  2360. /**
  2361. * Get the first added mesh found of a given ID
  2362. * @param {string} id - the id to search for
  2363. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2364. */
  2365. public getMeshByID(id: string): Nullable<AbstractMesh> {
  2366. for (var index = 0; index < this.meshes.length; index++) {
  2367. if (this.meshes[index].id === id) {
  2368. return this.meshes[index];
  2369. }
  2370. }
  2371. return null;
  2372. }
  2373. public getMeshesByID(id: string): Array<AbstractMesh> {
  2374. return this.meshes.filter(function (m) {
  2375. return m.id === id;
  2376. })
  2377. }
  2378. /**
  2379. * Get the first added transform node found of a given ID
  2380. * @param {string} id - the id to search for
  2381. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  2382. */
  2383. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  2384. for (var index = 0; index < this.transformNodes.length; index++) {
  2385. if (this.transformNodes[index].id === id) {
  2386. return this.transformNodes[index];
  2387. }
  2388. }
  2389. return null;
  2390. }
  2391. public getTransformNodesByID(id: string): Array<TransformNode> {
  2392. return this.transformNodes.filter(function (m) {
  2393. return m.id === id;
  2394. })
  2395. }
  2396. /**
  2397. * Get a mesh with its auto-generated unique id
  2398. * @param {number} uniqueId - the unique id to search for
  2399. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2400. */
  2401. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  2402. for (var index = 0; index < this.meshes.length; index++) {
  2403. if (this.meshes[index].uniqueId === uniqueId) {
  2404. return this.meshes[index];
  2405. }
  2406. }
  2407. return null;
  2408. }
  2409. /**
  2410. * Get a the last added mesh found of a given ID
  2411. * @param {string} id - the id to search for
  2412. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2413. */
  2414. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  2415. for (var index = this.meshes.length - 1; index >= 0; index--) {
  2416. if (this.meshes[index].id === id) {
  2417. return this.meshes[index];
  2418. }
  2419. }
  2420. return null;
  2421. }
  2422. /**
  2423. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  2424. * @param {string} id - the id to search for
  2425. * @return {BABYLON.Node|null} the node found or null if not found at all.
  2426. */
  2427. public getLastEntryByID(id: string): Nullable<Node> {
  2428. var index: number;
  2429. for (index = this.meshes.length - 1; index >= 0; index--) {
  2430. if (this.meshes[index].id === id) {
  2431. return this.meshes[index];
  2432. }
  2433. }
  2434. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  2435. if (this.transformNodes[index].id === id) {
  2436. return this.transformNodes[index];
  2437. }
  2438. }
  2439. for (index = this.cameras.length - 1; index >= 0; index--) {
  2440. if (this.cameras[index].id === id) {
  2441. return this.cameras[index];
  2442. }
  2443. }
  2444. for (index = this.lights.length - 1; index >= 0; index--) {
  2445. if (this.lights[index].id === id) {
  2446. return this.lights[index];
  2447. }
  2448. }
  2449. return null;
  2450. }
  2451. public getNodeByID(id: string): Nullable<Node> {
  2452. var mesh = this.getMeshByID(id);
  2453. if (mesh) {
  2454. return mesh;
  2455. }
  2456. var light = this.getLightByID(id);
  2457. if (light) {
  2458. return light;
  2459. }
  2460. var camera = this.getCameraByID(id);
  2461. if (camera) {
  2462. return camera;
  2463. }
  2464. var bone = this.getBoneByID(id);
  2465. return bone;
  2466. }
  2467. public getNodeByName(name: string): Nullable<Node> {
  2468. var mesh = this.getMeshByName(name);
  2469. if (mesh) {
  2470. return mesh;
  2471. }
  2472. var light = this.getLightByName(name);
  2473. if (light) {
  2474. return light;
  2475. }
  2476. var camera = this.getCameraByName(name);
  2477. if (camera) {
  2478. return camera;
  2479. }
  2480. var bone = this.getBoneByName(name);
  2481. return bone;
  2482. }
  2483. public getMeshByName(name: string): Nullable<AbstractMesh> {
  2484. for (var index = 0; index < this.meshes.length; index++) {
  2485. if (this.meshes[index].name === name) {
  2486. return this.meshes[index];
  2487. }
  2488. }
  2489. return null;
  2490. }
  2491. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  2492. for (var index = 0; index < this.transformNodes.length; index++) {
  2493. if (this.transformNodes[index].name === name) {
  2494. return this.transformNodes[index];
  2495. }
  2496. }
  2497. return null;
  2498. }
  2499. public getSoundByName(name: string): Nullable<Sound> {
  2500. var index: number;
  2501. if (AudioEngine) {
  2502. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  2503. if (this.mainSoundTrack.soundCollection[index].name === name) {
  2504. return this.mainSoundTrack.soundCollection[index];
  2505. }
  2506. }
  2507. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  2508. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  2509. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  2510. return this.soundTracks[sdIndex].soundCollection[index];
  2511. }
  2512. }
  2513. }
  2514. }
  2515. return null;
  2516. }
  2517. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  2518. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  2519. if (this.skeletons[index].id === id) {
  2520. return this.skeletons[index];
  2521. }
  2522. }
  2523. return null;
  2524. }
  2525. public getSkeletonById(id: string): Nullable<Skeleton> {
  2526. for (var index = 0; index < this.skeletons.length; index++) {
  2527. if (this.skeletons[index].id === id) {
  2528. return this.skeletons[index];
  2529. }
  2530. }
  2531. return null;
  2532. }
  2533. public getSkeletonByName(name: string): Nullable<Skeleton> {
  2534. for (var index = 0; index < this.skeletons.length; index++) {
  2535. if (this.skeletons[index].name === name) {
  2536. return this.skeletons[index];
  2537. }
  2538. }
  2539. return null;
  2540. }
  2541. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  2542. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  2543. if (this.morphTargetManagers[index].uniqueId === id) {
  2544. return this.morphTargetManagers[index];
  2545. }
  2546. }
  2547. return null;
  2548. }
  2549. public isActiveMesh(mesh: AbstractMesh): boolean {
  2550. return (this._activeMeshes.indexOf(mesh) !== -1);
  2551. }
  2552. /**
  2553. * Return a the first highlight layer of the scene with a given name.
  2554. * @param name The name of the highlight layer to look for.
  2555. * @return The highlight layer if found otherwise null.
  2556. */
  2557. public getHighlightLayerByName(name: string): Nullable<HighlightLayer> {
  2558. for (var index = 0; index < this.effectLayers.length; index++) {
  2559. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  2560. return (<any>this.effectLayers[index]) as HighlightLayer;
  2561. }
  2562. }
  2563. return null;
  2564. }
  2565. /**
  2566. * Return a the first highlight layer of the scene with a given name.
  2567. * @param name The name of the highlight layer to look for.
  2568. * @return The highlight layer if found otherwise null.
  2569. */
  2570. public getGlowLayerByName(name: string): Nullable<GlowLayer> {
  2571. for (var index = 0; index < this.effectLayers.length; index++) {
  2572. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  2573. return (<any>this.effectLayers[index]) as GlowLayer;
  2574. }
  2575. }
  2576. return null;
  2577. }
  2578. /**
  2579. * Return a unique id as a string which can serve as an identifier for the scene
  2580. */
  2581. public get uid(): string {
  2582. if (!this._uid) {
  2583. this._uid = Tools.RandomId();
  2584. }
  2585. return this._uid;
  2586. }
  2587. /**
  2588. * Add an externaly attached data from its key.
  2589. * This method call will fail and return false, if such key already exists.
  2590. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2591. * @param key the unique key that identifies the data
  2592. * @param data the data object to associate to the key for this Engine instance
  2593. * @return true if no such key were already present and the data was added successfully, false otherwise
  2594. */
  2595. public addExternalData<T>(key: string, data: T): boolean {
  2596. if (!this._externalData) {
  2597. this._externalData = new StringDictionary<Object>();
  2598. }
  2599. return this._externalData.add(key, data);
  2600. }
  2601. /**
  2602. * Get an externaly attached data from its key
  2603. * @param key the unique key that identifies the data
  2604. * @return the associated data, if present (can be null), or undefined if not present
  2605. */
  2606. public getExternalData<T>(key: string): Nullable<T> {
  2607. if (!this._externalData) {
  2608. return null;
  2609. }
  2610. return <T>this._externalData.get(key);
  2611. }
  2612. /**
  2613. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2614. * @param key the unique key that identifies the data
  2615. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2616. * @return the associated data, can be null if the factory returned null.
  2617. */
  2618. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2619. if (!this._externalData) {
  2620. this._externalData = new StringDictionary<Object>();
  2621. }
  2622. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2623. }
  2624. /**
  2625. * Remove an externaly attached data from the Engine instance
  2626. * @param key the unique key that identifies the data
  2627. * @return true if the data was successfully removed, false if it doesn't exist
  2628. */
  2629. public removeExternalData(key: string): boolean {
  2630. return this._externalData.remove(key);
  2631. }
  2632. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  2633. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  2634. if (mesh.showSubMeshesBoundingBox) {
  2635. const boundingInfo = subMesh.getBoundingInfo();
  2636. if (boundingInfo !== null && boundingInfo !== undefined) {
  2637. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  2638. }
  2639. }
  2640. const material = subMesh.getMaterial();
  2641. if (material !== null && material !== undefined) {
  2642. // Render targets
  2643. if (material.getRenderTargetTextures !== undefined) {
  2644. if (this._processedMaterials.indexOf(material) === -1) {
  2645. this._processedMaterials.push(material);
  2646. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  2647. }
  2648. }
  2649. // Dispatch
  2650. this._activeIndices.addCount(subMesh.indexCount, false);
  2651. this._renderingManager.dispatch(subMesh, mesh, material);
  2652. }
  2653. }
  2654. }
  2655. /**
  2656. * Clear the processed materials smart array preventing retention point in material dispose.
  2657. */
  2658. public freeProcessedMaterials(): void {
  2659. this._processedMaterials.dispose();
  2660. }
  2661. /**
  2662. * Clear the active meshes smart array preventing retention point in mesh dispose.
  2663. */
  2664. public freeActiveMeshes(): void {
  2665. this._activeMeshes.dispose();
  2666. if (this.activeCamera && this.activeCamera._activeMeshes) {
  2667. this.activeCamera._activeMeshes.dispose();
  2668. }
  2669. if (this.activeCameras) {
  2670. for (let i = 0; i < this.activeCameras.length; i++) {
  2671. let activeCamera = this.activeCameras[i];
  2672. if (activeCamera && activeCamera._activeMeshes) {
  2673. activeCamera._activeMeshes.dispose();
  2674. }
  2675. }
  2676. }
  2677. }
  2678. /**
  2679. * Clear the info related to rendering groups preventing retention points during dispose.
  2680. */
  2681. public freeRenderingGroups(): void {
  2682. if (this._renderingManager) {
  2683. this._renderingManager.freeRenderingGroups();
  2684. }
  2685. if (this.textures) {
  2686. for (let i = 0; i < this.textures.length; i++) {
  2687. let texture = this.textures[i];
  2688. if (texture && (<RenderTargetTexture>texture).renderList) {
  2689. (<RenderTargetTexture>texture).freeRenderingGroups();
  2690. }
  2691. }
  2692. }
  2693. }
  2694. public _isInIntermediateRendering(): boolean {
  2695. return this._intermediateRendering
  2696. }
  2697. private _activeMeshCandidateProvider: IActiveMeshCandidateProvider;
  2698. public setActiveMeshCandidateProvider(provider: IActiveMeshCandidateProvider): void {
  2699. this._activeMeshCandidateProvider = provider;
  2700. }
  2701. public getActiveMeshCandidateProvider(): IActiveMeshCandidateProvider {
  2702. return this._activeMeshCandidateProvider;
  2703. }
  2704. private _activeMeshesFrozen = false;
  2705. /**
  2706. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  2707. */
  2708. public freezeActiveMeshes(): Scene {
  2709. if (!this.activeCamera) {
  2710. return this;
  2711. }
  2712. if (!this._frustumPlanes) {
  2713. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  2714. }
  2715. this._evaluateActiveMeshes();
  2716. this._activeMeshesFrozen = true;
  2717. return this;
  2718. }
  2719. /**
  2720. * Use this function to restart evaluating active meshes on every frame
  2721. */
  2722. public unfreezeActiveMeshes() {
  2723. this._activeMeshesFrozen = false;
  2724. return this;
  2725. }
  2726. private _evaluateActiveMeshes(): void {
  2727. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  2728. return;
  2729. }
  2730. if (!this.activeCamera) {
  2731. return;
  2732. }
  2733. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  2734. this.activeCamera._activeMeshes.reset();
  2735. this._activeMeshes.reset();
  2736. this._renderingManager.reset();
  2737. this._processedMaterials.reset();
  2738. this._activeParticleSystems.reset();
  2739. this._activeSkeletons.reset();
  2740. this._softwareSkinnedMeshes.reset();
  2741. if (this._boundingBoxRenderer) {
  2742. this._boundingBoxRenderer.reset();
  2743. }
  2744. // Meshes
  2745. var meshes: AbstractMesh[];
  2746. var len: number;
  2747. var checkIsEnabled = true;
  2748. // Determine mesh candidates
  2749. if (this._activeMeshCandidateProvider !== undefined) {
  2750. // Use _activeMeshCandidateProvider
  2751. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  2752. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  2753. if (meshes !== undefined) {
  2754. len = meshes.length;
  2755. } else {
  2756. len = 0;
  2757. }
  2758. } else if (this._selectionOctree !== undefined) {
  2759. // Octree
  2760. var selection = this._selectionOctree.select(this._frustumPlanes);
  2761. meshes = selection.data;
  2762. len = selection.length;
  2763. } else {
  2764. // Full scene traversal
  2765. len = this.meshes.length;
  2766. meshes = this.meshes;
  2767. }
  2768. // Check each mesh
  2769. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  2770. mesh = meshes[meshIndex];
  2771. if (mesh.isBlocked) {
  2772. continue;
  2773. }
  2774. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  2775. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  2776. continue;
  2777. }
  2778. mesh.computeWorldMatrix();
  2779. // Intersections
  2780. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  2781. this._meshesForIntersections.pushNoDuplicate(mesh);
  2782. }
  2783. // Switch to current LOD
  2784. meshLOD = mesh.getLOD(this.activeCamera);
  2785. if (meshLOD === undefined || meshLOD === null) {
  2786. continue;
  2787. }
  2788. mesh._preActivate();
  2789. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  2790. this._activeMeshes.push(mesh);
  2791. this.activeCamera._activeMeshes.push(mesh);
  2792. mesh._activate(this._renderId);
  2793. if (meshLOD !== mesh) {
  2794. meshLOD._activate(this._renderId);
  2795. }
  2796. this._activeMesh(mesh, meshLOD);
  2797. }
  2798. }
  2799. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  2800. // Particle systems
  2801. if (this.particlesEnabled) {
  2802. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  2803. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  2804. var particleSystem = this.particleSystems[particleIndex];
  2805. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  2806. continue;
  2807. }
  2808. let emitter = <any>particleSystem.emitter;
  2809. if (!emitter.position || emitter.isEnabled()) {
  2810. this._activeParticleSystems.push(particleSystem);
  2811. particleSystem.animate();
  2812. this._renderingManager.dispatchParticles(particleSystem);
  2813. }
  2814. }
  2815. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  2816. }
  2817. }
  2818. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  2819. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  2820. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  2821. mesh.skeleton.prepare();
  2822. }
  2823. if (!mesh.computeBonesUsingShaders) {
  2824. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  2825. }
  2826. }
  2827. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  2828. let boundingInfo = sourceMesh.getBoundingInfo();
  2829. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  2830. }
  2831. if (
  2832. mesh !== undefined && mesh !== null
  2833. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  2834. ) {
  2835. // Submeshes Octrees
  2836. var len: number;
  2837. var subMeshes: SubMesh[];
  2838. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  2839. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  2840. len = intersections.length;
  2841. subMeshes = intersections.data;
  2842. } else {
  2843. subMeshes = mesh.subMeshes;
  2844. len = subMeshes.length;
  2845. }
  2846. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  2847. subMesh = subMeshes[subIndex];
  2848. this._evaluateSubMesh(subMesh, mesh);
  2849. }
  2850. }
  2851. }
  2852. public updateTransformMatrix(force?: boolean): void {
  2853. if (!this.activeCamera) {
  2854. return;
  2855. }
  2856. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  2857. }
  2858. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  2859. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  2860. }
  2861. private _renderForCamera(camera: Camera, rigParent?: Camera): void {
  2862. if (camera && camera._skipRendering) {
  2863. return;
  2864. }
  2865. var engine = this._engine;
  2866. this.activeCamera = camera;
  2867. if (!this.activeCamera)
  2868. throw new Error("Active camera not set");
  2869. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2870. // Viewport
  2871. engine.setViewport(this.activeCamera.viewport);
  2872. // Camera
  2873. this.resetCachedMaterial();
  2874. this._renderId++;
  2875. this.updateTransformMatrix();
  2876. if (camera._alternateCamera) {
  2877. this.updateAlternateTransformMatrix(camera._alternateCamera);
  2878. this._alternateRendering = true;
  2879. }
  2880. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  2881. // Meshes
  2882. this._evaluateActiveMeshes();
  2883. // Software skinning
  2884. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  2885. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  2886. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  2887. }
  2888. // Render targets
  2889. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  2890. var needsRestoreFrameBuffer = false;
  2891. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  2892. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  2893. }
  2894. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  2895. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  2896. }
  2897. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  2898. this._intermediateRendering = true;
  2899. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2900. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  2901. let renderTarget = this._renderTargets.data[renderIndex];
  2902. if (renderTarget._shouldRender()) {
  2903. this._renderId++;
  2904. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  2905. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  2906. }
  2907. }
  2908. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2909. this._intermediateRendering = false;
  2910. this._renderId++;
  2911. needsRestoreFrameBuffer = true; // Restore back buffer
  2912. }
  2913. // Render EffecttLayer Texture
  2914. var stencilState = this._engine.getStencilBuffer();
  2915. var renderEffects = false;
  2916. var needStencil = false;
  2917. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  2918. this._intermediateRendering = true;
  2919. for (let i = 0; i < this.effectLayers.length; i++) {
  2920. let effectLayer = this.effectLayers[i];
  2921. if (effectLayer.shouldRender() &&
  2922. (!effectLayer.camera ||
  2923. (effectLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  2924. (effectLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  2925. renderEffects = true;
  2926. needStencil = needStencil || effectLayer.needStencil();
  2927. let renderTarget = (<RenderTargetTexture>(<any>effectLayer)._mainTexture);
  2928. if (renderTarget._shouldRender()) {
  2929. this._renderId++;
  2930. renderTarget.render(false, false);
  2931. needsRestoreFrameBuffer = true;
  2932. }
  2933. }
  2934. }
  2935. this._intermediateRendering = false;
  2936. this._renderId++;
  2937. }
  2938. if (needsRestoreFrameBuffer) {
  2939. engine.restoreDefaultFramebuffer(); // Restore back buffer
  2940. }
  2941. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  2942. // Prepare Frame
  2943. this.postProcessManager._prepareFrame();
  2944. // Backgrounds
  2945. var layerIndex;
  2946. var layer;
  2947. if (this.layers.length) {
  2948. engine.setDepthBuffer(false);
  2949. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2950. layer = this.layers[layerIndex];
  2951. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2952. layer.render();
  2953. }
  2954. }
  2955. engine.setDepthBuffer(true);
  2956. }
  2957. // Activate effect Layer stencil
  2958. if (needStencil) {
  2959. this._engine.setStencilBuffer(true);
  2960. }
  2961. // Render
  2962. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  2963. this._renderingManager.render(null, null, true, true);
  2964. this.onAfterDrawPhaseObservable.notifyObservers(this);
  2965. // Restore effect Layer stencil
  2966. if (needStencil) {
  2967. this._engine.setStencilBuffer(stencilState);
  2968. }
  2969. // Bounding boxes
  2970. if (this._boundingBoxRenderer) {
  2971. this._boundingBoxRenderer.render();
  2972. }
  2973. // Lens flares
  2974. if (this.lensFlaresEnabled) {
  2975. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2976. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  2977. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  2978. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  2979. lensFlareSystem.render();
  2980. }
  2981. }
  2982. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2983. }
  2984. // Foregrounds
  2985. if (this.layers.length) {
  2986. engine.setDepthBuffer(false);
  2987. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2988. layer = this.layers[layerIndex];
  2989. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2990. layer.render();
  2991. }
  2992. }
  2993. engine.setDepthBuffer(true);
  2994. }
  2995. // Effect Layer
  2996. if (renderEffects) {
  2997. engine.setDepthBuffer(false);
  2998. for (let i = 0; i < this.effectLayers.length; i++) {
  2999. if (this.effectLayers[i].shouldRender()) {
  3000. this.effectLayers[i].render();
  3001. }
  3002. }
  3003. engine.setDepthBuffer(true);
  3004. }
  3005. // Finalize frame
  3006. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  3007. // Reset some special arrays
  3008. this._renderTargets.reset();
  3009. this._alternateRendering = false;
  3010. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  3011. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  3012. }
  3013. private _processSubCameras(camera: Camera): void {
  3014. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  3015. this._renderForCamera(camera);
  3016. return;
  3017. }
  3018. // rig cameras
  3019. for (var index = 0; index < camera._rigCameras.length; index++) {
  3020. this._renderForCamera(camera._rigCameras[index], camera);
  3021. }
  3022. this.activeCamera = camera;
  3023. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3024. }
  3025. private _checkIntersections(): void {
  3026. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  3027. var sourceMesh = this._meshesForIntersections.data[index];
  3028. if (!sourceMesh.actionManager) {
  3029. continue;
  3030. }
  3031. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  3032. var action = sourceMesh.actionManager.actions[actionIndex];
  3033. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3034. var parameters = action.getTriggerParameter();
  3035. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  3036. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  3037. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  3038. if (areIntersecting && currentIntersectionInProgress === -1) {
  3039. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  3040. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3041. sourceMesh._intersectionsInProgress.push(otherMesh);
  3042. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3043. sourceMesh._intersectionsInProgress.push(otherMesh);
  3044. }
  3045. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  3046. //They intersected, and now they don't.
  3047. //is this trigger an exit trigger? execute an event.
  3048. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3049. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3050. }
  3051. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  3052. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  3053. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  3054. }
  3055. }
  3056. }
  3057. }
  3058. }
  3059. }
  3060. public render(): void {
  3061. if (this.isDisposed) {
  3062. return;
  3063. }
  3064. this._activeParticles.fetchNewFrame();
  3065. this._totalVertices.fetchNewFrame();
  3066. this._activeIndices.fetchNewFrame();
  3067. this._activeBones.fetchNewFrame();
  3068. this._meshesForIntersections.reset();
  3069. this.resetCachedMaterial();
  3070. this.onBeforeAnimationsObservable.notifyObservers(this);
  3071. // Actions
  3072. if (this.actionManager) {
  3073. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger);
  3074. }
  3075. //Simplification Queue
  3076. if (this.simplificationQueue && !this.simplificationQueue.running) {
  3077. this.simplificationQueue.executeNext();
  3078. }
  3079. if (this._engine.isDeterministicLockStep()) {
  3080. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  3081. var defaultFPS = (60.0 / 1000.0);
  3082. let defaultFrameTime = 1000 / 60; // frame time in MS
  3083. if (this._physicsEngine) {
  3084. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  3085. }
  3086. let stepsTaken = 0;
  3087. var maxSubSteps = this._engine.getLockstepMaxSteps();
  3088. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  3089. internalSteps = Math.min(internalSteps, maxSubSteps);
  3090. do {
  3091. this.onBeforeStepObservable.notifyObservers(this);
  3092. // Animations
  3093. this._animationRatio = defaultFrameTime * defaultFPS;
  3094. this._animate();
  3095. this.onAfterAnimationsObservable.notifyObservers(this);
  3096. // Physics
  3097. if (this._physicsEngine) {
  3098. this.onBeforePhysicsObservable.notifyObservers(this);
  3099. this._physicsEngine._step(defaultFrameTime / 1000);
  3100. this.onAfterPhysicsObservable.notifyObservers(this);
  3101. }
  3102. this.onAfterStepObservable.notifyObservers(this);
  3103. this._currentStepId++;
  3104. stepsTaken++;
  3105. deltaTime -= defaultFrameTime;
  3106. } while (deltaTime > 0 && stepsTaken < internalSteps);
  3107. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  3108. }
  3109. else {
  3110. // Animations
  3111. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  3112. this._animationRatio = deltaTime * (60.0 / 1000.0);
  3113. this._animate();
  3114. this.onAfterAnimationsObservable.notifyObservers(this);
  3115. // Physics
  3116. if (this._physicsEngine) {
  3117. this.onBeforePhysicsObservable.notifyObservers(this);
  3118. this._physicsEngine._step(deltaTime / 1000.0);
  3119. this.onAfterPhysicsObservable.notifyObservers(this);
  3120. }
  3121. }
  3122. // update gamepad manager
  3123. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  3124. this._gamepadManager._checkGamepadsStatus();
  3125. }
  3126. // Update Cameras
  3127. if (this.activeCameras.length > 0) {
  3128. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3129. let camera = this.activeCameras[cameraIndex];
  3130. camera.update();
  3131. if (camera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3132. // rig cameras
  3133. for (var index = 0; index < camera._rigCameras.length; index++) {
  3134. camera._rigCameras[index].update();
  3135. }
  3136. }
  3137. }
  3138. } else if (this.activeCamera) {
  3139. this.activeCamera.update();
  3140. if (this.activeCamera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3141. // rig cameras
  3142. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  3143. this.activeCamera._rigCameras[index].update();
  3144. }
  3145. }
  3146. }
  3147. // Before render
  3148. this.onBeforeRenderObservable.notifyObservers(this);
  3149. // Customs render targets
  3150. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3151. var engine = this.getEngine();
  3152. var currentActiveCamera = this.activeCamera;
  3153. if (this.renderTargetsEnabled) {
  3154. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3155. this._intermediateRendering = true;
  3156. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  3157. var renderTarget = this.customRenderTargets[customIndex];
  3158. if (renderTarget._shouldRender()) {
  3159. this._renderId++;
  3160. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  3161. if (!this.activeCamera)
  3162. throw new Error("Active camera not set");
  3163. // Viewport
  3164. engine.setViewport(this.activeCamera.viewport);
  3165. // Camera
  3166. this.updateTransformMatrix();
  3167. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  3168. }
  3169. }
  3170. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3171. this._intermediateRendering = false;
  3172. this._renderId++;
  3173. }
  3174. // Restore back buffer
  3175. if (this.customRenderTargets.length > 0) {
  3176. engine.restoreDefaultFramebuffer();
  3177. }
  3178. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  3179. this.activeCamera = currentActiveCamera;
  3180. // Procedural textures
  3181. if (this.proceduralTexturesEnabled) {
  3182. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  3183. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  3184. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  3185. if (proceduralTexture._shouldRender()) {
  3186. proceduralTexture.render();
  3187. }
  3188. }
  3189. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  3190. }
  3191. // Clear
  3192. if (this.autoClearDepthAndStencil || this.autoClear) {
  3193. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  3194. }
  3195. // Shadows
  3196. if (this.shadowsEnabled) {
  3197. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  3198. var light = this.lights[lightIndex];
  3199. var shadowGenerator = light.getShadowGenerator();
  3200. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  3201. var shadowMap = <RenderTargetTexture>(shadowGenerator.getShadowMap());
  3202. if (this.textures.indexOf(shadowMap) !== -1) {
  3203. this._renderTargets.push(shadowMap);
  3204. }
  3205. }
  3206. }
  3207. }
  3208. // Depth renderer
  3209. for (var key in this._depthRenderer) {
  3210. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  3211. }
  3212. // Geometry renderer
  3213. if (this._geometryBufferRenderer) {
  3214. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  3215. }
  3216. // RenderPipeline
  3217. if (this._postProcessRenderPipelineManager) {
  3218. this._postProcessRenderPipelineManager.update();
  3219. }
  3220. // Multi-cameras?
  3221. if (this.activeCameras.length > 0) {
  3222. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3223. if (cameraIndex > 0) {
  3224. this._engine.clear(null, false, true, true);
  3225. }
  3226. this._processSubCameras(this.activeCameras[cameraIndex]);
  3227. }
  3228. } else {
  3229. if (!this.activeCamera) {
  3230. throw new Error("No camera defined");
  3231. }
  3232. this._processSubCameras(this.activeCamera);
  3233. }
  3234. // Intersection checks
  3235. this._checkIntersections();
  3236. // Update the audio listener attached to the camera
  3237. if (AudioEngine) {
  3238. this._updateAudioParameters();
  3239. }
  3240. // After render
  3241. if (this.afterRender) {
  3242. this.afterRender();
  3243. }
  3244. this.onAfterRenderObservable.notifyObservers(this);
  3245. // Cleaning
  3246. for (var index = 0; index < this._toBeDisposed.length; index++) {
  3247. var data = this._toBeDisposed.data[index];
  3248. if (data) {
  3249. data.dispose();
  3250. }
  3251. this._toBeDisposed[index] = null;
  3252. }
  3253. this._toBeDisposed.reset();
  3254. if (this.dumpNextRenderTargets) {
  3255. this.dumpNextRenderTargets = false;
  3256. }
  3257. this._activeBones.addCount(0, true);
  3258. this._activeIndices.addCount(0, true);
  3259. this._activeParticles.addCount(0, true);
  3260. }
  3261. private _updateAudioParameters() {
  3262. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  3263. return;
  3264. }
  3265. var listeningCamera: Nullable<Camera>;
  3266. var audioEngine = Engine.audioEngine;
  3267. if (this.activeCameras.length > 0) {
  3268. listeningCamera = this.activeCameras[0];
  3269. } else {
  3270. listeningCamera = this.activeCamera;
  3271. }
  3272. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  3273. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  3274. // for VR cameras
  3275. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  3276. listeningCamera = listeningCamera.rigCameras[0];
  3277. }
  3278. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  3279. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  3280. cameraDirection.normalize();
  3281. // To avoid some errors on GearVR
  3282. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  3283. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  3284. }
  3285. var i: number;
  3286. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3287. var sound = this.mainSoundTrack.soundCollection[i];
  3288. if (sound.useCustomAttenuation) {
  3289. sound.updateDistanceFromListener();
  3290. }
  3291. }
  3292. for (i = 0; i < this.soundTracks.length; i++) {
  3293. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3294. sound = this.soundTracks[i].soundCollection[j];
  3295. if (sound.useCustomAttenuation) {
  3296. sound.updateDistanceFromListener();
  3297. }
  3298. }
  3299. }
  3300. }
  3301. }
  3302. // Audio
  3303. public get audioEnabled(): boolean {
  3304. return this._audioEnabled;
  3305. }
  3306. public set audioEnabled(value: boolean) {
  3307. this._audioEnabled = value;
  3308. if (AudioEngine) {
  3309. if (this._audioEnabled) {
  3310. this._enableAudio();
  3311. }
  3312. else {
  3313. this._disableAudio();
  3314. }
  3315. }
  3316. }
  3317. private _disableAudio() {
  3318. var i: number;
  3319. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3320. this.mainSoundTrack.soundCollection[i].pause();
  3321. }
  3322. for (i = 0; i < this.soundTracks.length; i++) {
  3323. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3324. this.soundTracks[i].soundCollection[j].pause();
  3325. }
  3326. }
  3327. }
  3328. private _enableAudio() {
  3329. var i: number;
  3330. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  3331. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  3332. this.mainSoundTrack.soundCollection[i].play();
  3333. }
  3334. }
  3335. for (i = 0; i < this.soundTracks.length; i++) {
  3336. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  3337. if (this.soundTracks[i].soundCollection[j].isPaused) {
  3338. this.soundTracks[i].soundCollection[j].play();
  3339. }
  3340. }
  3341. }
  3342. }
  3343. public get headphone(): boolean {
  3344. return this._headphone;
  3345. }
  3346. public set headphone(value: boolean) {
  3347. this._headphone = value;
  3348. if (AudioEngine) {
  3349. if (this._headphone) {
  3350. this._switchAudioModeForHeadphones();
  3351. }
  3352. else {
  3353. this._switchAudioModeForNormalSpeakers();
  3354. }
  3355. }
  3356. }
  3357. private _switchAudioModeForHeadphones() {
  3358. this.mainSoundTrack.switchPanningModelToHRTF();
  3359. for (var i = 0; i < this.soundTracks.length; i++) {
  3360. this.soundTracks[i].switchPanningModelToHRTF();
  3361. }
  3362. }
  3363. private _switchAudioModeForNormalSpeakers() {
  3364. this.mainSoundTrack.switchPanningModelToEqualPower();
  3365. for (var i = 0; i < this.soundTracks.length; i++) {
  3366. this.soundTracks[i].switchPanningModelToEqualPower();
  3367. }
  3368. }
  3369. /**
  3370. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  3371. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  3372. * @returns the created depth renderer
  3373. */
  3374. public enableDepthRenderer(camera?: Nullable<Camera>): DepthRenderer {
  3375. camera = camera || this.activeCamera;
  3376. if (!camera) {
  3377. throw "No camera available to enable depth renderer";
  3378. }
  3379. if (!this._depthRenderer[camera.id]) {
  3380. this._depthRenderer[camera.id] = new DepthRenderer(this, Engine.TEXTURETYPE_FLOAT, camera);
  3381. }
  3382. return this._depthRenderer[camera.id];
  3383. }
  3384. /**
  3385. * Disables a depth renderer for a given camera
  3386. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  3387. */
  3388. public disableDepthRenderer(camera?: Nullable<Camera>): void {
  3389. camera = camera || this.activeCamera;
  3390. if (!camera || !this._depthRenderer[camera.id]) {
  3391. return;
  3392. }
  3393. this._depthRenderer[camera.id].dispose();
  3394. delete this._depthRenderer[camera.id];
  3395. }
  3396. public enableGeometryBufferRenderer(ratio: number = 1): Nullable<GeometryBufferRenderer> {
  3397. if (this._geometryBufferRenderer) {
  3398. return this._geometryBufferRenderer;
  3399. }
  3400. this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio);
  3401. if (!this._geometryBufferRenderer.isSupported) {
  3402. this._geometryBufferRenderer = null;
  3403. }
  3404. return this._geometryBufferRenderer;
  3405. }
  3406. public disableGeometryBufferRenderer(): void {
  3407. if (!this._geometryBufferRenderer) {
  3408. return;
  3409. }
  3410. this._geometryBufferRenderer.dispose();
  3411. this._geometryBufferRenderer = null;
  3412. }
  3413. public freezeMaterials(): void {
  3414. for (var i = 0; i < this.materials.length; i++) {
  3415. this.materials[i].freeze();
  3416. }
  3417. }
  3418. public unfreezeMaterials(): void {
  3419. for (var i = 0; i < this.materials.length; i++) {
  3420. this.materials[i].unfreeze();
  3421. }
  3422. }
  3423. public dispose(): void {
  3424. this.beforeRender = null;
  3425. this.afterRender = null;
  3426. this.skeletons = [];
  3427. this.morphTargetManagers = [];
  3428. this.importedMeshesFiles = new Array<string>();
  3429. this.stopAllAnimations();
  3430. this.resetCachedMaterial();
  3431. for (var key in this._depthRenderer) {
  3432. this._depthRenderer[key].dispose();
  3433. }
  3434. if (this._gamepadManager) {
  3435. this._gamepadManager.dispose();
  3436. this._gamepadManager = null;
  3437. }
  3438. // Smart arrays
  3439. if (this.activeCamera) {
  3440. this.activeCamera._activeMeshes.dispose();
  3441. this.activeCamera = null;
  3442. }
  3443. this._activeMeshes.dispose();
  3444. this._renderingManager.dispose();
  3445. this._processedMaterials.dispose();
  3446. this._activeParticleSystems.dispose();
  3447. this._activeSkeletons.dispose();
  3448. this._softwareSkinnedMeshes.dispose();
  3449. this._renderTargets.dispose();
  3450. if (this._boundingBoxRenderer) {
  3451. this._boundingBoxRenderer.dispose();
  3452. }
  3453. this._meshesForIntersections.dispose();
  3454. this._toBeDisposed.dispose();
  3455. // Abort active requests
  3456. for (let request of this._activeRequests) {
  3457. request.abort();
  3458. }
  3459. // Debug layer
  3460. if (this._debugLayer) {
  3461. this._debugLayer.hide();
  3462. }
  3463. // Events
  3464. this.onDisposeObservable.notifyObservers(this);
  3465. this.onDisposeObservable.clear();
  3466. this.onBeforeRenderObservable.clear();
  3467. this.onAfterRenderObservable.clear();
  3468. this.OnBeforeRenderTargetsRenderObservable.clear();
  3469. this.OnAfterRenderTargetsRenderObservable.clear();
  3470. this.onAfterStepObservable.clear();
  3471. this.onBeforeStepObservable.clear();
  3472. this.onBeforeActiveMeshesEvaluationObservable.clear();
  3473. this.onAfterActiveMeshesEvaluationObservable.clear();
  3474. this.onBeforeParticlesRenderingObservable.clear();
  3475. this.onAfterParticlesRenderingObservable.clear();
  3476. this.onBeforeSpritesRenderingObservable.clear();
  3477. this.onAfterSpritesRenderingObservable.clear();
  3478. this.onBeforeDrawPhaseObservable.clear();
  3479. this.onAfterDrawPhaseObservable.clear();
  3480. this.onBeforePhysicsObservable.clear();
  3481. this.onAfterPhysicsObservable.clear();
  3482. this.onBeforeAnimationsObservable.clear();
  3483. this.onAfterAnimationsObservable.clear();
  3484. this.onDataLoadedObservable.clear();
  3485. this.detachControl();
  3486. // Release sounds & sounds tracks
  3487. if (AudioEngine) {
  3488. this.disposeSounds();
  3489. }
  3490. // VR Helper
  3491. if (this.VRHelper) {
  3492. this.VRHelper.dispose();
  3493. }
  3494. // Detach cameras
  3495. var canvas = this._engine.getRenderingCanvas();
  3496. if (canvas) {
  3497. var index;
  3498. for (index = 0; index < this.cameras.length; index++) {
  3499. this.cameras[index].detachControl(canvas);
  3500. }
  3501. }
  3502. // Release animation groups
  3503. while (this.animationGroups.length) {
  3504. this.animationGroups[0].dispose();
  3505. }
  3506. // Release lights
  3507. while (this.lights.length) {
  3508. this.lights[0].dispose();
  3509. }
  3510. // Release meshes
  3511. while (this.meshes.length) {
  3512. this.meshes[0].dispose(true);
  3513. }
  3514. while (this.transformNodes.length) {
  3515. this.removeTransformNode(this.transformNodes[0]);
  3516. }
  3517. // Release cameras
  3518. while (this.cameras.length) {
  3519. this.cameras[0].dispose();
  3520. }
  3521. // Release materials
  3522. if (this.defaultMaterial) {
  3523. this.defaultMaterial.dispose()
  3524. }
  3525. while (this.multiMaterials.length) {
  3526. this.multiMaterials[0].dispose();
  3527. }
  3528. while (this.materials.length) {
  3529. this.materials[0].dispose();
  3530. }
  3531. // Release particles
  3532. while (this.particleSystems.length) {
  3533. this.particleSystems[0].dispose();
  3534. }
  3535. // Release sprites
  3536. while (this.spriteManagers.length) {
  3537. this.spriteManagers[0].dispose();
  3538. }
  3539. // Release postProcesses
  3540. while (this.postProcesses.length) {
  3541. this.postProcesses[0].dispose();
  3542. }
  3543. // Release layers
  3544. while (this.layers.length) {
  3545. this.layers[0].dispose();
  3546. }
  3547. while (this.effectLayers.length) {
  3548. this.effectLayers[0].dispose();
  3549. }
  3550. // Release textures
  3551. while (this.textures.length) {
  3552. this.textures[0].dispose();
  3553. }
  3554. // Release UBO
  3555. this._sceneUbo.dispose();
  3556. if (this._alternateSceneUbo) {
  3557. this._alternateSceneUbo.dispose();
  3558. }
  3559. // Post-processes
  3560. this.postProcessManager.dispose();
  3561. if (this._postProcessRenderPipelineManager) {
  3562. this._postProcessRenderPipelineManager.dispose();
  3563. }
  3564. // Physics
  3565. if (this._physicsEngine) {
  3566. this.disablePhysicsEngine();
  3567. }
  3568. // Remove from engine
  3569. index = this._engine.scenes.indexOf(this);
  3570. if (index > -1) {
  3571. this._engine.scenes.splice(index, 1);
  3572. }
  3573. this._engine.wipeCaches(true);
  3574. this._isDisposed = true;
  3575. }
  3576. public get isDisposed(): boolean {
  3577. return this._isDisposed;
  3578. }
  3579. // Release sounds & sounds tracks
  3580. public disposeSounds() {
  3581. if (!this._mainSoundTrack) {
  3582. return;
  3583. }
  3584. this.mainSoundTrack.dispose();
  3585. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  3586. this.soundTracks[scIndex].dispose();
  3587. }
  3588. }
  3589. // Octrees
  3590. /**
  3591. * Get the world extend vectors with an optional filter
  3592. *
  3593. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  3594. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  3595. */
  3596. public getWorldExtends(filterPredicate?: (mesh: AbstractMesh) => boolean): { min: Vector3; max: Vector3 } {
  3597. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3598. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3599. filterPredicate = filterPredicate || (() => true);
  3600. this.meshes.filter(filterPredicate).forEach(mesh => {
  3601. mesh.computeWorldMatrix(true);
  3602. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  3603. return;
  3604. }
  3605. let boundingInfo = mesh.getBoundingInfo();
  3606. var minBox = boundingInfo.boundingBox.minimumWorld;
  3607. var maxBox = boundingInfo.boundingBox.maximumWorld;
  3608. Tools.CheckExtends(minBox, min, max);
  3609. Tools.CheckExtends(maxBox, min, max);
  3610. })
  3611. return {
  3612. min: min,
  3613. max: max
  3614. };
  3615. }
  3616. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  3617. if (!this._selectionOctree) {
  3618. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  3619. }
  3620. var worldExtends = this.getWorldExtends();
  3621. // Update octree
  3622. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  3623. return this._selectionOctree;
  3624. }
  3625. // Picking
  3626. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  3627. let result = Ray.Zero();
  3628. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  3629. return result;
  3630. }
  3631. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  3632. var engine = this._engine;
  3633. if (!camera) {
  3634. if (!this.activeCamera)
  3635. throw new Error("Active camera not set");
  3636. camera = this.activeCamera;
  3637. }
  3638. var cameraViewport = camera.viewport;
  3639. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3640. // Moving coordinates to local viewport world
  3641. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3642. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3643. result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  3644. return this;
  3645. }
  3646. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  3647. let result = Ray.Zero();
  3648. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  3649. return result;
  3650. }
  3651. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  3652. if (!PickingInfo) {
  3653. return this;
  3654. }
  3655. var engine = this._engine;
  3656. if (!camera) {
  3657. if (!this.activeCamera)
  3658. throw new Error("Active camera not set");
  3659. camera = this.activeCamera;
  3660. }
  3661. var cameraViewport = camera.viewport;
  3662. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3663. var identity = Matrix.Identity();
  3664. // Moving coordinates to local viewport world
  3665. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3666. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3667. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  3668. return this;
  3669. }
  3670. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  3671. if (!PickingInfo) {
  3672. return null;
  3673. }
  3674. var pickingInfo = null;
  3675. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3676. var mesh = this.meshes[meshIndex];
  3677. if (predicate) {
  3678. if (!predicate(mesh)) {
  3679. continue;
  3680. }
  3681. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3682. continue;
  3683. }
  3684. var world = mesh.getWorldMatrix();
  3685. var ray = rayFunction(world);
  3686. var result = mesh.intersects(ray, fastCheck);
  3687. if (!result || !result.hit)
  3688. continue;
  3689. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3690. continue;
  3691. pickingInfo = result;
  3692. if (fastCheck) {
  3693. break;
  3694. }
  3695. }
  3696. return pickingInfo || new PickingInfo();
  3697. }
  3698. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  3699. if (!PickingInfo) {
  3700. return null;
  3701. }
  3702. var pickingInfos = new Array<PickingInfo>();
  3703. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3704. var mesh = this.meshes[meshIndex];
  3705. if (predicate) {
  3706. if (!predicate(mesh)) {
  3707. continue;
  3708. }
  3709. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3710. continue;
  3711. }
  3712. var world = mesh.getWorldMatrix();
  3713. var ray = rayFunction(world);
  3714. var result = mesh.intersects(ray, false);
  3715. if (!result || !result.hit)
  3716. continue;
  3717. pickingInfos.push(result);
  3718. }
  3719. return pickingInfos;
  3720. }
  3721. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  3722. if (!PickingInfo) {
  3723. return null;
  3724. }
  3725. var pickingInfo = null;
  3726. if (!camera) {
  3727. if (!this.activeCamera) {
  3728. return null;
  3729. }
  3730. camera = this.activeCamera;
  3731. }
  3732. if (this.spriteManagers.length > 0) {
  3733. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  3734. var spriteManager = this.spriteManagers[spriteIndex];
  3735. if (!spriteManager.isPickable) {
  3736. continue;
  3737. }
  3738. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  3739. if (!result || !result.hit)
  3740. continue;
  3741. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3742. continue;
  3743. pickingInfo = result;
  3744. if (fastCheck) {
  3745. break;
  3746. }
  3747. }
  3748. }
  3749. return pickingInfo || new PickingInfo();
  3750. }
  3751. private _tempPickingRay: Nullable<Ray> = Ray ? Ray.Zero() : null;
  3752. /** Launch a ray to try to pick a mesh in the scene
  3753. * @param x position on screen
  3754. * @param y position on screen
  3755. * @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
  3756. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3757. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3758. */
  3759. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  3760. if (!PickingInfo) {
  3761. return null;
  3762. }
  3763. return this._internalPick(world => {
  3764. this.createPickingRayToRef(x, y, world, this._tempPickingRay!, camera || null);
  3765. return this._tempPickingRay!;
  3766. }, predicate, fastCheck);
  3767. }
  3768. /** Launch a ray to try to pick a sprite in the scene
  3769. * @param x position on screen
  3770. * @param y position on screen
  3771. * @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
  3772. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3773. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3774. */
  3775. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  3776. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay!, camera);
  3777. return this._internalPickSprites(this._tempPickingRay!, predicate, fastCheck, camera);
  3778. }
  3779. private _cachedRayForTransform: Ray;
  3780. /** Use the given ray to pick a mesh in the scene
  3781. * @param ray The ray to use to pick meshes
  3782. * @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
  3783. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3784. */
  3785. public pickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  3786. return this._internalPick(world => {
  3787. if (!this._pickWithRayInverseMatrix) {
  3788. this._pickWithRayInverseMatrix = Matrix.Identity();
  3789. }
  3790. world.invertToRef(this._pickWithRayInverseMatrix);
  3791. if (!this._cachedRayForTransform) {
  3792. this._cachedRayForTransform = Ray.Zero();
  3793. }
  3794. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  3795. return this._cachedRayForTransform;
  3796. }, predicate, fastCheck);
  3797. }
  3798. /**
  3799. * Launch a ray to try to pick a mesh in the scene
  3800. * @param x X position on screen
  3801. * @param y Y position on screen
  3802. * @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
  3803. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3804. */
  3805. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): Nullable<PickingInfo[]> {
  3806. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera || null), predicate);
  3807. }
  3808. /**
  3809. * Launch a ray to try to pick a mesh in the scene
  3810. * @param ray Ray to use
  3811. * @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
  3812. */
  3813. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  3814. return this._internalMultiPick(world => {
  3815. if (!this._pickWithRayInverseMatrix) {
  3816. this._pickWithRayInverseMatrix = Matrix.Identity();
  3817. }
  3818. world.invertToRef(this._pickWithRayInverseMatrix);
  3819. if (!this._cachedRayForTransform) {
  3820. this._cachedRayForTransform = Ray.Zero();
  3821. }
  3822. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  3823. return this._cachedRayForTransform;
  3824. }, predicate);
  3825. }
  3826. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  3827. if (this._pointerOverMesh === mesh) {
  3828. return;
  3829. }
  3830. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3831. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3832. }
  3833. this._pointerOverMesh = mesh;
  3834. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3835. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3836. }
  3837. }
  3838. public getPointerOverMesh(): Nullable<AbstractMesh> {
  3839. return this._pointerOverMesh;
  3840. }
  3841. public setPointerOverSprite(sprite: Nullable<Sprite>): void {
  3842. if (this._pointerOverSprite === sprite) {
  3843. return;
  3844. }
  3845. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3846. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3847. }
  3848. this._pointerOverSprite = sprite;
  3849. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3850. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3851. }
  3852. }
  3853. public getPointerOverSprite(): Nullable<Sprite> {
  3854. return this._pointerOverSprite;
  3855. }
  3856. // Physics
  3857. public getPhysicsEngine(): Nullable<PhysicsEngine> {
  3858. return this._physicsEngine;
  3859. }
  3860. /**
  3861. * Enables physics to the current scene
  3862. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  3863. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  3864. * @return {boolean} was the physics engine initialized
  3865. */
  3866. public enablePhysics(gravity: Nullable<Vector3> = null, plugin?: IPhysicsEnginePlugin): boolean {
  3867. if (this._physicsEngine) {
  3868. return true;
  3869. }
  3870. try {
  3871. this._physicsEngine = new PhysicsEngine(gravity, plugin);
  3872. return true;
  3873. } catch (e) {
  3874. Tools.Error(e.message);
  3875. return false;
  3876. }
  3877. }
  3878. public disablePhysicsEngine(): void {
  3879. if (!this._physicsEngine) {
  3880. return;
  3881. }
  3882. this._physicsEngine.dispose();
  3883. this._physicsEngine = null;
  3884. }
  3885. public isPhysicsEnabled(): boolean {
  3886. return this._physicsEngine !== undefined;
  3887. }
  3888. public deleteCompoundImpostor(compound: any): void {
  3889. var mesh: AbstractMesh = compound.parts[0].mesh;
  3890. if (mesh.physicsImpostor) {
  3891. mesh.physicsImpostor.dispose(/*true*/);
  3892. mesh.physicsImpostor = null;
  3893. }
  3894. }
  3895. // Misc.
  3896. public _rebuildGeometries(): void {
  3897. for (var geometry of this._geometries) {
  3898. geometry._rebuild();
  3899. }
  3900. for (var mesh of this.meshes) {
  3901. mesh._rebuild();
  3902. }
  3903. if (this.postProcessManager) {
  3904. this.postProcessManager._rebuild();
  3905. }
  3906. for (var layer of this.layers) {
  3907. layer._rebuild();
  3908. }
  3909. for (var effectLayer of this.effectLayers) {
  3910. effectLayer._rebuild();
  3911. }
  3912. if (this._boundingBoxRenderer) {
  3913. this._boundingBoxRenderer._rebuild();
  3914. }
  3915. for (var system of this.particleSystems) {
  3916. system.rebuild();
  3917. }
  3918. if (this._postProcessRenderPipelineManager) {
  3919. this._postProcessRenderPipelineManager._rebuild();
  3920. }
  3921. }
  3922. public _rebuildTextures(): void {
  3923. for (var texture of this.textures) {
  3924. texture._rebuild();
  3925. }
  3926. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  3927. }
  3928. /**
  3929. * Creates a default light for the scene.
  3930. * @param replace Whether to replace the existing lights in the scene.
  3931. */
  3932. public createDefaultLight(replace = false): void {
  3933. // Dispose existing light in replace mode.
  3934. if (replace) {
  3935. if (this.lights) {
  3936. for (var i = 0; i < this.lights.length; i++) {
  3937. this.lights[i].dispose();
  3938. }
  3939. }
  3940. }
  3941. // Light
  3942. if (this.lights.length === 0) {
  3943. new HemisphericLight("default light", Vector3.Up(), this);
  3944. }
  3945. }
  3946. /**
  3947. * Creates a default camera for the scene.
  3948. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  3949. * @param replace Whether to replace the existing active camera in the scene.
  3950. * @param attachCameraControls Whether to attach camera controls to the canvas.
  3951. */
  3952. public createDefaultCamera(createArcRotateCamera = false, replace = false, attachCameraControls = false): void {
  3953. // Dispose existing camera in replace mode.
  3954. if (replace) {
  3955. if (this.activeCamera) {
  3956. this.activeCamera.dispose();
  3957. this.activeCamera = null;
  3958. }
  3959. }
  3960. // Camera
  3961. if (!this.activeCamera) {
  3962. var worldExtends = this.getWorldExtends();
  3963. var worldSize = worldExtends.max.subtract(worldExtends.min);
  3964. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  3965. var camera: TargetCamera;
  3966. var radius = worldSize.length() * 1.5;
  3967. // empty scene scenario!
  3968. if (!isFinite(radius)) {
  3969. radius = 1;
  3970. worldCenter.copyFromFloats(0, 0, 0);
  3971. }
  3972. if (createArcRotateCamera) {
  3973. var arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  3974. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  3975. arcRotateCamera.wheelPrecision = 100 / radius;
  3976. camera = arcRotateCamera;
  3977. }
  3978. else {
  3979. var freeCamera = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this);
  3980. freeCamera.setTarget(worldCenter);
  3981. camera = freeCamera;
  3982. }
  3983. camera.minZ = radius * 0.01;
  3984. camera.maxZ = radius * 1000;
  3985. camera.speed = radius * 0.2;
  3986. this.activeCamera = camera;
  3987. let canvas = this.getEngine().getRenderingCanvas();
  3988. if (attachCameraControls && canvas) {
  3989. camera.attachControl(canvas);
  3990. }
  3991. }
  3992. }
  3993. public createDefaultCameraOrLight(createArcRotateCamera = false, replace = false, attachCameraControls = false): void {
  3994. this.createDefaultLight(replace);
  3995. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  3996. }
  3997. public createDefaultSkybox(environmentTexture?: BaseTexture, pbr = false, scale = 1000, blur = 0): Nullable<Mesh> {
  3998. if (environmentTexture) {
  3999. this.environmentTexture = environmentTexture;
  4000. }
  4001. if (!this.environmentTexture) {
  4002. Tools.Warn("Can not create default skybox without environment texture.");
  4003. return null;
  4004. }
  4005. // Skybox
  4006. var hdrSkybox = Mesh.CreateBox("hdrSkyBox", scale, this);
  4007. if (pbr) {
  4008. let hdrSkyboxMaterial = new PBRMaterial("skyBox", this);
  4009. hdrSkyboxMaterial.backFaceCulling = false;
  4010. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  4011. if (hdrSkyboxMaterial.reflectionTexture) {
  4012. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  4013. }
  4014. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  4015. hdrSkyboxMaterial.disableLighting = true;
  4016. hdrSkyboxMaterial.twoSidedLighting = true;
  4017. hdrSkybox.infiniteDistance = true;
  4018. hdrSkybox.material = hdrSkyboxMaterial;
  4019. }
  4020. else {
  4021. let skyboxMaterial = new StandardMaterial("skyBox", this);
  4022. skyboxMaterial.backFaceCulling = false;
  4023. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  4024. if (skyboxMaterial.reflectionTexture) {
  4025. skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  4026. }
  4027. skyboxMaterial.disableLighting = true;
  4028. hdrSkybox.infiniteDistance = true;
  4029. hdrSkybox.material = skyboxMaterial;
  4030. }
  4031. return hdrSkybox;
  4032. }
  4033. public createDefaultEnvironment(options: Partial<IEnvironmentHelperOptions>): Nullable<EnvironmentHelper> {
  4034. if (EnvironmentHelper) {
  4035. return new EnvironmentHelper(options, this);
  4036. }
  4037. return null;
  4038. }
  4039. public createDefaultVRExperience(webVROptions: VRExperienceHelperOptions = {}): VRExperienceHelper {
  4040. return new VRExperienceHelper(this, webVROptions);
  4041. }
  4042. // Tags
  4043. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  4044. if (tagsQuery === undefined) {
  4045. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  4046. return list;
  4047. }
  4048. var listByTags = [];
  4049. forEach = forEach || ((item: any) => { return; });
  4050. for (var i in list) {
  4051. var item = list[i];
  4052. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  4053. listByTags.push(item);
  4054. forEach(item);
  4055. }
  4056. }
  4057. return listByTags;
  4058. }
  4059. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  4060. return this._getByTags(this.meshes, tagsQuery, forEach);
  4061. }
  4062. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  4063. return this._getByTags(this.cameras, tagsQuery, forEach);
  4064. }
  4065. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  4066. return this._getByTags(this.lights, tagsQuery, forEach);
  4067. }
  4068. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  4069. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  4070. }
  4071. /**
  4072. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  4073. * This allowed control for front to back rendering or reversly depending of the special needs.
  4074. *
  4075. * @param renderingGroupId The rendering group id corresponding to its index
  4076. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  4077. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  4078. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  4079. */
  4080. public setRenderingOrder(renderingGroupId: number,
  4081. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4082. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4083. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  4084. this._renderingManager.setRenderingOrder(renderingGroupId,
  4085. opaqueSortCompareFn,
  4086. alphaTestSortCompareFn,
  4087. transparentSortCompareFn);
  4088. }
  4089. /**
  4090. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  4091. *
  4092. * @param renderingGroupId The rendering group id corresponding to its index
  4093. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  4094. * @param depth Automatically clears depth between groups if true and autoClear is true.
  4095. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  4096. */
  4097. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  4098. depth = true,
  4099. stencil = true): void {
  4100. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  4101. }
  4102. /**
  4103. * Will flag all materials as dirty to trigger new shader compilation
  4104. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  4105. */
  4106. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  4107. for (var material of this.materials) {
  4108. if (predicate && !predicate(material)) {
  4109. continue;
  4110. }
  4111. material.markAsDirty(flag);
  4112. }
  4113. }
  4114. 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 {
  4115. let request = Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  4116. this._activeRequests.push(request);
  4117. request.onCompleteObservable.add(request => {
  4118. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4119. });
  4120. return request;
  4121. }
  4122. /** @ignore */
  4123. public _loadFileAsync(url: string, useDatabase?: boolean, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4124. return new Promise((resolve, reject) => {
  4125. this._loadFile(url, (data) => {
  4126. resolve(data);
  4127. }, undefined, useDatabase, useArrayBuffer, (request, exception) => {
  4128. reject(exception);
  4129. })
  4130. });
  4131. }
  4132. }
  4133. }