scene.ts 209 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613
  1. import { Nullable } from "./types";
  2. import { IAnimatable, IFileRequest, Tools, PerfCounter } from "./Misc/tools";
  3. import { PrecisionDate } from "./Misc/precisionDate";
  4. import { Observable, Observer } from "./Misc/observable";
  5. import { SmartArrayNoDuplicate, SmartArray, ISmartArrayLike } from "./Misc/smartArray";
  6. import { StringDictionary } from "./Misc/stringDictionary";
  7. import { Tags } from "./Misc/tags";
  8. import { Color4, Color3, Plane, Vector2, Vector3, Matrix, Tmp, Quaternion, Frustum } from "./Maths/math";
  9. import { Geometry } from "./Meshes/geometry";
  10. import { TransformNode } from "./Meshes/transformNode";
  11. import { SubMesh } from "./Meshes/subMesh";
  12. import { AbstractMesh } from "./Meshes/abstractMesh";
  13. import { Mesh } from "./Meshes/mesh";
  14. import { IParticleSystem } from "./Particles/IParticleSystem";
  15. import { Bone } from "./Bones/bone";
  16. import { Skeleton } from "./Bones/skeleton";
  17. import { MorphTargetManager } from "./Morph/morphTargetManager";
  18. import { Camera } from "./Cameras/camera";
  19. import { AbstractScene } from "./abstractScene";
  20. import { BaseTexture } from "./Materials/Textures/baseTexture";
  21. import { Texture } from "./Materials/Textures/texture";
  22. import { RenderTargetTexture } from "./Materials/Textures/renderTargetTexture";
  23. import { Material } from "./Materials/material";
  24. import { ImageProcessingConfiguration } from "./Materials/imageProcessingConfiguration";
  25. import { Effect } from "./Materials/effect";
  26. import { UniformBuffer } from "./Materials/uniformBuffer";
  27. import { MultiMaterial } from "./Materials/multiMaterial";
  28. import { Animation } from "./Animations/animation";
  29. import { RuntimeAnimation } from "./Animations/runtimeAnimation";
  30. import { AnimationGroup } from "./Animations/animationGroup";
  31. import { Animatable } from "./Animations/animatable";
  32. import { AnimationPropertiesOverride } from "./Animations/animationPropertiesOverride";
  33. import { Light } from "./Lights/light";
  34. import { PickingInfo } from "./Collisions/pickingInfo";
  35. import { Collider } from "./Collisions/collider";
  36. import { ICollisionCoordinator, CollisionCoordinatorLegacy } from "./Collisions/collisionCoordinator";
  37. import { PointerEventTypes, PointerInfoPre, PointerInfo } from "./Events/pointerEvents";
  38. import { KeyboardInfoPre, KeyboardInfo, KeyboardEventTypes } from "./Events/keyboardEvents";
  39. import { ActionEvent } from "./Actions/actionEvent";
  40. import { ActionManager } from "./Actions/actionManager";
  41. import { PostProcess } from "./PostProcesses/postProcess";
  42. import { PostProcessManager } from "./PostProcesses/postProcessManager";
  43. import { IOfflineProvider } from "./Offline/IOfflineProvider";
  44. import { RenderingGroupInfo, RenderingManager, IRenderingManagerAutoClearSetup } from "./Rendering/renderingManager";
  45. import { ISceneComponent, ISceneSerializableComponent, Stage, SimpleStageAction, RenderTargetsStageAction, RenderTargetStageAction, MeshStageAction, EvaluateSubMeshStageAction, ActiveMeshStageAction, CameraStageAction, RenderingGroupStageAction, RenderingMeshStageAction, PointerMoveStageAction, PointerUpDownStageAction } from "./sceneComponent";
  46. import { Engine } from "./Engines/engine";
  47. import { Ray } from "./Culling/ray";
  48. import { Node } from "./node";
  49. import { MorphTarget } from "./Morph/morphTarget";
  50. import { Constants } from "./Engines/constants";
  51. import { DomManagement } from "./Misc/domManagement";
  52. import { Logger } from "./Misc/logger";
  53. import { EngineStore } from "./Engines/engineStore";
  54. /**
  55. * Define an interface for all classes that will hold resources
  56. */
  57. export interface IDisposable {
  58. /**
  59. * Releases all held resources
  60. */
  61. dispose(): void;
  62. }
  63. /** @hidden */
  64. class ClickInfo {
  65. private _singleClick = false;
  66. private _doubleClick = false;
  67. private _hasSwiped = false;
  68. private _ignore = false;
  69. public get singleClick(): boolean {
  70. return this._singleClick;
  71. }
  72. public get doubleClick(): boolean {
  73. return this._doubleClick;
  74. }
  75. public get hasSwiped(): boolean {
  76. return this._hasSwiped;
  77. }
  78. public get ignore(): boolean {
  79. return this._ignore;
  80. }
  81. public set singleClick(b: boolean) {
  82. this._singleClick = b;
  83. }
  84. public set doubleClick(b: boolean) {
  85. this._doubleClick = b;
  86. }
  87. public set hasSwiped(b: boolean) {
  88. this._hasSwiped = b;
  89. }
  90. public set ignore(b: boolean) {
  91. this._ignore = b;
  92. }
  93. }
  94. /** Interface defining initialization parameters for Scene class */
  95. export interface SceneOptions {
  96. /**
  97. * Defines that scene should keep up-to-date a map of geometry to enable fast look-up by uniqueId
  98. * It will improve performance when the number of geometries becomes important.
  99. */
  100. useGeometryUniqueIdsMap?: boolean;
  101. /**
  102. * Defines that each material of the scene should keep up-to-date a map of referencing meshes for fast diposing
  103. * It will improve performance when the number of mesh becomes important, but might consume a bit more memory
  104. */
  105. useMaterialMeshMap?: boolean;
  106. /**
  107. * Defines that each mesh of the scene should keep up-to-date a map of referencing cloned meshes for fast diposing
  108. * It will improve performance when the number of mesh becomes important, but might consume a bit more memory
  109. */
  110. useClonedMeshhMap?: boolean;
  111. }
  112. /**
  113. * Represents a scene to be rendered by the engine.
  114. * @see http://doc.babylonjs.com/features/scene
  115. */
  116. export class Scene extends AbstractScene implements IAnimatable {
  117. // Statics
  118. private static _uniqueIdCounter = 0;
  119. /** The fog is deactivated */
  120. public static readonly FOGMODE_NONE = 0;
  121. /** The fog density is following an exponential function */
  122. public static readonly FOGMODE_EXP = 1;
  123. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  124. public static readonly FOGMODE_EXP2 = 2;
  125. /** The fog density is following a linear function. */
  126. public static readonly FOGMODE_LINEAR = 3;
  127. /**
  128. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  129. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  130. */
  131. public static MinDeltaTime = 1.0;
  132. /**
  133. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  134. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  135. */
  136. public static MaxDeltaTime = 1000.0;
  137. /**
  138. * Factory used to create the default material.
  139. * @param name The name of the material to create
  140. * @param scene The scene to create the material for
  141. * @returns The default material
  142. */
  143. public static DefaultMaterialFactory(scene: Scene): Material {
  144. throw "Import StandardMaterial or Fill DefaultMaterialFactory static property on scene before relying on default material creation.";
  145. }
  146. // Members
  147. /** @hidden */
  148. public readonly _isScene = true;
  149. /**
  150. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  151. */
  152. public autoClear = true;
  153. /**
  154. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  155. */
  156. public autoClearDepthAndStencil = true;
  157. /**
  158. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  159. */
  160. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  161. /**
  162. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  163. */
  164. public ambientColor = new Color3(0, 0, 0);
  165. /** @hidden */
  166. public _environmentBRDFTexture: BaseTexture;
  167. /** @hidden */
  168. protected _environmentTexture: Nullable<BaseTexture>;
  169. /**
  170. * Texture used in all pbr material as the reflection texture.
  171. * As in the majority of the scene they are the same (exception for multi room and so on),
  172. * this is easier to reference from here than from all the materials.
  173. */
  174. public get environmentTexture(): Nullable<BaseTexture> {
  175. return this._environmentTexture;
  176. }
  177. /**
  178. * Texture used in all pbr material as the reflection texture.
  179. * As in the majority of the scene they are the same (exception for multi room and so on),
  180. * this is easier to set here than in all the materials.
  181. */
  182. public set environmentTexture(value: Nullable<BaseTexture>) {
  183. if (this._environmentTexture === value) {
  184. return;
  185. }
  186. this._environmentTexture = value;
  187. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  188. }
  189. /** @hidden */
  190. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  191. /**
  192. * Default image processing configuration used either in the rendering
  193. * Forward main pass or through the imageProcessingPostProcess if present.
  194. * As in the majority of the scene they are the same (exception for multi camera),
  195. * this is easier to reference from here than from all the materials and post process.
  196. *
  197. * No setter as we it is a shared configuration, you can set the values instead.
  198. */
  199. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  200. return this._imageProcessingConfiguration;
  201. }
  202. private _forceWireframe = false;
  203. /**
  204. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  205. */
  206. public set forceWireframe(value: boolean) {
  207. if (this._forceWireframe === value) {
  208. return;
  209. }
  210. this._forceWireframe = value;
  211. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  212. }
  213. public get forceWireframe(): boolean {
  214. return this._forceWireframe;
  215. }
  216. private _forcePointsCloud = false;
  217. /**
  218. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  219. */
  220. public set forcePointsCloud(value: boolean) {
  221. if (this._forcePointsCloud === value) {
  222. return;
  223. }
  224. this._forcePointsCloud = value;
  225. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  226. }
  227. public get forcePointsCloud(): boolean {
  228. return this._forcePointsCloud;
  229. }
  230. /**
  231. * Gets or sets the active clipplane 1
  232. */
  233. public clipPlane: Nullable<Plane>;
  234. /**
  235. * Gets or sets the active clipplane 2
  236. */
  237. public clipPlane2: Nullable<Plane>;
  238. /**
  239. * Gets or sets the active clipplane 3
  240. */
  241. public clipPlane3: Nullable<Plane>;
  242. /**
  243. * Gets or sets the active clipplane 4
  244. */
  245. public clipPlane4: Nullable<Plane>;
  246. /**
  247. * Gets or sets a boolean indicating if animations are enabled
  248. */
  249. public animationsEnabled = true;
  250. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  251. /**
  252. * Gets or sets the animation properties override
  253. */
  254. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  255. return this._animationPropertiesOverride;
  256. }
  257. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  258. this._animationPropertiesOverride = value;
  259. }
  260. /**
  261. * Gets or sets a boolean indicating if a constant deltatime has to be used
  262. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  263. */
  264. public useConstantAnimationDeltaTime = false;
  265. /**
  266. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  267. * Please note that it requires to run a ray cast through the scene on every frame
  268. */
  269. public constantlyUpdateMeshUnderPointer = false;
  270. /**
  271. * Defines the HTML cursor to use when hovering over interactive elements
  272. */
  273. public hoverCursor = "pointer";
  274. /**
  275. * Defines the HTML default cursor to use (empty by default)
  276. */
  277. public defaultCursor: string = "";
  278. /**
  279. * This is used to call preventDefault() on pointer down
  280. * in order to block unwanted artifacts like system double clicks
  281. */
  282. public preventDefaultOnPointerDown = true;
  283. /**
  284. * This is used to call preventDefault() on pointer up
  285. * in order to block unwanted artifacts like system double clicks
  286. */
  287. public preventDefaultOnPointerUp = true;
  288. // Metadata
  289. /**
  290. * Gets or sets user defined metadata
  291. */
  292. public metadata: any = null;
  293. /**
  294. * For internal use only. Please do not use.
  295. */
  296. public reservedDataStore: any = null;
  297. /**
  298. * Gets the name of the plugin used to load this scene (null by default)
  299. */
  300. public loadingPluginName: string;
  301. /**
  302. * Use this array to add regular expressions used to disable offline support for specific urls
  303. */
  304. public disableOfflineSupportExceptionRules = new Array<RegExp>();
  305. /**
  306. * An event triggered when the scene is disposed.
  307. */
  308. public onDisposeObservable = new Observable<Scene>();
  309. private _onDisposeObserver: Nullable<Observer<Scene>> = null;
  310. /** Sets a function to be executed when this scene is disposed. */
  311. public set onDispose(callback: () => void) {
  312. if (this._onDisposeObserver) {
  313. this.onDisposeObservable.remove(this._onDisposeObserver);
  314. }
  315. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  316. }
  317. /**
  318. * An event triggered before rendering the scene (right after animations and physics)
  319. */
  320. public onBeforeRenderObservable = new Observable<Scene>();
  321. private _onBeforeRenderObserver: Nullable<Observer<Scene>> = null;
  322. /** Sets a function to be executed before rendering this scene */
  323. public set beforeRender(callback: Nullable<() => void>) {
  324. if (this._onBeforeRenderObserver) {
  325. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  326. }
  327. if (callback) {
  328. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  329. }
  330. }
  331. /**
  332. * An event triggered after rendering the scene
  333. */
  334. public onAfterRenderObservable = new Observable<Scene>();
  335. private _onAfterRenderObserver: Nullable<Observer<Scene>> = null;
  336. /** Sets a function to be executed after rendering this scene */
  337. public set afterRender(callback: Nullable<() => void>) {
  338. if (this._onAfterRenderObserver) {
  339. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  340. }
  341. if (callback) {
  342. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  343. }
  344. }
  345. /**
  346. * An event triggered before animating the scene
  347. */
  348. public onBeforeAnimationsObservable = new Observable<Scene>();
  349. /**
  350. * An event triggered after animations processing
  351. */
  352. public onAfterAnimationsObservable = new Observable<Scene>();
  353. /**
  354. * An event triggered before draw calls are ready to be sent
  355. */
  356. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  357. /**
  358. * An event triggered after draw calls have been sent
  359. */
  360. public onAfterDrawPhaseObservable = new Observable<Scene>();
  361. /**
  362. * An event triggered when the scene is ready
  363. */
  364. public onReadyObservable = new Observable<Scene>();
  365. /**
  366. * An event triggered before rendering a camera
  367. */
  368. public onBeforeCameraRenderObservable = new Observable<Camera>();
  369. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>> = null;
  370. /** Sets a function to be executed before rendering a camera*/
  371. public set beforeCameraRender(callback: () => void) {
  372. if (this._onBeforeCameraRenderObserver) {
  373. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  374. }
  375. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  376. }
  377. /**
  378. * An event triggered after rendering a camera
  379. */
  380. public onAfterCameraRenderObservable = new Observable<Camera>();
  381. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>> = null;
  382. /** Sets a function to be executed after rendering a camera*/
  383. public set afterCameraRender(callback: () => void) {
  384. if (this._onAfterCameraRenderObserver) {
  385. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  386. }
  387. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  388. }
  389. /**
  390. * An event triggered when active meshes evaluation is about to start
  391. */
  392. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  393. /**
  394. * An event triggered when active meshes evaluation is done
  395. */
  396. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  397. /**
  398. * An event triggered when particles rendering is about to start
  399. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  400. */
  401. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  402. /**
  403. * An event triggered when particles rendering is done
  404. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  405. */
  406. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  407. /**
  408. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  409. */
  410. public onDataLoadedObservable = new Observable<Scene>();
  411. /**
  412. * An event triggered when a camera is created
  413. */
  414. public onNewCameraAddedObservable = new Observable<Camera>();
  415. /**
  416. * An event triggered when a camera is removed
  417. */
  418. public onCameraRemovedObservable = new Observable<Camera>();
  419. /**
  420. * An event triggered when a light is created
  421. */
  422. public onNewLightAddedObservable = new Observable<Light>();
  423. /**
  424. * An event triggered when a light is removed
  425. */
  426. public onLightRemovedObservable = new Observable<Light>();
  427. /**
  428. * An event triggered when a geometry is created
  429. */
  430. public onNewGeometryAddedObservable = new Observable<Geometry>();
  431. /**
  432. * An event triggered when a geometry is removed
  433. */
  434. public onGeometryRemovedObservable = new Observable<Geometry>();
  435. /**
  436. * An event triggered when a transform node is created
  437. */
  438. public onNewTransformNodeAddedObservable = new Observable<TransformNode>();
  439. /**
  440. * An event triggered when a transform node is removed
  441. */
  442. public onTransformNodeRemovedObservable = new Observable<TransformNode>();
  443. /**
  444. * An event triggered when a mesh is created
  445. */
  446. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  447. /**
  448. * An event triggered when a mesh is removed
  449. */
  450. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  451. /**
  452. * An event triggered when a material is created
  453. */
  454. public onNewMaterialAddedObservable = new Observable<Material>();
  455. /**
  456. * An event triggered when a material is removed
  457. */
  458. public onMaterialRemovedObservable = new Observable<Material>();
  459. /**
  460. * An event triggered when a texture is created
  461. */
  462. public onNewTextureAddedObservable = new Observable<BaseTexture>();
  463. /**
  464. * An event triggered when a texture is removed
  465. */
  466. public onTextureRemovedObservable = new Observable<BaseTexture>();
  467. /**
  468. * An event triggered when render targets are about to be rendered
  469. * Can happen multiple times per frame.
  470. */
  471. public onBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  472. /**
  473. * An event triggered when render targets were rendered.
  474. * Can happen multiple times per frame.
  475. */
  476. public onAfterRenderTargetsRenderObservable = new Observable<Scene>();
  477. /**
  478. * An event triggered before calculating deterministic simulation step
  479. */
  480. public onBeforeStepObservable = new Observable<Scene>();
  481. /**
  482. * An event triggered after calculating deterministic simulation step
  483. */
  484. public onAfterStepObservable = new Observable<Scene>();
  485. /**
  486. * An event triggered when the activeCamera property is updated
  487. */
  488. public onActiveCameraChanged = new Observable<Scene>();
  489. /**
  490. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  491. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  492. * 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)
  493. */
  494. public onBeforeRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  495. /**
  496. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  497. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  498. * 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)
  499. */
  500. public onAfterRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  501. /**
  502. * This Observable will when a mesh has been imported into the scene.
  503. */
  504. public onMeshImportedObservable = new Observable<AbstractMesh>();
  505. // Animations
  506. private _registeredForLateAnimationBindings = new SmartArrayNoDuplicate<any>(256);
  507. // Pointers
  508. /**
  509. * Gets or sets a predicate used to select candidate meshes for a pointer down event
  510. */
  511. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  512. /**
  513. * Gets or sets a predicate used to select candidate meshes for a pointer up event
  514. */
  515. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  516. /**
  517. * Gets or sets a predicate used to select candidate meshes for a pointer move event
  518. */
  519. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  520. private _onPointerMove: (evt: PointerEvent) => void;
  521. private _onPointerDown: (evt: PointerEvent) => void;
  522. private _onPointerUp: (evt: PointerEvent) => void;
  523. /** Callback called when a pointer move is detected */
  524. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  525. /** Callback called when a pointer down is detected */
  526. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  527. /** Callback called when a pointer up is detected */
  528. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>, type: PointerEventTypes) => void;
  529. /** Callback called when a pointer pick is detected */
  530. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  531. /**
  532. * 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).
  533. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  534. */
  535. public onPrePointerObservable = new Observable<PointerInfoPre>();
  536. /**
  537. * Observable event triggered each time an input event is received from the rendering canvas
  538. */
  539. public onPointerObservable = new Observable<PointerInfo>();
  540. /**
  541. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  542. */
  543. public get unTranslatedPointer(): Vector2 {
  544. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  545. }
  546. /** The distance in pixel that you have to move to prevent some events */
  547. public static DragMovementThreshold = 10; // in pixels
  548. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  549. public static LongPressDelay = 500; // in milliseconds
  550. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  551. public static DoubleClickDelay = 300; // in milliseconds
  552. /** If you need to check double click without raising a single click at first click, enable this flag */
  553. public static ExclusiveDoubleClickMode = false;
  554. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  555. private _initActionManager: (act: Nullable<ActionManager>, clickInfo: ClickInfo) => Nullable<ActionManager>;
  556. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  557. private _delayedSimpleClickTimeout: number;
  558. private _previousDelayedSimpleClickTimeout: number;
  559. private _meshPickProceed = false;
  560. private _previousButtonPressed: number;
  561. private _currentPickResult: Nullable<PickingInfo> = null;
  562. private _previousPickResult: Nullable<PickingInfo> = null;
  563. private _totalPointersPressed = 0;
  564. private _doubleClickOccured = false;
  565. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  566. public cameraToUseForPointers: Nullable<Camera> = null;
  567. private _pointerX: number = 0;
  568. private _pointerY: number = 0;
  569. private _unTranslatedPointerX: number;
  570. private _unTranslatedPointerY: number;
  571. private _startingPointerPosition = new Vector2(0, 0);
  572. private _previousStartingPointerPosition = new Vector2(0, 0);
  573. private _startingPointerTime = 0;
  574. private _previousStartingPointerTime = 0;
  575. private _pointerCaptures: { [pointerId: number]: boolean } = {};
  576. // Deterministic lockstep
  577. private _timeAccumulator: number = 0;
  578. private _currentStepId: number = 0;
  579. private _currentInternalStep: number = 0;
  580. // Mirror
  581. /** @hidden */
  582. public _mirroredCameraPosition: Nullable<Vector3>;
  583. // Keyboard
  584. /**
  585. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  586. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  587. */
  588. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  589. /**
  590. * Observable event triggered each time an keyboard event is received from the hosting window
  591. */
  592. public onKeyboardObservable = new Observable<KeyboardInfo>();
  593. private _onKeyDown: (evt: KeyboardEvent) => void;
  594. private _onKeyUp: (evt: KeyboardEvent) => void;
  595. private _onCanvasFocusObserver: Nullable<Observer<Engine>>;
  596. private _onCanvasBlurObserver: Nullable<Observer<Engine>>;
  597. // Coordinates system
  598. private _useRightHandedSystem = false;
  599. /**
  600. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  601. */
  602. public set useRightHandedSystem(value: boolean) {
  603. if (this._useRightHandedSystem === value) {
  604. return;
  605. }
  606. this._useRightHandedSystem = value;
  607. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  608. }
  609. public get useRightHandedSystem(): boolean {
  610. return this._useRightHandedSystem;
  611. }
  612. /**
  613. * Sets the step Id used by deterministic lock step
  614. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  615. * @param newStepId defines the step Id
  616. */
  617. public setStepId(newStepId: number): void {
  618. this._currentStepId = newStepId;
  619. }
  620. /**
  621. * Gets the step Id used by deterministic lock step
  622. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  623. * @returns the step Id
  624. */
  625. public getStepId(): number {
  626. return this._currentStepId;
  627. }
  628. /**
  629. * Gets the internal step used by deterministic lock step
  630. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  631. * @returns the internal step
  632. */
  633. public getInternalStep(): number {
  634. return this._currentInternalStep;
  635. }
  636. // Fog
  637. private _fogEnabled = true;
  638. /**
  639. * Gets or sets a boolean indicating if fog is enabled on this scene
  640. * @see http://doc.babylonjs.com/babylon101/environment#fog
  641. * (Default is true)
  642. */
  643. public set fogEnabled(value: boolean) {
  644. if (this._fogEnabled === value) {
  645. return;
  646. }
  647. this._fogEnabled = value;
  648. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  649. }
  650. public get fogEnabled(): boolean {
  651. return this._fogEnabled;
  652. }
  653. private _fogMode = Scene.FOGMODE_NONE;
  654. /**
  655. * Gets or sets the fog mode to use
  656. * @see http://doc.babylonjs.com/babylon101/environment#fog
  657. * | mode | value |
  658. * | --- | --- |
  659. * | FOGMODE_NONE | 0 |
  660. * | FOGMODE_EXP | 1 |
  661. * | FOGMODE_EXP2 | 2 |
  662. * | FOGMODE_LINEAR | 3 |
  663. */
  664. public set fogMode(value: number) {
  665. if (this._fogMode === value) {
  666. return;
  667. }
  668. this._fogMode = value;
  669. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  670. }
  671. public get fogMode(): number {
  672. return this._fogMode;
  673. }
  674. /**
  675. * Gets or sets the fog color to use
  676. * @see http://doc.babylonjs.com/babylon101/environment#fog
  677. * (Default is Color3(0.2, 0.2, 0.3))
  678. */
  679. public fogColor = new Color3(0.2, 0.2, 0.3);
  680. /**
  681. * Gets or sets the fog density to use
  682. * @see http://doc.babylonjs.com/babylon101/environment#fog
  683. * (Default is 0.1)
  684. */
  685. public fogDensity = 0.1;
  686. /**
  687. * Gets or sets the fog start distance to use
  688. * @see http://doc.babylonjs.com/babylon101/environment#fog
  689. * (Default is 0)
  690. */
  691. public fogStart = 0;
  692. /**
  693. * Gets or sets the fog end distance to use
  694. * @see http://doc.babylonjs.com/babylon101/environment#fog
  695. * (Default is 1000)
  696. */
  697. public fogEnd = 1000.0;
  698. // Lights
  699. private _shadowsEnabled = true;
  700. /**
  701. * Gets or sets a boolean indicating if shadows are enabled on this scene
  702. */
  703. public set shadowsEnabled(value: boolean) {
  704. if (this._shadowsEnabled === value) {
  705. return;
  706. }
  707. this._shadowsEnabled = value;
  708. this.markAllMaterialsAsDirty(Constants.MATERIAL_LightDirtyFlag);
  709. }
  710. public get shadowsEnabled(): boolean {
  711. return this._shadowsEnabled;
  712. }
  713. private _lightsEnabled = true;
  714. /**
  715. * Gets or sets a boolean indicating if lights are enabled on this scene
  716. */
  717. public set lightsEnabled(value: boolean) {
  718. if (this._lightsEnabled === value) {
  719. return;
  720. }
  721. this._lightsEnabled = value;
  722. this.markAllMaterialsAsDirty(Constants.MATERIAL_LightDirtyFlag);
  723. }
  724. public get lightsEnabled(): boolean {
  725. return this._lightsEnabled;
  726. }
  727. /** All of the active cameras added to this scene. */
  728. public activeCameras = new Array<Camera>();
  729. private _activeCamera: Nullable<Camera>;
  730. /** Gets or sets the current active camera */
  731. public get activeCamera(): Nullable<Camera> {
  732. return this._activeCamera;
  733. }
  734. public set activeCamera(value: Nullable<Camera>) {
  735. if (value === this._activeCamera) {
  736. return;
  737. }
  738. this._activeCamera = value;
  739. this.onActiveCameraChanged.notifyObservers(this);
  740. }
  741. private _defaultMaterial: Material;
  742. /** The default material used on meshes when no material is affected */
  743. public get defaultMaterial(): Material {
  744. if (!this._defaultMaterial) {
  745. this._defaultMaterial = Scene.DefaultMaterialFactory(this);
  746. }
  747. return this._defaultMaterial;
  748. }
  749. /** The default material used on meshes when no material is affected */
  750. public set defaultMaterial(value: Material) {
  751. this._defaultMaterial = value;
  752. }
  753. // Textures
  754. private _texturesEnabled = true;
  755. /**
  756. * Gets or sets a boolean indicating if textures are enabled on this scene
  757. */
  758. public set texturesEnabled(value: boolean) {
  759. if (this._texturesEnabled === value) {
  760. return;
  761. }
  762. this._texturesEnabled = value;
  763. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  764. }
  765. public get texturesEnabled(): boolean {
  766. return this._texturesEnabled;
  767. }
  768. // Particles
  769. /**
  770. * Gets or sets a boolean indicating if particles are enabled on this scene
  771. */
  772. public particlesEnabled = true;
  773. // Sprites
  774. /**
  775. * Gets or sets a boolean indicating if sprites are enabled on this scene
  776. */
  777. public spritesEnabled = true;
  778. // Skeletons
  779. private _skeletonsEnabled = true;
  780. /**
  781. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  782. */
  783. public set skeletonsEnabled(value: boolean) {
  784. if (this._skeletonsEnabled === value) {
  785. return;
  786. }
  787. this._skeletonsEnabled = value;
  788. this.markAllMaterialsAsDirty(Constants.MATERIAL_AttributesDirtyFlag);
  789. }
  790. public get skeletonsEnabled(): boolean {
  791. return this._skeletonsEnabled;
  792. }
  793. // Lens flares
  794. /**
  795. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  796. */
  797. public lensFlaresEnabled = true;
  798. // Collisions
  799. /**
  800. * Gets or sets a boolean indicating if collisions are enabled on this scene
  801. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  802. */
  803. public collisionsEnabled = true;
  804. /** @hidden */
  805. public collisionCoordinator: ICollisionCoordinator;
  806. /**
  807. * Defines the gravity applied to this scene (used only for collisions)
  808. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  809. */
  810. public gravity = new Vector3(0, -9.807, 0);
  811. // Postprocesses
  812. /**
  813. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  814. */
  815. public postProcessesEnabled = true;
  816. /**
  817. * The list of postprocesses added to the scene
  818. */
  819. public postProcesses = new Array<PostProcess>();
  820. /**
  821. * Gets the current postprocess manager
  822. */
  823. public postProcessManager: PostProcessManager;
  824. // Customs render targets
  825. /**
  826. * Gets or sets a boolean indicating if render targets are enabled on this scene
  827. */
  828. public renderTargetsEnabled = true;
  829. /**
  830. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  831. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  832. */
  833. public dumpNextRenderTargets = false;
  834. /**
  835. * The list of user defined render targets added to the scene
  836. */
  837. public customRenderTargets = new Array<RenderTargetTexture>();
  838. /**
  839. * Defines if texture loading must be delayed
  840. * If true, textures will only be loaded when they need to be rendered
  841. */
  842. public useDelayedTextureLoading: boolean;
  843. /**
  844. * Gets the list of meshes imported to the scene through SceneLoader
  845. */
  846. public importedMeshesFiles = new Array<String>();
  847. // Probes
  848. /**
  849. * Gets or sets a boolean indicating if probes are enabled on this scene
  850. */
  851. public probesEnabled = true;
  852. // Offline support
  853. /**
  854. * Gets or sets the current offline provider to use to store scene data
  855. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  856. */
  857. public offlineProvider: IOfflineProvider;
  858. /**
  859. * Gets or sets the action manager associated with the scene
  860. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  861. */
  862. public actionManager: ActionManager;
  863. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  864. // Procedural textures
  865. /**
  866. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  867. */
  868. public proceduralTexturesEnabled = true;
  869. // Private
  870. private _engine: Engine;
  871. // Performance counters
  872. private _totalVertices = new PerfCounter();
  873. /** @hidden */
  874. public _activeIndices = new PerfCounter();
  875. /** @hidden */
  876. public _activeParticles = new PerfCounter();
  877. /** @hidden */
  878. public _activeBones = new PerfCounter();
  879. private _animationRatio: number;
  880. private _animationTimeLast: number;
  881. private _animationTime: number = 0;
  882. /**
  883. * Gets or sets a general scale for animation speed
  884. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  885. */
  886. public animationTimeScale: number = 1;
  887. /** @hidden */
  888. public _cachedMaterial: Nullable<Material>;
  889. /** @hidden */
  890. public _cachedEffect: Nullable<Effect>;
  891. /** @hidden */
  892. public _cachedVisibility: Nullable<number>;
  893. private _renderId = 0;
  894. private _frameId = 0;
  895. private _executeWhenReadyTimeoutId = -1;
  896. private _intermediateRendering = false;
  897. private _viewUpdateFlag = -1;
  898. private _projectionUpdateFlag = -1;
  899. private _alternateViewUpdateFlag = -1;
  900. private _alternateProjectionUpdateFlag = -1;
  901. /** @hidden */
  902. public _toBeDisposed = new Array<Nullable<IDisposable>>(256);
  903. private _activeRequests = new Array<IFileRequest>();
  904. private _pendingData = new Array();
  905. private _isDisposed = false;
  906. /**
  907. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  908. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  909. */
  910. public dispatchAllSubMeshesOfActiveMeshes: boolean = false;
  911. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  912. private _processedMaterials = new SmartArray<Material>(256);
  913. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  914. /** @hidden */
  915. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  916. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  917. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  918. private _renderingManager: RenderingManager;
  919. /** @hidden */
  920. public _activeAnimatables = new Array<Animatable>();
  921. private _transformMatrix = Matrix.Zero();
  922. private _sceneUbo: UniformBuffer;
  923. private _alternateSceneUbo: UniformBuffer;
  924. private _pickWithRayInverseMatrix: Matrix;
  925. private _viewMatrix: Matrix;
  926. private _projectionMatrix: Matrix;
  927. private _alternateViewMatrix: Matrix;
  928. private _alternateProjectionMatrix: Matrix;
  929. private _alternateTransformMatrix: Matrix;
  930. private _useAlternateCameraConfiguration = false;
  931. private _alternateRendering = false;
  932. private _wheelEventName = "";
  933. /** @hidden */
  934. public _forcedViewPosition: Nullable<Vector3>;
  935. /** @hidden */
  936. public get _isAlternateRenderingEnabled(): boolean {
  937. return this._alternateRendering;
  938. }
  939. private _frustumPlanes: Plane[];
  940. /**
  941. * Gets the list of frustum planes (built from the active camera)
  942. */
  943. public get frustumPlanes(): Plane[] {
  944. return this._frustumPlanes;
  945. }
  946. /**
  947. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  948. * This is useful if there are more lights that the maximum simulteanous authorized
  949. */
  950. public requireLightSorting = false;
  951. /** @hidden */
  952. public readonly useMaterialMeshMap: boolean;
  953. /** @hidden */
  954. public readonly useClonedMeshhMap: boolean;
  955. private _pointerOverMesh: Nullable<AbstractMesh>;
  956. private _pickedDownMesh: Nullable<AbstractMesh>;
  957. private _pickedUpMesh: Nullable<AbstractMesh>;
  958. private _externalData: StringDictionary<Object>;
  959. private _uid: Nullable<string>;
  960. /**
  961. * @hidden
  962. * Backing store of defined scene components.
  963. */
  964. public _components: ISceneComponent[] = [];
  965. /**
  966. * @hidden
  967. * Backing store of defined scene components.
  968. */
  969. public _serializableComponents: ISceneSerializableComponent[] = [];
  970. /**
  971. * List of components to register on the next registration step.
  972. */
  973. private _transientComponents: ISceneComponent[] = [];
  974. /**
  975. * Registers the transient components if needed.
  976. */
  977. private _registerTransientComponents(): void {
  978. // Register components that have been associated lately to the scene.
  979. if (this._transientComponents.length > 0) {
  980. for (let component of this._transientComponents) {
  981. component.register();
  982. }
  983. this._transientComponents = [];
  984. }
  985. }
  986. /**
  987. * @hidden
  988. * Add a component to the scene.
  989. * Note that the ccomponent could be registered on th next frame if this is called after
  990. * the register component stage.
  991. * @param component Defines the component to add to the scene
  992. */
  993. public _addComponent(component: ISceneComponent) {
  994. this._components.push(component);
  995. this._transientComponents.push(component);
  996. const serializableComponent = component as ISceneSerializableComponent;
  997. if (serializableComponent.addFromContainer) {
  998. this._serializableComponents.push(serializableComponent);
  999. }
  1000. }
  1001. /**
  1002. * @hidden
  1003. * Gets a component from the scene.
  1004. * @param name defines the name of the component to retrieve
  1005. * @returns the component or null if not present
  1006. */
  1007. public _getComponent(name: string): Nullable<ISceneComponent> {
  1008. for (let component of this._components) {
  1009. if (component.name === name) {
  1010. return component;
  1011. }
  1012. }
  1013. return null;
  1014. }
  1015. /**
  1016. * @hidden
  1017. * Defines the actions happening before camera updates.
  1018. */
  1019. public _beforeCameraUpdateStage = Stage.Create<SimpleStageAction>();
  1020. /**
  1021. * @hidden
  1022. * Defines the actions happening before clear the canvas.
  1023. */
  1024. public _beforeClearStage = Stage.Create<SimpleStageAction>();
  1025. /**
  1026. * @hidden
  1027. * Defines the actions when collecting render targets for the frame.
  1028. */
  1029. public _gatherRenderTargetsStage = Stage.Create<RenderTargetsStageAction>();
  1030. /**
  1031. * @hidden
  1032. * Defines the actions happening for one camera in the frame.
  1033. */
  1034. public _gatherActiveCameraRenderTargetsStage = Stage.Create<RenderTargetsStageAction>();
  1035. /**
  1036. * @hidden
  1037. * Defines the actions happening during the per mesh ready checks.
  1038. */
  1039. public _isReadyForMeshStage = Stage.Create<MeshStageAction>();
  1040. /**
  1041. * @hidden
  1042. * Defines the actions happening before evaluate active mesh checks.
  1043. */
  1044. public _beforeEvaluateActiveMeshStage = Stage.Create<SimpleStageAction>();
  1045. /**
  1046. * @hidden
  1047. * Defines the actions happening during the evaluate sub mesh checks.
  1048. */
  1049. public _evaluateSubMeshStage = Stage.Create<EvaluateSubMeshStageAction>();
  1050. /**
  1051. * @hidden
  1052. * Defines the actions happening during the active mesh stage.
  1053. */
  1054. public _activeMeshStage = Stage.Create<ActiveMeshStageAction>();
  1055. /**
  1056. * @hidden
  1057. * Defines the actions happening during the per camera render target step.
  1058. */
  1059. public _cameraDrawRenderTargetStage = Stage.Create<CameraStageAction>();
  1060. /**
  1061. * @hidden
  1062. * Defines the actions happening just before the active camera is drawing.
  1063. */
  1064. public _beforeCameraDrawStage = Stage.Create<CameraStageAction>();
  1065. /**
  1066. * @hidden
  1067. * Defines the actions happening just before a render target is drawing.
  1068. */
  1069. public _beforeRenderTargetDrawStage = Stage.Create<RenderTargetStageAction>();
  1070. /**
  1071. * @hidden
  1072. * Defines the actions happening just before a rendering group is drawing.
  1073. */
  1074. public _beforeRenderingGroupDrawStage = Stage.Create<RenderingGroupStageAction>();
  1075. /**
  1076. * @hidden
  1077. * Defines the actions happening just before a mesh is drawing.
  1078. */
  1079. public _beforeRenderingMeshStage = Stage.Create<RenderingMeshStageAction>();
  1080. /**
  1081. * @hidden
  1082. * Defines the actions happening just after a mesh has been drawn.
  1083. */
  1084. public _afterRenderingMeshStage = Stage.Create<RenderingMeshStageAction>();
  1085. /**
  1086. * @hidden
  1087. * Defines the actions happening just after a rendering group has been drawn.
  1088. */
  1089. public _afterRenderingGroupDrawStage = Stage.Create<RenderingGroupStageAction>();
  1090. /**
  1091. * @hidden
  1092. * Defines the actions happening just after the active camera has been drawn.
  1093. */
  1094. public _afterCameraDrawStage = Stage.Create<CameraStageAction>();
  1095. /**
  1096. * @hidden
  1097. * Defines the actions happening just after a render target has been drawn.
  1098. */
  1099. public _afterRenderTargetDrawStage = Stage.Create<RenderTargetStageAction>();
  1100. /**
  1101. * @hidden
  1102. * Defines the actions happening just after rendering all cameras and computing intersections.
  1103. */
  1104. public _afterRenderStage = Stage.Create<SimpleStageAction>();
  1105. /**
  1106. * @hidden
  1107. * Defines the actions happening when a pointer move event happens.
  1108. */
  1109. public _pointerMoveStage = Stage.Create<PointerMoveStageAction>();
  1110. /**
  1111. * @hidden
  1112. * Defines the actions happening when a pointer down event happens.
  1113. */
  1114. public _pointerDownStage = Stage.Create<PointerUpDownStageAction>();
  1115. /**
  1116. * @hidden
  1117. * Defines the actions happening when a pointer up event happens.
  1118. */
  1119. public _pointerUpStage = Stage.Create<PointerUpDownStageAction>();
  1120. /**
  1121. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  1122. */
  1123. private geometriesByUniqueId: Nullable<{ [uniqueId: string]: number | undefined }> = null;
  1124. /**
  1125. * Creates a new Scene
  1126. * @param engine defines the engine to use to render this scene
  1127. * @param options defines the scene options
  1128. */
  1129. constructor(engine: Engine, options?: SceneOptions) {
  1130. super();
  1131. this._engine = engine || EngineStore.LastCreatedEngine;
  1132. this._engine.scenes.push(this);
  1133. this._uid = null;
  1134. this._renderingManager = new RenderingManager(this);
  1135. if (PostProcessManager) {
  1136. this.postProcessManager = new PostProcessManager(this);
  1137. }
  1138. if (DomManagement.IsWindowObjectExist()) {
  1139. this.attachControl();
  1140. }
  1141. //collision coordinator initialization. For now legacy per default.
  1142. this.workerCollisions = false; //(!!Worker && (!!CollisionWorker || WorkerIncluded));
  1143. // Uniform Buffer
  1144. this._createUbo();
  1145. // Default Image processing definition
  1146. if (ImageProcessingConfiguration) {
  1147. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  1148. }
  1149. this.setDefaultCandidateProviders();
  1150. if (options && options.useGeometryUniqueIdsMap === true) {
  1151. this.geometriesByUniqueId = {};
  1152. }
  1153. this.useMaterialMeshMap = options && options.useGeometryUniqueIdsMap || false;
  1154. this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  1155. this._engine.onNewSceneAddedObservable.notifyObservers(this);
  1156. }
  1157. private _defaultMeshCandidates: ISmartArrayLike<AbstractMesh> = {
  1158. data: [],
  1159. length: 0
  1160. };
  1161. /**
  1162. * @hidden
  1163. */
  1164. public _getDefaultMeshCandidates(): ISmartArrayLike<AbstractMesh> {
  1165. this._defaultMeshCandidates.data = this.meshes;
  1166. this._defaultMeshCandidates.length = this.meshes.length;
  1167. return this._defaultMeshCandidates;
  1168. }
  1169. private _defaultSubMeshCandidates: ISmartArrayLike<SubMesh> = {
  1170. data: [],
  1171. length: 0
  1172. };
  1173. /**
  1174. * @hidden
  1175. */
  1176. public _getDefaultSubMeshCandidates(mesh: AbstractMesh): ISmartArrayLike<SubMesh> {
  1177. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  1178. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  1179. return this._defaultSubMeshCandidates;
  1180. }
  1181. /**
  1182. * Sets the default candidate providers for the scene.
  1183. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  1184. * and getCollidingSubMeshCandidates to their default function
  1185. */
  1186. public setDefaultCandidateProviders(): void {
  1187. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  1188. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1189. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1190. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1191. }
  1192. public set workerCollisions(enabled: boolean) {
  1193. if (!CollisionCoordinatorLegacy) {
  1194. return;
  1195. }
  1196. if (this.collisionCoordinator) {
  1197. this.collisionCoordinator.destroy();
  1198. }
  1199. this.collisionCoordinator = new CollisionCoordinatorLegacy();
  1200. this.collisionCoordinator.init(this);
  1201. }
  1202. /**
  1203. * Gets a boolean indicating if collisions are processed on a web worker
  1204. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  1205. */
  1206. public get workerCollisions(): boolean {
  1207. // Worker has been deprecated.
  1208. // Keep for back compat.
  1209. return false;
  1210. }
  1211. /**
  1212. * Gets the mesh that is currently under the pointer
  1213. */
  1214. public get meshUnderPointer(): Nullable<AbstractMesh> {
  1215. return this._pointerOverMesh;
  1216. }
  1217. /**
  1218. * Gets or sets the current on-screen X position of the pointer
  1219. */
  1220. public get pointerX(): number {
  1221. return this._pointerX;
  1222. }
  1223. public set pointerX(value: number) {
  1224. this._pointerX = value;
  1225. }
  1226. /**
  1227. * Gets or sets the current on-screen Y position of the pointer
  1228. */
  1229. public get pointerY(): number {
  1230. return this._pointerY;
  1231. }
  1232. public set pointerY(value: number) {
  1233. this._pointerY = value;
  1234. }
  1235. /**
  1236. * Gets the cached material (ie. the latest rendered one)
  1237. * @returns the cached material
  1238. */
  1239. public getCachedMaterial(): Nullable<Material> {
  1240. return this._cachedMaterial;
  1241. }
  1242. /**
  1243. * Gets the cached effect (ie. the latest rendered one)
  1244. * @returns the cached effect
  1245. */
  1246. public getCachedEffect(): Nullable<Effect> {
  1247. return this._cachedEffect;
  1248. }
  1249. /**
  1250. * Gets the cached visibility state (ie. the latest rendered one)
  1251. * @returns the cached visibility state
  1252. */
  1253. public getCachedVisibility(): Nullable<number> {
  1254. return this._cachedVisibility;
  1255. }
  1256. /**
  1257. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  1258. * @param material defines the current material
  1259. * @param effect defines the current effect
  1260. * @param visibility defines the current visibility state
  1261. * @returns true if one parameter is not cached
  1262. */
  1263. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  1264. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  1265. }
  1266. /**
  1267. * Gets the engine associated with the scene
  1268. * @returns an Engine
  1269. */
  1270. public getEngine(): Engine {
  1271. return this._engine;
  1272. }
  1273. /**
  1274. * Gets the total number of vertices rendered per frame
  1275. * @returns the total number of vertices rendered per frame
  1276. */
  1277. public getTotalVertices(): number {
  1278. return this._totalVertices.current;
  1279. }
  1280. /**
  1281. * Gets the performance counter for total vertices
  1282. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1283. */
  1284. public get totalVerticesPerfCounter(): PerfCounter {
  1285. return this._totalVertices;
  1286. }
  1287. /**
  1288. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  1289. * @returns the total number of active indices rendered per frame
  1290. */
  1291. public getActiveIndices(): number {
  1292. return this._activeIndices.current;
  1293. }
  1294. /**
  1295. * Gets the performance counter for active indices
  1296. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1297. */
  1298. public get totalActiveIndicesPerfCounter(): PerfCounter {
  1299. return this._activeIndices;
  1300. }
  1301. /**
  1302. * Gets the total number of active particles rendered per frame
  1303. * @returns the total number of active particles rendered per frame
  1304. */
  1305. public getActiveParticles(): number {
  1306. return this._activeParticles.current;
  1307. }
  1308. /**
  1309. * Gets the performance counter for active particles
  1310. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1311. */
  1312. public get activeParticlesPerfCounter(): PerfCounter {
  1313. return this._activeParticles;
  1314. }
  1315. /**
  1316. * Gets the total number of active bones rendered per frame
  1317. * @returns the total number of active bones rendered per frame
  1318. */
  1319. public getActiveBones(): number {
  1320. return this._activeBones.current;
  1321. }
  1322. /**
  1323. * Gets the performance counter for active bones
  1324. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1325. */
  1326. public get activeBonesPerfCounter(): PerfCounter {
  1327. return this._activeBones;
  1328. }
  1329. /**
  1330. * Gets the array of active meshes
  1331. * @returns an array of AbstractMesh
  1332. */
  1333. public getActiveMeshes(): SmartArray<AbstractMesh> {
  1334. return this._activeMeshes;
  1335. }
  1336. /**
  1337. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  1338. * @returns a number
  1339. */
  1340. public getAnimationRatio(): number {
  1341. return this._animationRatio !== undefined ? this._animationRatio : 1;
  1342. }
  1343. /**
  1344. * Gets an unique Id for the current render phase
  1345. * @returns a number
  1346. */
  1347. public getRenderId(): number {
  1348. return this._renderId;
  1349. }
  1350. /**
  1351. * Gets an unique Id for the current frame
  1352. * @returns a number
  1353. */
  1354. public getFrameId(): number {
  1355. return this._frameId;
  1356. }
  1357. /** Call this function if you want to manually increment the render Id*/
  1358. public incrementRenderId(): void {
  1359. this._renderId++;
  1360. }
  1361. private _updatePointerPosition(evt: PointerEvent): void {
  1362. var canvasRect = this._engine.getRenderingCanvasClientRect();
  1363. if (!canvasRect) {
  1364. return;
  1365. }
  1366. this._pointerX = evt.clientX - canvasRect.left;
  1367. this._pointerY = evt.clientY - canvasRect.top;
  1368. this._unTranslatedPointerX = this._pointerX;
  1369. this._unTranslatedPointerY = this._pointerY;
  1370. }
  1371. private _createUbo(): void {
  1372. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  1373. this._sceneUbo.addUniform("viewProjection", 16);
  1374. this._sceneUbo.addUniform("view", 16);
  1375. }
  1376. private _createAlternateUbo(): void {
  1377. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  1378. this._alternateSceneUbo.addUniform("viewProjection", 16);
  1379. this._alternateSceneUbo.addUniform("view", 16);
  1380. }
  1381. // Pointers handling
  1382. private _setRayOnPointerInfo(pointerInfo: PointerInfo) {
  1383. if (pointerInfo.pickInfo) {
  1384. if (!pointerInfo.pickInfo.ray) {
  1385. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, Matrix.Identity(), this.activeCamera);
  1386. }
  1387. }
  1388. }
  1389. /**
  1390. * Use this method to simulate a pointer move on a mesh
  1391. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1392. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1393. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1394. * @returns the current scene
  1395. */
  1396. public simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1397. let evt = new PointerEvent("pointermove", pointerEventInit);
  1398. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERMOVE)) {
  1399. return this;
  1400. }
  1401. return this._processPointerMove(pickResult, evt);
  1402. }
  1403. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1404. var canvas = this._engine.getRenderingCanvas();
  1405. if (!canvas) {
  1406. return this;
  1407. }
  1408. // Restore pointer
  1409. canvas.style.cursor = this.defaultCursor;
  1410. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  1411. if (isMeshPicked) {
  1412. this.setPointerOverMesh(pickResult!.pickedMesh);
  1413. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  1414. if (this._pointerOverMesh.actionManager.hoverCursor) {
  1415. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  1416. } else {
  1417. canvas.style.cursor = this.hoverCursor;
  1418. }
  1419. }
  1420. } else {
  1421. this.setPointerOverMesh(null);
  1422. }
  1423. for (let step of this._pointerMoveStage) {
  1424. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  1425. }
  1426. if (pickResult) {
  1427. let type = evt.type === this._wheelEventName ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1428. if (this.onPointerMove) {
  1429. this.onPointerMove(evt, pickResult, type);
  1430. }
  1431. if (this.onPointerObservable.hasObservers()) {
  1432. let pi = new PointerInfo(type, evt, pickResult);
  1433. this._setRayOnPointerInfo(pi);
  1434. this.onPointerObservable.notifyObservers(pi, type);
  1435. }
  1436. }
  1437. return this;
  1438. }
  1439. private _checkPrePointerObservable(pickResult: Nullable<PickingInfo>, evt: PointerEvent, type: number) {
  1440. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1441. if (pickResult) {
  1442. pi.ray = pickResult.ray;
  1443. }
  1444. this.onPrePointerObservable.notifyObservers(pi, type);
  1445. if (pi.skipOnPointerObservable) {
  1446. return true;
  1447. } else {
  1448. return false;
  1449. }
  1450. }
  1451. /**
  1452. * Use this method to simulate a pointer down on a mesh
  1453. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1454. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1455. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1456. * @returns the current scene
  1457. */
  1458. public simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1459. let evt = new PointerEvent("pointerdown", pointerEventInit);
  1460. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)) {
  1461. return this;
  1462. }
  1463. return this._processPointerDown(pickResult, evt);
  1464. }
  1465. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1466. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1467. this._pickedDownMesh = pickResult.pickedMesh;
  1468. var actionManager = pickResult.pickedMesh.actionManager;
  1469. if (actionManager) {
  1470. if (actionManager.hasPickTriggers) {
  1471. actionManager.processTrigger(Constants.ACTION_OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1472. switch (evt.button) {
  1473. case 0:
  1474. actionManager.processTrigger(Constants.ACTION_OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1475. break;
  1476. case 1:
  1477. actionManager.processTrigger(Constants.ACTION_OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1478. break;
  1479. case 2:
  1480. actionManager.processTrigger(Constants.ACTION_OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1481. break;
  1482. }
  1483. }
  1484. if (actionManager.hasSpecificTrigger(Constants.ACTION_OnLongPressTrigger)) {
  1485. window.setTimeout(() => {
  1486. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1487. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(Constants.ACTION_OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1488. false, this.cameraToUseForPointers);
  1489. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1490. if (this._totalPointersPressed !== 0 &&
  1491. ((Date.now() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1492. !this._isPointerSwiping()) {
  1493. this._startingPointerTime = 0;
  1494. actionManager.processTrigger(Constants.ACTION_OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1495. }
  1496. }
  1497. }, Scene.LongPressDelay);
  1498. }
  1499. }
  1500. }
  1501. else {
  1502. for (let step of this._pointerDownStage) {
  1503. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  1504. }
  1505. }
  1506. if (pickResult) {
  1507. let type = PointerEventTypes.POINTERDOWN;
  1508. if (this.onPointerDown) {
  1509. this.onPointerDown(evt, pickResult, type);
  1510. }
  1511. if (this.onPointerObservable.hasObservers()) {
  1512. let pi = new PointerInfo(type, evt, pickResult);
  1513. this._setRayOnPointerInfo(pi);
  1514. this.onPointerObservable.notifyObservers(pi, type);
  1515. }
  1516. }
  1517. return this;
  1518. }
  1519. /**
  1520. * Use this method to simulate a pointer up on a mesh
  1521. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1522. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1523. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1524. * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
  1525. * @returns the current scene
  1526. */
  1527. public simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit, doubleTap?: boolean): Scene {
  1528. let evt = new PointerEvent("pointerup", pointerEventInit);
  1529. let clickInfo = new ClickInfo();
  1530. if (doubleTap) {
  1531. clickInfo.doubleClick = true;
  1532. } else {
  1533. clickInfo.singleClick = true;
  1534. }
  1535. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)) {
  1536. return this;
  1537. }
  1538. return this._processPointerUp(pickResult, evt, clickInfo);
  1539. }
  1540. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1541. if (pickResult && pickResult && pickResult.pickedMesh) {
  1542. this._pickedUpMesh = pickResult.pickedMesh;
  1543. if (this._pickedDownMesh === this._pickedUpMesh) {
  1544. if (this.onPointerPick) {
  1545. this.onPointerPick(evt, pickResult);
  1546. }
  1547. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1548. let type = PointerEventTypes.POINTERPICK;
  1549. let pi = new PointerInfo(type, evt, pickResult);
  1550. this._setRayOnPointerInfo(pi);
  1551. this.onPointerObservable.notifyObservers(pi, type);
  1552. }
  1553. }
  1554. if (pickResult.pickedMesh.actionManager && !clickInfo.ignore) {
  1555. pickResult.pickedMesh.actionManager.processTrigger(Constants.ACTION_OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1556. if (!clickInfo.hasSwiped && clickInfo.singleClick) {
  1557. pickResult.pickedMesh.actionManager.processTrigger(Constants.ACTION_OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1558. }
  1559. if (clickInfo.doubleClick && pickResult.pickedMesh.actionManager.hasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger)) {
  1560. pickResult.pickedMesh.actionManager.processTrigger(Constants.ACTION_OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1561. }
  1562. }
  1563. }
  1564. else {
  1565. if (!clickInfo.ignore) {
  1566. for (let step of this._pointerUpStage) {
  1567. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  1568. }
  1569. }
  1570. }
  1571. if (this._pickedDownMesh &&
  1572. this._pickedDownMesh.actionManager &&
  1573. this._pickedDownMesh.actionManager.hasSpecificTrigger(Constants.ACTION_OnPickOutTrigger) &&
  1574. this._pickedDownMesh !== this._pickedUpMesh) {
  1575. this._pickedDownMesh.actionManager.processTrigger(Constants.ACTION_OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1576. }
  1577. let type = 0;
  1578. if (this.onPointerObservable.hasObservers()) {
  1579. if (!clickInfo.ignore && !clickInfo.hasSwiped) {
  1580. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1581. type = PointerEventTypes.POINTERTAP;
  1582. }
  1583. else if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1584. type = PointerEventTypes.POINTERDOUBLETAP;
  1585. }
  1586. if (type) {
  1587. let pi = new PointerInfo(type, evt, pickResult);
  1588. this._setRayOnPointerInfo(pi);
  1589. this.onPointerObservable.notifyObservers(pi, type);
  1590. }
  1591. }
  1592. if (!clickInfo.ignore) {
  1593. type = PointerEventTypes.POINTERUP;
  1594. let pi = new PointerInfo(type, evt, pickResult);
  1595. this._setRayOnPointerInfo(pi);
  1596. this.onPointerObservable.notifyObservers(pi, type);
  1597. }
  1598. }
  1599. if (this.onPointerUp && !clickInfo.ignore) {
  1600. this.onPointerUp(evt, pickResult, type);
  1601. }
  1602. return this;
  1603. }
  1604. /**
  1605. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  1606. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  1607. * @returns true if the pointer was captured
  1608. */
  1609. public isPointerCaptured(pointerId = 0): boolean {
  1610. return this._pointerCaptures[pointerId];
  1611. }
  1612. /** @hidden */
  1613. public _isPointerSwiping(): boolean {
  1614. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1615. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1616. }
  1617. /**
  1618. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1619. * @param attachUp defines if you want to attach events to pointerup
  1620. * @param attachDown defines if you want to attach events to pointerdown
  1621. * @param attachMove defines if you want to attach events to pointermove
  1622. */
  1623. public attachControl(attachUp = true, attachDown = true, attachMove = true): void {
  1624. this._initActionManager = (act: Nullable<ActionManager>, clickInfo: ClickInfo): Nullable<ActionManager> => {
  1625. if (!this._meshPickProceed) {
  1626. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1627. this._currentPickResult = pickResult;
  1628. if (pickResult) {
  1629. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1630. }
  1631. this._meshPickProceed = true;
  1632. }
  1633. return act;
  1634. };
  1635. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1636. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1637. if ((Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1638. btn !== this._previousButtonPressed) {
  1639. this._doubleClickOccured = false;
  1640. clickInfo.singleClick = true;
  1641. clickInfo.ignore = false;
  1642. cb(clickInfo, this._currentPickResult);
  1643. }
  1644. };
  1645. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1646. let clickInfo = new ClickInfo();
  1647. this._currentPickResult = null;
  1648. let act: Nullable<ActionManager> = null;
  1649. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1650. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1651. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1652. if (!checkPicking && ActionManager) {
  1653. act = this._initActionManager(act, clickInfo);
  1654. if (act) {
  1655. checkPicking = act.hasPickTriggers;
  1656. }
  1657. }
  1658. let needToIgnoreNext = false;
  1659. if (checkPicking) {
  1660. let btn = evt.button;
  1661. clickInfo.hasSwiped = this._isPointerSwiping();
  1662. if (!clickInfo.hasSwiped) {
  1663. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1664. if (!checkSingleClickImmediately) {
  1665. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1666. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1667. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger)) {
  1668. act = this._initActionManager(act, clickInfo);
  1669. if (act) {
  1670. checkSingleClickImmediately = !act.hasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger);
  1671. }
  1672. }
  1673. }
  1674. if (checkSingleClickImmediately) {
  1675. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1676. if (Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1677. btn !== this._previousButtonPressed) {
  1678. clickInfo.singleClick = true;
  1679. cb(clickInfo, this._currentPickResult);
  1680. needToIgnoreNext = true;
  1681. }
  1682. }
  1683. // at least one double click is required to be check and exclusive double click is enabled
  1684. else {
  1685. // wait that no double click has been raised during the double click delay
  1686. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1687. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1688. }
  1689. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1690. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1691. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger)) {
  1692. act = this._initActionManager(act, clickInfo);
  1693. if (act) {
  1694. checkDoubleClick = act.hasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger);
  1695. }
  1696. }
  1697. if (checkDoubleClick) {
  1698. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1699. if (btn === this._previousButtonPressed &&
  1700. Date.now() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1701. !this._doubleClickOccured
  1702. ) {
  1703. // pointer has not moved for 2 clicks, it's a double click
  1704. if (!clickInfo.hasSwiped &&
  1705. !this._isPointerSwiping()) {
  1706. this._previousStartingPointerTime = 0;
  1707. this._doubleClickOccured = true;
  1708. clickInfo.doubleClick = true;
  1709. clickInfo.ignore = false;
  1710. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1711. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1712. }
  1713. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1714. cb(clickInfo, this._currentPickResult);
  1715. }
  1716. // if the two successive clicks are too far, it's just two simple clicks
  1717. else {
  1718. this._doubleClickOccured = false;
  1719. this._previousStartingPointerTime = this._startingPointerTime;
  1720. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1721. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1722. this._previousButtonPressed = btn;
  1723. if (Scene.ExclusiveDoubleClickMode) {
  1724. if (this._previousDelayedSimpleClickTimeout) {
  1725. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1726. }
  1727. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1728. cb(clickInfo, this._previousPickResult);
  1729. }
  1730. else {
  1731. cb(clickInfo, this._currentPickResult);
  1732. }
  1733. }
  1734. needToIgnoreNext = true;
  1735. }
  1736. // just the first click of the double has been raised
  1737. else {
  1738. this._doubleClickOccured = false;
  1739. this._previousStartingPointerTime = this._startingPointerTime;
  1740. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1741. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1742. this._previousButtonPressed = btn;
  1743. }
  1744. }
  1745. }
  1746. }
  1747. if (!needToIgnoreNext) {
  1748. cb(clickInfo, this._currentPickResult);
  1749. }
  1750. };
  1751. this._onPointerMove = (evt: PointerEvent) => {
  1752. this._updatePointerPosition(evt);
  1753. // PreObservable support
  1754. if (this._checkPrePointerObservable(null, evt, evt.type === this._wheelEventName ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)) {
  1755. return;
  1756. }
  1757. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1758. return;
  1759. }
  1760. if (!this.pointerMovePredicate) {
  1761. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1762. }
  1763. // Meshes
  1764. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1765. this._processPointerMove(pickResult, evt);
  1766. };
  1767. this._onPointerDown = (evt: PointerEvent) => {
  1768. this._totalPointersPressed++;
  1769. this._pickedDownMesh = null;
  1770. this._meshPickProceed = false;
  1771. this._updatePointerPosition(evt);
  1772. if (this.preventDefaultOnPointerDown && canvas) {
  1773. evt.preventDefault();
  1774. canvas.focus();
  1775. }
  1776. this._startingPointerPosition.x = this._pointerX;
  1777. this._startingPointerPosition.y = this._pointerY;
  1778. this._startingPointerTime = Date.now();
  1779. // PreObservable support
  1780. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)) {
  1781. return;
  1782. }
  1783. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1784. return;
  1785. }
  1786. this._pointerCaptures[evt.pointerId] = true;
  1787. if (!this.pointerDownPredicate) {
  1788. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1789. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1790. };
  1791. }
  1792. // Meshes
  1793. this._pickedDownMesh = null;
  1794. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1795. this._processPointerDown(pickResult, evt);
  1796. };
  1797. this._onPointerUp = (evt: PointerEvent) => {
  1798. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1799. return; // So we need to test it the pointer down was pressed before.
  1800. }
  1801. this._totalPointersPressed--;
  1802. this._pickedUpMesh = null;
  1803. this._meshPickProceed = false;
  1804. this._updatePointerPosition(evt);
  1805. if (this.preventDefaultOnPointerUp && canvas) {
  1806. evt.preventDefault();
  1807. canvas.focus();
  1808. }
  1809. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1810. this._pointerCaptures[evt.pointerId] = false;
  1811. // PreObservable support
  1812. if (this.onPrePointerObservable.hasObservers()) {
  1813. if (!clickInfo.ignore) {
  1814. if (!clickInfo.hasSwiped) {
  1815. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1816. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)) {
  1817. return;
  1818. }
  1819. }
  1820. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1821. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)) {
  1822. return;
  1823. }
  1824. }
  1825. }
  1826. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) {
  1827. return;
  1828. }
  1829. }
  1830. }
  1831. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1832. return;
  1833. }
  1834. if (!this.pointerUpPredicate) {
  1835. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1836. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1837. };
  1838. }
  1839. // Meshes
  1840. if (!this._meshPickProceed && (ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1841. this._initActionManager(null, clickInfo);
  1842. }
  1843. if (!pickResult) {
  1844. pickResult = this._currentPickResult;
  1845. }
  1846. this._processPointerUp(pickResult, evt, clickInfo);
  1847. this._previousPickResult = this._currentPickResult;
  1848. });
  1849. };
  1850. this._onKeyDown = (evt: KeyboardEvent) => {
  1851. let type = KeyboardEventTypes.KEYDOWN;
  1852. if (this.onPreKeyboardObservable.hasObservers()) {
  1853. let pi = new KeyboardInfoPre(type, evt);
  1854. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1855. if (pi.skipOnPointerObservable) {
  1856. return;
  1857. }
  1858. }
  1859. if (this.onKeyboardObservable.hasObservers()) {
  1860. let pi = new KeyboardInfo(type, evt);
  1861. this.onKeyboardObservable.notifyObservers(pi, type);
  1862. }
  1863. if (this.actionManager) {
  1864. this.actionManager.processTrigger(Constants.ACTION_OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1865. }
  1866. };
  1867. this._onKeyUp = (evt: KeyboardEvent) => {
  1868. let type = KeyboardEventTypes.KEYUP;
  1869. if (this.onPreKeyboardObservable.hasObservers()) {
  1870. let pi = new KeyboardInfoPre(type, evt);
  1871. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1872. if (pi.skipOnPointerObservable) {
  1873. return;
  1874. }
  1875. }
  1876. if (this.onKeyboardObservable.hasObservers()) {
  1877. let pi = new KeyboardInfo(type, evt);
  1878. this.onKeyboardObservable.notifyObservers(pi, type);
  1879. }
  1880. if (this.actionManager) {
  1881. this.actionManager.processTrigger(Constants.ACTION_OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1882. }
  1883. };
  1884. let engine = this.getEngine();
  1885. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(() => {
  1886. if (!canvas) {
  1887. return;
  1888. }
  1889. canvas.addEventListener("keydown", this._onKeyDown, false);
  1890. canvas.addEventListener("keyup", this._onKeyUp, false);
  1891. });
  1892. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(() => {
  1893. if (!canvas) {
  1894. return;
  1895. }
  1896. canvas.removeEventListener("keydown", this._onKeyDown);
  1897. canvas.removeEventListener("keyup", this._onKeyUp);
  1898. });
  1899. var eventPrefix = Tools.GetPointerPrefix();
  1900. var canvas = this._engine.getRenderingCanvas();
  1901. if (!canvas) {
  1902. return;
  1903. }
  1904. if (attachMove) {
  1905. canvas.addEventListener(eventPrefix + "move", <any>this._onPointerMove, false);
  1906. // Wheel
  1907. this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  1908. (<any>document).onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  1909. "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  1910. canvas.addEventListener(this._wheelEventName, <any>this._onPointerMove, false);
  1911. }
  1912. if (attachDown) {
  1913. canvas.addEventListener(eventPrefix + "down", <any>this._onPointerDown, false);
  1914. }
  1915. if (attachUp) {
  1916. window.addEventListener(eventPrefix + "up", <any>this._onPointerUp, false);
  1917. }
  1918. canvas.tabIndex = 1;
  1919. }
  1920. /** Detaches all event handlers*/
  1921. public detachControl() {
  1922. let engine = this.getEngine();
  1923. var eventPrefix = Tools.GetPointerPrefix();
  1924. var canvas = engine.getRenderingCanvas();
  1925. if (!canvas) {
  1926. return;
  1927. }
  1928. canvas.removeEventListener(eventPrefix + "move", <any>this._onPointerMove);
  1929. canvas.removeEventListener(eventPrefix + "down", <any>this._onPointerDown);
  1930. window.removeEventListener(eventPrefix + "up", <any>this._onPointerUp);
  1931. if (this._onCanvasBlurObserver) {
  1932. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1933. }
  1934. if (this._onCanvasFocusObserver) {
  1935. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1936. }
  1937. // Wheel
  1938. canvas.removeEventListener(this._wheelEventName, <any>this._onPointerMove);
  1939. // Keyboard
  1940. canvas.removeEventListener("keydown", this._onKeyDown);
  1941. canvas.removeEventListener("keyup", this._onKeyUp);
  1942. // Observables
  1943. this.onKeyboardObservable.clear();
  1944. this.onPreKeyboardObservable.clear();
  1945. this.onPointerObservable.clear();
  1946. this.onPrePointerObservable.clear();
  1947. }
  1948. /**
  1949. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  1950. * Delay loaded resources are not taking in account
  1951. * @return true if all required resources are ready
  1952. */
  1953. public isReady(): boolean {
  1954. if (this._isDisposed) {
  1955. return false;
  1956. }
  1957. let index: number;
  1958. let engine = this.getEngine();
  1959. // Effects
  1960. if (!engine.areAllEffectsReady()) {
  1961. return false;
  1962. }
  1963. // Pending data
  1964. if (this._pendingData.length > 0) {
  1965. return false;
  1966. }
  1967. // Meshes
  1968. for (index = 0; index < this.meshes.length; index++) {
  1969. var mesh = this.meshes[index];
  1970. if (!mesh.isEnabled()) {
  1971. continue;
  1972. }
  1973. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1974. continue;
  1975. }
  1976. if (!mesh.isReady(true)) {
  1977. return false;
  1978. }
  1979. let hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || mesh.getClassName() === "InstancedLinesMesh" || engine.getCaps().instancedArrays && (<Mesh>mesh).instances.length > 0;
  1980. // Is Ready For Mesh
  1981. for (let step of this._isReadyForMeshStage) {
  1982. if (!step.action(mesh, hardwareInstancedRendering)) {
  1983. return false;
  1984. }
  1985. }
  1986. }
  1987. // Geometries
  1988. for (index = 0; index < this.geometries.length; index++) {
  1989. var geometry = this.geometries[index];
  1990. if (geometry.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
  1991. return false;
  1992. }
  1993. }
  1994. // Post-processes
  1995. if (this.activeCameras && this.activeCameras.length > 0) {
  1996. for (var camera of this.activeCameras) {
  1997. if (!camera.isReady(true)) {
  1998. return false;
  1999. }
  2000. }
  2001. } else if (this.activeCamera) {
  2002. if (!this.activeCamera.isReady(true)) {
  2003. return false;
  2004. }
  2005. }
  2006. // Particles
  2007. for (var particleSystem of this.particleSystems) {
  2008. if (!particleSystem.isReady()) {
  2009. return false;
  2010. }
  2011. }
  2012. return true;
  2013. }
  2014. /** Resets all cached information relative to material (including effect and visibility) */
  2015. public resetCachedMaterial(): void {
  2016. this._cachedMaterial = null;
  2017. this._cachedEffect = null;
  2018. this._cachedVisibility = null;
  2019. }
  2020. /**
  2021. * Registers a function to be called before every frame render
  2022. * @param func defines the function to register
  2023. */
  2024. public registerBeforeRender(func: () => void): void {
  2025. this.onBeforeRenderObservable.add(func);
  2026. }
  2027. /**
  2028. * Unregisters a function called before every frame render
  2029. * @param func defines the function to unregister
  2030. */
  2031. public unregisterBeforeRender(func: () => void): void {
  2032. this.onBeforeRenderObservable.removeCallback(func);
  2033. }
  2034. /**
  2035. * Registers a function to be called after every frame render
  2036. * @param func defines the function to register
  2037. */
  2038. public registerAfterRender(func: () => void): void {
  2039. this.onAfterRenderObservable.add(func);
  2040. }
  2041. /**
  2042. * Unregisters a function called after every frame render
  2043. * @param func defines the function to unregister
  2044. */
  2045. public unregisterAfterRender(func: () => void): void {
  2046. this.onAfterRenderObservable.removeCallback(func);
  2047. }
  2048. private _executeOnceBeforeRender(func: () => void): void {
  2049. let execFunc = () => {
  2050. func();
  2051. setTimeout(() => {
  2052. this.unregisterBeforeRender(execFunc);
  2053. });
  2054. };
  2055. this.registerBeforeRender(execFunc);
  2056. }
  2057. /**
  2058. * The provided function will run before render once and will be disposed afterwards.
  2059. * A timeout delay can be provided so that the function will be executed in N ms.
  2060. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  2061. * @param func The function to be executed.
  2062. * @param timeout optional delay in ms
  2063. */
  2064. public executeOnceBeforeRender(func: () => void, timeout?: number): void {
  2065. if (timeout !== undefined) {
  2066. setTimeout(() => {
  2067. this._executeOnceBeforeRender(func);
  2068. }, timeout);
  2069. } else {
  2070. this._executeOnceBeforeRender(func);
  2071. }
  2072. }
  2073. /** @hidden */
  2074. public _addPendingData(data: any): void {
  2075. this._pendingData.push(data);
  2076. }
  2077. /** @hidden */
  2078. public _removePendingData(data: any): void {
  2079. var wasLoading = this.isLoading;
  2080. var index = this._pendingData.indexOf(data);
  2081. if (index !== -1) {
  2082. this._pendingData.splice(index, 1);
  2083. }
  2084. if (wasLoading && !this.isLoading) {
  2085. this.onDataLoadedObservable.notifyObservers(this);
  2086. }
  2087. }
  2088. /**
  2089. * Returns the number of items waiting to be loaded
  2090. * @returns the number of items waiting to be loaded
  2091. */
  2092. public getWaitingItemsCount(): number {
  2093. return this._pendingData.length;
  2094. }
  2095. /**
  2096. * Returns a boolean indicating if the scene is still loading data
  2097. */
  2098. public get isLoading(): boolean {
  2099. return this._pendingData.length > 0;
  2100. }
  2101. /**
  2102. * Registers a function to be executed when the scene is ready
  2103. * @param {Function} func - the function to be executed
  2104. */
  2105. public executeWhenReady(func: () => void): void {
  2106. this.onReadyObservable.add(func);
  2107. if (this._executeWhenReadyTimeoutId !== -1) {
  2108. return;
  2109. }
  2110. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2111. this._checkIsReady();
  2112. }, 150);
  2113. }
  2114. /**
  2115. * Returns a promise that resolves when the scene is ready
  2116. * @returns A promise that resolves when the scene is ready
  2117. */
  2118. public whenReadyAsync(): Promise<void> {
  2119. return new Promise((resolve) => {
  2120. this.executeWhenReady(() => {
  2121. resolve();
  2122. });
  2123. });
  2124. }
  2125. /** @hidden */
  2126. public _checkIsReady() {
  2127. this._registerTransientComponents();
  2128. if (this.isReady()) {
  2129. this.onReadyObservable.notifyObservers(this);
  2130. this.onReadyObservable.clear();
  2131. this._executeWhenReadyTimeoutId = -1;
  2132. return;
  2133. }
  2134. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2135. this._checkIsReady();
  2136. }, 150);
  2137. }
  2138. // Animations
  2139. /**
  2140. * Will start the animation sequence of a given target
  2141. * @param target defines the target
  2142. * @param from defines from which frame should animation start
  2143. * @param to defines until which frame should animation run.
  2144. * @param weight defines the weight to apply to the animation (1.0 by default)
  2145. * @param loop defines if the animation loops
  2146. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2147. * @param onAnimationEnd defines the function to be executed when the animation ends
  2148. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2149. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  2150. * @param onAnimationLoop defines the callback to call when an animation loops
  2151. * @returns the animatable object created for this animation
  2152. */
  2153. public beginWeightedAnimation(target: any, from: number, to: number, weight = 1.0, loop?: boolean, speedRatio: number = 1.0,
  2154. onAnimationEnd?: () => void, animatable?: Animatable, targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable {
  2155. let returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop);
  2156. returnedAnimatable.weight = weight;
  2157. return returnedAnimatable;
  2158. }
  2159. /**
  2160. * Will start the animation sequence of a given target
  2161. * @param target defines the target
  2162. * @param from defines from which frame should animation start
  2163. * @param to defines until which frame should animation run.
  2164. * @param loop defines if the animation loops
  2165. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2166. * @param onAnimationEnd defines the function to be executed when the animation ends
  2167. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2168. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  2169. * @param targetMask defines if the target should be animate if animations are present (this is called recursively on descendant animatables regardless of return value)
  2170. * @param onAnimationLoop defines the callback to call when an animation loops
  2171. * @returns the animatable object created for this animation
  2172. */
  2173. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0,
  2174. onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent = true,
  2175. targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable {
  2176. if (from > to && speedRatio > 0) {
  2177. speedRatio *= -1;
  2178. }
  2179. if (stopCurrent) {
  2180. this.stopAnimation(target, undefined, targetMask);
  2181. }
  2182. if (!animatable) {
  2183. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop);
  2184. }
  2185. const shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  2186. // Local animations
  2187. if (target.animations && shouldRunTargetAnimations) {
  2188. animatable.appendAnimations(target, target.animations);
  2189. }
  2190. // Children animations
  2191. if (target.getAnimatables) {
  2192. var animatables = target.getAnimatables();
  2193. for (var index = 0; index < animatables.length; index++) {
  2194. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop);
  2195. }
  2196. }
  2197. animatable.reset();
  2198. return animatable;
  2199. }
  2200. /**
  2201. * Will start the animation sequence of a given target and its hierarchy
  2202. * @param target defines the target
  2203. * @param 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.
  2204. * @param from defines from which frame should animation start
  2205. * @param to defines until which frame should animation run.
  2206. * @param loop defines if the animation loops
  2207. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2208. * @param onAnimationEnd defines the function to be executed when the animation ends
  2209. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2210. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  2211. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  2212. * @param onAnimationLoop defines the callback to call when an animation loops
  2213. * @returns the list of created animatables
  2214. */
  2215. public beginHierarchyAnimation(target: any, directDescendantsOnly: boolean, from: number, to: number, loop?: boolean, speedRatio: number = 1.0,
  2216. onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent = true,
  2217. targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable[] {
  2218. let children = target.getDescendants(directDescendantsOnly);
  2219. let result = [];
  2220. result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask));
  2221. for (var child of children) {
  2222. result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask));
  2223. }
  2224. return result;
  2225. }
  2226. /**
  2227. * Begin a new animation on a given node
  2228. * @param target defines the target where the animation will take place
  2229. * @param animations defines the list of animations to start
  2230. * @param from defines the initial value
  2231. * @param to defines the final value
  2232. * @param loop defines if you want animation to loop (off by default)
  2233. * @param speedRatio defines the speed ratio to apply to all animations
  2234. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  2235. * @param onAnimationLoop defines the callback to call when an animation loops
  2236. * @returns the list of created animatables
  2237. */
  2238. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, onAnimationLoop?: () => void): Animatable {
  2239. if (speedRatio === undefined) {
  2240. speedRatio = 1.0;
  2241. }
  2242. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop);
  2243. return animatable;
  2244. }
  2245. /**
  2246. * Begin a new animation on a given node and its hierarchy
  2247. * @param target defines the root node where the animation will take place
  2248. * @param 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.
  2249. * @param animations defines the list of animations to start
  2250. * @param from defines the initial value
  2251. * @param to defines the final value
  2252. * @param loop defines if you want animation to loop (off by default)
  2253. * @param speedRatio defines the speed ratio to apply to all animations
  2254. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  2255. * @param onAnimationLoop defines the callback to call when an animation loops
  2256. * @returns the list of animatables created for all nodes
  2257. */
  2258. public beginDirectHierarchyAnimation(target: Node, directDescendantsOnly: boolean, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, onAnimationLoop?: () => void): Animatable[] {
  2259. let children = target.getDescendants(directDescendantsOnly);
  2260. let result = [];
  2261. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop));
  2262. for (var child of children) {
  2263. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop));
  2264. }
  2265. return result;
  2266. }
  2267. /**
  2268. * Gets the animatable associated with a specific target
  2269. * @param target defines the target of the animatable
  2270. * @returns the required animatable if found
  2271. */
  2272. public getAnimatableByTarget(target: any): Nullable<Animatable> {
  2273. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2274. if (this._activeAnimatables[index].target === target) {
  2275. return this._activeAnimatables[index];
  2276. }
  2277. }
  2278. return null;
  2279. }
  2280. /**
  2281. * Gets all animatables associated with a given target
  2282. * @param target defines the target to look animatables for
  2283. * @returns an array of Animatables
  2284. */
  2285. public getAllAnimatablesByTarget(target: any): Array<Animatable> {
  2286. let result = [];
  2287. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2288. if (this._activeAnimatables[index].target === target) {
  2289. result.push(this._activeAnimatables[index]);
  2290. }
  2291. }
  2292. return result;
  2293. }
  2294. /**
  2295. * Gets all animatable attached to the scene
  2296. */
  2297. public get animatables(): Animatable[] {
  2298. return this._activeAnimatables;
  2299. }
  2300. /**
  2301. * Will stop the animation of the given target
  2302. * @param target - the target
  2303. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  2304. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  2305. */
  2306. public stopAnimation(target: any, animationName?: string, targetMask?: (target: any) => boolean): void {
  2307. var animatables = this.getAllAnimatablesByTarget(target);
  2308. for (var animatable of animatables) {
  2309. animatable.stop(animationName, targetMask);
  2310. }
  2311. }
  2312. /**
  2313. * Stops and removes all animations that have been applied to the scene
  2314. */
  2315. public stopAllAnimations(): void {
  2316. if (this._activeAnimatables) {
  2317. for (let i = 0; i < this._activeAnimatables.length; i++) {
  2318. this._activeAnimatables[i].stop();
  2319. }
  2320. this._activeAnimatables = [];
  2321. }
  2322. for (var group of this.animationGroups) {
  2323. group.stop();
  2324. }
  2325. }
  2326. /**
  2327. * Resets the last animation time frame.
  2328. * Useful to override when animations start running when loading a scene for the first time.
  2329. */
  2330. public resetLastAnimationTimeFrame(): void {
  2331. this._animationTimeLast = PrecisionDate.Now;
  2332. }
  2333. private _animate(): void {
  2334. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  2335. return;
  2336. }
  2337. // Getting time
  2338. var now = PrecisionDate.Now;
  2339. if (!this._animationTimeLast) {
  2340. if (this._pendingData.length > 0) {
  2341. return;
  2342. }
  2343. this._animationTimeLast = now;
  2344. }
  2345. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  2346. this._animationTime += deltaTime;
  2347. this._animationTimeLast = now;
  2348. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2349. this._activeAnimatables[index]._animate(this._animationTime);
  2350. }
  2351. // Late animation bindings
  2352. this._processLateAnimationBindings();
  2353. }
  2354. /** @hidden */
  2355. public _registerTargetForLateAnimationBinding(runtimeAnimation: RuntimeAnimation, originalValue: any): void {
  2356. let target = runtimeAnimation.target;
  2357. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  2358. if (!target._lateAnimationHolders) {
  2359. target._lateAnimationHolders = {};
  2360. }
  2361. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  2362. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  2363. totalWeight: 0,
  2364. animations: [],
  2365. originalValue: originalValue
  2366. };
  2367. }
  2368. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  2369. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  2370. }
  2371. private _processLateAnimationBindingsForMatrices(holder: {
  2372. totalWeight: number,
  2373. animations: RuntimeAnimation[],
  2374. originalValue: Matrix
  2375. }): any {
  2376. let normalizer = 1.0;
  2377. let finalPosition = Tmp.Vector3[0];
  2378. let finalScaling = Tmp.Vector3[1];
  2379. let finalQuaternion = Tmp.Quaternion[0];
  2380. let startIndex = 0;
  2381. let originalAnimation = holder.animations[0];
  2382. let originalValue = holder.originalValue;
  2383. var scale = 1;
  2384. if (holder.totalWeight < 1.0) {
  2385. // We need to mix the original value in
  2386. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  2387. scale = 1.0 - holder.totalWeight;
  2388. } else {
  2389. startIndex = 1;
  2390. // We need to normalize the weights
  2391. normalizer = holder.totalWeight;
  2392. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  2393. scale = originalAnimation.weight / normalizer;
  2394. if (scale == 1) {
  2395. return originalAnimation.currentValue;
  2396. }
  2397. }
  2398. finalScaling.scaleInPlace(scale);
  2399. finalPosition.scaleInPlace(scale);
  2400. finalQuaternion.scaleInPlace(scale);
  2401. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  2402. var runtimeAnimation = holder.animations[animIndex];
  2403. var scale = runtimeAnimation.weight / normalizer;
  2404. let currentPosition = Tmp.Vector3[2];
  2405. let currentScaling = Tmp.Vector3[3];
  2406. let currentQuaternion = Tmp.Quaternion[1];
  2407. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  2408. currentScaling.scaleAndAddToRef(scale, finalScaling);
  2409. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  2410. currentPosition.scaleAndAddToRef(scale, finalPosition);
  2411. }
  2412. Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  2413. return originalAnimation._workValue;
  2414. }
  2415. private _processLateAnimationBindingsForQuaternions(holder: {
  2416. totalWeight: number,
  2417. animations: RuntimeAnimation[],
  2418. originalValue: Quaternion
  2419. }, refQuaternion: Quaternion): Quaternion {
  2420. let originalAnimation = holder.animations[0];
  2421. let originalValue = holder.originalValue;
  2422. if (holder.animations.length === 1) {
  2423. Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  2424. return refQuaternion;
  2425. }
  2426. let normalizer = 1.0;
  2427. let quaternions: Array<Quaternion>;
  2428. let weights: Array<number>;
  2429. if (holder.totalWeight < 1.0) {
  2430. let scale = 1.0 - holder.totalWeight;
  2431. quaternions = [];
  2432. weights = [];
  2433. quaternions.push(originalValue);
  2434. weights.push(scale);
  2435. } else {
  2436. if (holder.animations.length === 2) { // Slerp as soon as we can
  2437. Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  2438. return refQuaternion;
  2439. }
  2440. quaternions = [];
  2441. weights = [];
  2442. normalizer = holder.totalWeight;
  2443. }
  2444. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  2445. let runtimeAnimation = holder.animations[animIndex];
  2446. quaternions.push(runtimeAnimation.currentValue);
  2447. weights.push(runtimeAnimation.weight / normalizer);
  2448. }
  2449. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  2450. let cumulativeAmount = 0;
  2451. let cumulativeQuaternion: Nullable<Quaternion> = null;
  2452. for (var index = 0; index < quaternions.length;) {
  2453. if (!cumulativeQuaternion) {
  2454. Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  2455. cumulativeQuaternion = refQuaternion;
  2456. cumulativeAmount = weights[index] + weights[index + 1];
  2457. index += 2;
  2458. continue;
  2459. }
  2460. cumulativeAmount += weights[index];
  2461. Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  2462. index++;
  2463. }
  2464. return cumulativeQuaternion!;
  2465. }
  2466. private _processLateAnimationBindings(): void {
  2467. if (!this._registeredForLateAnimationBindings.length) {
  2468. return;
  2469. }
  2470. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  2471. var target = this._registeredForLateAnimationBindings.data[index];
  2472. for (var path in target._lateAnimationHolders) {
  2473. var holder = target._lateAnimationHolders[path];
  2474. let originalAnimation: RuntimeAnimation = holder.animations[0];
  2475. let originalValue = holder.originalValue;
  2476. let matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  2477. let finalValue: any = target[path];
  2478. if (matrixDecomposeMode) {
  2479. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  2480. } else {
  2481. let quaternionMode = originalValue.w !== undefined;
  2482. if (quaternionMode) {
  2483. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || Quaternion.Identity());
  2484. } else {
  2485. let startIndex = 0;
  2486. let normalizer = 1.0;
  2487. if (holder.totalWeight < 1.0) {
  2488. // We need to mix the original value in
  2489. if (originalValue.scale) {
  2490. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  2491. } else {
  2492. finalValue = originalValue * (1.0 - holder.totalWeight);
  2493. }
  2494. } else {
  2495. // We need to normalize the weights
  2496. normalizer = holder.totalWeight;
  2497. let scale = originalAnimation.weight / normalizer;
  2498. if (scale !== 1) {
  2499. if (originalAnimation.currentValue.scale) {
  2500. finalValue = originalAnimation.currentValue.scale(scale);
  2501. } else {
  2502. finalValue = originalAnimation.currentValue * scale;
  2503. }
  2504. } else {
  2505. finalValue = originalAnimation.currentValue;
  2506. }
  2507. startIndex = 1;
  2508. }
  2509. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  2510. var runtimeAnimation = holder.animations[animIndex];
  2511. var scale = runtimeAnimation.weight / normalizer;
  2512. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  2513. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  2514. } else {
  2515. finalValue += runtimeAnimation.currentValue * scale;
  2516. }
  2517. }
  2518. }
  2519. }
  2520. target[path] = finalValue;
  2521. }
  2522. target._lateAnimationHolders = {};
  2523. }
  2524. this._registeredForLateAnimationBindings.reset();
  2525. }
  2526. // Matrix
  2527. /** @hidden */
  2528. public _switchToAlternateCameraConfiguration(active: boolean): void {
  2529. this._useAlternateCameraConfiguration = active;
  2530. }
  2531. /**
  2532. * Gets the current view matrix
  2533. * @returns a Matrix
  2534. */
  2535. public getViewMatrix(): Matrix {
  2536. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  2537. }
  2538. /**
  2539. * Gets the current projection matrix
  2540. * @returns a Matrix
  2541. */
  2542. public getProjectionMatrix(): Matrix {
  2543. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  2544. }
  2545. /**
  2546. * Gets the current transform matrix
  2547. * @returns a Matrix made of View * Projection
  2548. */
  2549. public getTransformMatrix(): Matrix {
  2550. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  2551. }
  2552. /**
  2553. * Sets the current transform matrix
  2554. * @param view defines the View matrix to use
  2555. * @param projection defines the Projection matrix to use
  2556. */
  2557. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  2558. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  2559. return;
  2560. }
  2561. this._viewUpdateFlag = view.updateFlag;
  2562. this._projectionUpdateFlag = projection.updateFlag;
  2563. this._viewMatrix = view;
  2564. this._projectionMatrix = projection;
  2565. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  2566. // Update frustum
  2567. if (!this._frustumPlanes) {
  2568. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  2569. } else {
  2570. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  2571. }
  2572. if (this.activeCamera && this.activeCamera._alternateCamera) {
  2573. let otherCamera = this.activeCamera._alternateCamera;
  2574. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  2575. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  2576. }
  2577. if (this._sceneUbo.useUbo) {
  2578. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  2579. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  2580. this._sceneUbo.update();
  2581. }
  2582. }
  2583. /** @hidden */
  2584. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  2585. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  2586. return;
  2587. }
  2588. this._alternateViewUpdateFlag = view.updateFlag;
  2589. this._alternateProjectionUpdateFlag = projection.updateFlag;
  2590. this._alternateViewMatrix = view;
  2591. this._alternateProjectionMatrix = projection;
  2592. if (!this._alternateTransformMatrix) {
  2593. this._alternateTransformMatrix = Matrix.Zero();
  2594. }
  2595. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  2596. if (!this._alternateSceneUbo) {
  2597. this._createAlternateUbo();
  2598. }
  2599. if (this._alternateSceneUbo.useUbo) {
  2600. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  2601. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  2602. this._alternateSceneUbo.update();
  2603. }
  2604. }
  2605. /**
  2606. * Gets the uniform buffer used to store scene data
  2607. * @returns a UniformBuffer
  2608. */
  2609. public getSceneUniformBuffer(): UniformBuffer {
  2610. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  2611. }
  2612. /**
  2613. * Gets an unique (relatively to the current scene) Id
  2614. * @returns an unique number for the scene
  2615. */
  2616. public getUniqueId() {
  2617. var result = Scene._uniqueIdCounter;
  2618. Scene._uniqueIdCounter++;
  2619. return result;
  2620. }
  2621. /**
  2622. * Add a mesh to the list of scene's meshes
  2623. * @param newMesh defines the mesh to add
  2624. * @param recursive if all child meshes should also be added to the scene
  2625. */
  2626. public addMesh(newMesh: AbstractMesh, recursive = false) {
  2627. this.meshes.push(newMesh);
  2628. //notify the collision coordinator
  2629. if (this.collisionCoordinator) {
  2630. this.collisionCoordinator.onMeshAdded(newMesh);
  2631. }
  2632. newMesh._resyncLightSources();
  2633. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  2634. if (recursive) {
  2635. newMesh.getChildMeshes().forEach((m) => {
  2636. this.addMesh(m);
  2637. });
  2638. }
  2639. }
  2640. /**
  2641. * Remove a mesh for the list of scene's meshes
  2642. * @param toRemove defines the mesh to remove
  2643. * @param recursive if all child meshes should also be removed from the scene
  2644. * @returns the index where the mesh was in the mesh list
  2645. */
  2646. public removeMesh(toRemove: AbstractMesh, recursive = false): number {
  2647. var index = this.meshes.indexOf(toRemove);
  2648. if (index !== -1) {
  2649. // Remove from the scene if mesh found
  2650. this.meshes[index] = this.meshes[this.meshes.length - 1];
  2651. this.meshes.pop();
  2652. }
  2653. this.onMeshRemovedObservable.notifyObservers(toRemove);
  2654. if (recursive) {
  2655. toRemove.getChildMeshes().forEach((m) => {
  2656. this.removeMesh(m);
  2657. });
  2658. }
  2659. return index;
  2660. }
  2661. /**
  2662. * Add a transform node to the list of scene's transform nodes
  2663. * @param newTransformNode defines the transform node to add
  2664. */
  2665. public addTransformNode(newTransformNode: TransformNode) {
  2666. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  2667. this.transformNodes.push(newTransformNode);
  2668. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  2669. }
  2670. /**
  2671. * Remove a transform node for the list of scene's transform nodes
  2672. * @param toRemove defines the transform node to remove
  2673. * @returns the index where the transform node was in the transform node list
  2674. */
  2675. public removeTransformNode(toRemove: TransformNode): number {
  2676. var index = toRemove._indexInSceneTransformNodesArray;
  2677. if (index !== -1) {
  2678. if (index !== this.transformNodes.length - 1) {
  2679. const lastNode = this.transformNodes[this.transformNodes.length - 1];
  2680. this.transformNodes[index] = lastNode;
  2681. lastNode._indexInSceneTransformNodesArray = index;
  2682. }
  2683. toRemove._indexInSceneTransformNodesArray = -1;
  2684. this.transformNodes.pop();
  2685. }
  2686. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  2687. return index;
  2688. }
  2689. /**
  2690. * Remove a skeleton for the list of scene's skeletons
  2691. * @param toRemove defines the skeleton to remove
  2692. * @returns the index where the skeleton was in the skeleton list
  2693. */
  2694. public removeSkeleton(toRemove: Skeleton): number {
  2695. var index = this.skeletons.indexOf(toRemove);
  2696. if (index !== -1) {
  2697. // Remove from the scene if found
  2698. this.skeletons.splice(index, 1);
  2699. }
  2700. return index;
  2701. }
  2702. /**
  2703. * Remove a morph target for the list of scene's morph targets
  2704. * @param toRemove defines the morph target to remove
  2705. * @returns the index where the morph target was in the morph target list
  2706. */
  2707. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  2708. var index = this.morphTargetManagers.indexOf(toRemove);
  2709. if (index !== -1) {
  2710. // Remove from the scene if found
  2711. this.morphTargetManagers.splice(index, 1);
  2712. }
  2713. return index;
  2714. }
  2715. /**
  2716. * Remove a light for the list of scene's lights
  2717. * @param toRemove defines the light to remove
  2718. * @returns the index where the light was in the light list
  2719. */
  2720. public removeLight(toRemove: Light): number {
  2721. var index = this.lights.indexOf(toRemove);
  2722. if (index !== -1) {
  2723. // Remove from meshes
  2724. for (var mesh of this.meshes) {
  2725. mesh._removeLightSource(toRemove);
  2726. }
  2727. // Remove from the scene if mesh found
  2728. this.lights.splice(index, 1);
  2729. this.sortLightsByPriority();
  2730. }
  2731. this.onLightRemovedObservable.notifyObservers(toRemove);
  2732. return index;
  2733. }
  2734. /**
  2735. * Remove a camera for the list of scene's cameras
  2736. * @param toRemove defines the camera to remove
  2737. * @returns the index where the camera was in the camera list
  2738. */
  2739. public removeCamera(toRemove: Camera): number {
  2740. var index = this.cameras.indexOf(toRemove);
  2741. if (index !== -1) {
  2742. // Remove from the scene if mesh found
  2743. this.cameras.splice(index, 1);
  2744. }
  2745. // Remove from activeCameras
  2746. var index2 = this.activeCameras.indexOf(toRemove);
  2747. if (index2 !== -1) {
  2748. // Remove from the scene if mesh found
  2749. this.activeCameras.splice(index2, 1);
  2750. }
  2751. // Reset the activeCamera
  2752. if (this.activeCamera === toRemove) {
  2753. if (this.cameras.length > 0) {
  2754. this.activeCamera = this.cameras[0];
  2755. } else {
  2756. this.activeCamera = null;
  2757. }
  2758. }
  2759. this.onCameraRemovedObservable.notifyObservers(toRemove);
  2760. return index;
  2761. }
  2762. /**
  2763. * Remove a particle system for the list of scene's particle systems
  2764. * @param toRemove defines the particle system to remove
  2765. * @returns the index where the particle system was in the particle system list
  2766. */
  2767. public removeParticleSystem(toRemove: IParticleSystem): number {
  2768. var index = this.particleSystems.indexOf(toRemove);
  2769. if (index !== -1) {
  2770. this.particleSystems.splice(index, 1);
  2771. }
  2772. return index;
  2773. }
  2774. /**
  2775. * Remove a animation for the list of scene's animations
  2776. * @param toRemove defines the animation to remove
  2777. * @returns the index where the animation was in the animation list
  2778. */
  2779. public removeAnimation(toRemove: Animation): number {
  2780. var index = this.animations.indexOf(toRemove);
  2781. if (index !== -1) {
  2782. this.animations.splice(index, 1);
  2783. }
  2784. return index;
  2785. }
  2786. /**
  2787. * Removes the given animation group from this scene.
  2788. * @param toRemove The animation group to remove
  2789. * @returns The index of the removed animation group
  2790. */
  2791. public removeAnimationGroup(toRemove: AnimationGroup): number {
  2792. var index = this.animationGroups.indexOf(toRemove);
  2793. if (index !== -1) {
  2794. this.animationGroups.splice(index, 1);
  2795. }
  2796. return index;
  2797. }
  2798. /**
  2799. * Removes the given multi-material from this scene.
  2800. * @param toRemove The multi-material to remove
  2801. * @returns The index of the removed multi-material
  2802. */
  2803. public removeMultiMaterial(toRemove: MultiMaterial): number {
  2804. var index = this.multiMaterials.indexOf(toRemove);
  2805. if (index !== -1) {
  2806. this.multiMaterials.splice(index, 1);
  2807. }
  2808. return index;
  2809. }
  2810. /**
  2811. * Removes the given material from this scene.
  2812. * @param toRemove The material to remove
  2813. * @returns The index of the removed material
  2814. */
  2815. public removeMaterial(toRemove: Material): number {
  2816. var index = toRemove._indexInSceneMaterialArray;
  2817. if (index !== -1 && index < this.materials.length) {
  2818. if (index !== this.materials.length - 1) {
  2819. const lastMaterial = this.materials[this.materials.length - 1];
  2820. this.materials[index] = lastMaterial;
  2821. lastMaterial._indexInSceneMaterialArray = index;
  2822. }
  2823. toRemove._indexInSceneMaterialArray = -1;
  2824. this.materials.pop();
  2825. }
  2826. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  2827. return index;
  2828. }
  2829. /**
  2830. * Removes the given action manager from this scene.
  2831. * @param toRemove The action manager to remove
  2832. * @returns The index of the removed action manager
  2833. */
  2834. public removeActionManager(toRemove: ActionManager): number {
  2835. var index = this.actionManagers.indexOf(toRemove);
  2836. if (index !== -1) {
  2837. this.actionManagers.splice(index, 1);
  2838. }
  2839. return index;
  2840. }
  2841. /**
  2842. * Removes the given texture from this scene.
  2843. * @param toRemove The texture to remove
  2844. * @returns The index of the removed texture
  2845. */
  2846. public removeTexture(toRemove: BaseTexture): number {
  2847. var index = this.textures.indexOf(toRemove);
  2848. if (index !== -1) {
  2849. this.textures.splice(index, 1);
  2850. }
  2851. this.onTextureRemovedObservable.notifyObservers(toRemove);
  2852. return index;
  2853. }
  2854. /**
  2855. * Adds the given light to this scene
  2856. * @param newLight The light to add
  2857. */
  2858. public addLight(newLight: Light): void {
  2859. this.lights.push(newLight);
  2860. this.sortLightsByPriority();
  2861. // Add light to all meshes (To support if the light is removed and then readded)
  2862. for (var mesh of this.meshes) {
  2863. if (mesh._lightSources.indexOf(newLight) === -1) {
  2864. mesh._lightSources.push(newLight);
  2865. mesh._resyncLightSources();
  2866. }
  2867. }
  2868. this.onNewLightAddedObservable.notifyObservers(newLight);
  2869. }
  2870. /**
  2871. * Sorts the list list based on light priorities
  2872. */
  2873. public sortLightsByPriority(): void {
  2874. if (this.requireLightSorting) {
  2875. this.lights.sort(Light.CompareLightsPriority);
  2876. }
  2877. }
  2878. /**
  2879. * Adds the given camera to this scene
  2880. * @param newCamera The camera to add
  2881. */
  2882. public addCamera(newCamera: Camera): void {
  2883. this.cameras.push(newCamera);
  2884. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  2885. }
  2886. /**
  2887. * Adds the given skeleton to this scene
  2888. * @param newSkeleton The skeleton to add
  2889. */
  2890. public addSkeleton(newSkeleton: Skeleton): void {
  2891. this.skeletons.push(newSkeleton);
  2892. }
  2893. /**
  2894. * Adds the given particle system to this scene
  2895. * @param newParticleSystem The particle system to add
  2896. */
  2897. public addParticleSystem(newParticleSystem: IParticleSystem): void {
  2898. this.particleSystems.push(newParticleSystem);
  2899. }
  2900. /**
  2901. * Adds the given animation to this scene
  2902. * @param newAnimation The animation to add
  2903. */
  2904. public addAnimation(newAnimation: Animation): void {
  2905. this.animations.push(newAnimation);
  2906. }
  2907. /**
  2908. * Adds the given animation group to this scene.
  2909. * @param newAnimationGroup The animation group to add
  2910. */
  2911. public addAnimationGroup(newAnimationGroup: AnimationGroup): void {
  2912. this.animationGroups.push(newAnimationGroup);
  2913. }
  2914. /**
  2915. * Adds the given multi-material to this scene
  2916. * @param newMultiMaterial The multi-material to add
  2917. */
  2918. public addMultiMaterial(newMultiMaterial: MultiMaterial): void {
  2919. this.multiMaterials.push(newMultiMaterial);
  2920. }
  2921. /**
  2922. * Adds the given material to this scene
  2923. * @param newMaterial The material to add
  2924. */
  2925. public addMaterial(newMaterial: Material): void {
  2926. newMaterial._indexInSceneMaterialArray = this.materials.length;
  2927. this.materials.push(newMaterial);
  2928. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  2929. }
  2930. /**
  2931. * Adds the given morph target to this scene
  2932. * @param newMorphTargetManager The morph target to add
  2933. */
  2934. public addMorphTargetManager(newMorphTargetManager: MorphTargetManager): void {
  2935. this.morphTargetManagers.push(newMorphTargetManager);
  2936. }
  2937. /**
  2938. * Adds the given geometry to this scene
  2939. * @param newGeometry The geometry to add
  2940. */
  2941. public addGeometry(newGeometry: Geometry): void {
  2942. if (this.geometriesByUniqueId) {
  2943. this.geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length;
  2944. }
  2945. this.geometries.push(newGeometry);
  2946. }
  2947. /**
  2948. * Adds the given action manager to this scene
  2949. * @param newActionManager The action manager to add
  2950. */
  2951. public addActionManager(newActionManager: ActionManager): void {
  2952. this.actionManagers.push(newActionManager);
  2953. }
  2954. /**
  2955. * Adds the given texture to this scene.
  2956. * @param newTexture The texture to add
  2957. */
  2958. public addTexture(newTexture: BaseTexture): void {
  2959. this.textures.push(newTexture);
  2960. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  2961. }
  2962. /**
  2963. * Switch active camera
  2964. * @param newCamera defines the new active camera
  2965. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  2966. */
  2967. public switchActiveCamera(newCamera: Camera, attachControl = true): void {
  2968. var canvas = this._engine.getRenderingCanvas();
  2969. if (!canvas) {
  2970. return;
  2971. }
  2972. if (this.activeCamera) {
  2973. this.activeCamera.detachControl(canvas);
  2974. }
  2975. this.activeCamera = newCamera;
  2976. if (attachControl) {
  2977. newCamera.attachControl(canvas);
  2978. }
  2979. }
  2980. /**
  2981. * sets the active camera of the scene using its ID
  2982. * @param id defines the camera's ID
  2983. * @return the new active camera or null if none found.
  2984. */
  2985. public setActiveCameraByID(id: string): Nullable<Camera> {
  2986. var camera = this.getCameraByID(id);
  2987. if (camera) {
  2988. this.activeCamera = camera;
  2989. return camera;
  2990. }
  2991. return null;
  2992. }
  2993. /**
  2994. * sets the active camera of the scene using its name
  2995. * @param name defines the camera's name
  2996. * @returns the new active camera or null if none found.
  2997. */
  2998. public setActiveCameraByName(name: string): Nullable<Camera> {
  2999. var camera = this.getCameraByName(name);
  3000. if (camera) {
  3001. this.activeCamera = camera;
  3002. return camera;
  3003. }
  3004. return null;
  3005. }
  3006. /**
  3007. * get an animation group using its name
  3008. * @param name defines the material's name
  3009. * @return the animation group or null if none found.
  3010. */
  3011. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  3012. for (var index = 0; index < this.animationGroups.length; index++) {
  3013. if (this.animationGroups[index].name === name) {
  3014. return this.animationGroups[index];
  3015. }
  3016. }
  3017. return null;
  3018. }
  3019. /**
  3020. * get a material using its id
  3021. * @param id defines the material's ID
  3022. * @return the material or null if none found.
  3023. */
  3024. public getMaterialByID(id: string): Nullable<Material> {
  3025. for (var index = 0; index < this.materials.length; index++) {
  3026. if (this.materials[index].id === id) {
  3027. return this.materials[index];
  3028. }
  3029. }
  3030. return null;
  3031. }
  3032. /**
  3033. * Gets a material using its name
  3034. * @param name defines the material's name
  3035. * @return the material or null if none found.
  3036. */
  3037. public getMaterialByName(name: string): Nullable<Material> {
  3038. for (var index = 0; index < this.materials.length; index++) {
  3039. if (this.materials[index].name === name) {
  3040. return this.materials[index];
  3041. }
  3042. }
  3043. return null;
  3044. }
  3045. /**
  3046. * Gets a camera using its id
  3047. * @param id defines the id to look for
  3048. * @returns the camera or null if not found
  3049. */
  3050. public getCameraByID(id: string): Nullable<Camera> {
  3051. for (var index = 0; index < this.cameras.length; index++) {
  3052. if (this.cameras[index].id === id) {
  3053. return this.cameras[index];
  3054. }
  3055. }
  3056. return null;
  3057. }
  3058. /**
  3059. * Gets a camera using its unique id
  3060. * @param uniqueId defines the unique id to look for
  3061. * @returns the camera or null if not found
  3062. */
  3063. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  3064. for (var index = 0; index < this.cameras.length; index++) {
  3065. if (this.cameras[index].uniqueId === uniqueId) {
  3066. return this.cameras[index];
  3067. }
  3068. }
  3069. return null;
  3070. }
  3071. /**
  3072. * Gets a camera using its name
  3073. * @param name defines the camera's name
  3074. * @return the camera or null if none found.
  3075. */
  3076. public getCameraByName(name: string): Nullable<Camera> {
  3077. for (var index = 0; index < this.cameras.length; index++) {
  3078. if (this.cameras[index].name === name) {
  3079. return this.cameras[index];
  3080. }
  3081. }
  3082. return null;
  3083. }
  3084. /**
  3085. * Gets a bone using its id
  3086. * @param id defines the bone's id
  3087. * @return the bone or null if not found
  3088. */
  3089. public getBoneByID(id: string): Nullable<Bone> {
  3090. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  3091. var skeleton = this.skeletons[skeletonIndex];
  3092. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  3093. if (skeleton.bones[boneIndex].id === id) {
  3094. return skeleton.bones[boneIndex];
  3095. }
  3096. }
  3097. }
  3098. return null;
  3099. }
  3100. /**
  3101. * Gets a bone using its id
  3102. * @param name defines the bone's name
  3103. * @return the bone or null if not found
  3104. */
  3105. public getBoneByName(name: string): Nullable<Bone> {
  3106. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  3107. var skeleton = this.skeletons[skeletonIndex];
  3108. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  3109. if (skeleton.bones[boneIndex].name === name) {
  3110. return skeleton.bones[boneIndex];
  3111. }
  3112. }
  3113. }
  3114. return null;
  3115. }
  3116. /**
  3117. * Gets a light node using its name
  3118. * @param name defines the the light's name
  3119. * @return the light or null if none found.
  3120. */
  3121. public getLightByName(name: string): Nullable<Light> {
  3122. for (var index = 0; index < this.lights.length; index++) {
  3123. if (this.lights[index].name === name) {
  3124. return this.lights[index];
  3125. }
  3126. }
  3127. return null;
  3128. }
  3129. /**
  3130. * Gets a light node using its id
  3131. * @param id defines the light's id
  3132. * @return the light or null if none found.
  3133. */
  3134. public getLightByID(id: string): Nullable<Light> {
  3135. for (var index = 0; index < this.lights.length; index++) {
  3136. if (this.lights[index].id === id) {
  3137. return this.lights[index];
  3138. }
  3139. }
  3140. return null;
  3141. }
  3142. /**
  3143. * Gets a light node using its scene-generated unique ID
  3144. * @param uniqueId defines the light's unique id
  3145. * @return the light or null if none found.
  3146. */
  3147. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  3148. for (var index = 0; index < this.lights.length; index++) {
  3149. if (this.lights[index].uniqueId === uniqueId) {
  3150. return this.lights[index];
  3151. }
  3152. }
  3153. return null;
  3154. }
  3155. /**
  3156. * Gets a particle system by id
  3157. * @param id defines the particle system id
  3158. * @return the corresponding system or null if none found
  3159. */
  3160. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  3161. for (var index = 0; index < this.particleSystems.length; index++) {
  3162. if (this.particleSystems[index].id === id) {
  3163. return this.particleSystems[index];
  3164. }
  3165. }
  3166. return null;
  3167. }
  3168. /**
  3169. * Gets a geometry using its ID
  3170. * @param id defines the geometry's id
  3171. * @return the geometry or null if none found.
  3172. */
  3173. public getGeometryByID(id: string): Nullable<Geometry> {
  3174. for (var index = 0; index < this.geometries.length; index++) {
  3175. if (this.geometries[index].id === id) {
  3176. return this.geometries[index];
  3177. }
  3178. }
  3179. return null;
  3180. }
  3181. private _getGeometryByUniqueID(uniqueId: number): Nullable<Geometry> {
  3182. if (this.geometriesByUniqueId) {
  3183. const index = this.geometriesByUniqueId[uniqueId];
  3184. if (index !== undefined) {
  3185. return this.geometries[index];
  3186. }
  3187. }
  3188. else {
  3189. for (var index = 0; index < this.geometries.length; index++) {
  3190. if (this.geometries[index].uniqueId === uniqueId) {
  3191. return this.geometries[index];
  3192. }
  3193. }
  3194. }
  3195. return null;
  3196. }
  3197. /**
  3198. * Add a new geometry to this scene
  3199. * @param geometry defines the geometry to be added to the scene.
  3200. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  3201. * @return a boolean defining if the geometry was added or not
  3202. */
  3203. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  3204. if (!force && this._getGeometryByUniqueID(geometry.uniqueId)) {
  3205. return false;
  3206. }
  3207. this.addGeometry(geometry);
  3208. //notify the collision coordinator
  3209. if (this.collisionCoordinator) {
  3210. this.collisionCoordinator.onGeometryAdded(geometry);
  3211. }
  3212. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  3213. return true;
  3214. }
  3215. /**
  3216. * Removes an existing geometry
  3217. * @param geometry defines the geometry to be removed from the scene
  3218. * @return a boolean defining if the geometry was removed or not
  3219. */
  3220. public removeGeometry(geometry: Geometry): boolean {
  3221. let index;
  3222. if (this.geometriesByUniqueId) {
  3223. index = this.geometriesByUniqueId[geometry.uniqueId];
  3224. if (index === undefined) {
  3225. return false;
  3226. }
  3227. }
  3228. else {
  3229. index = this.geometries.indexOf(geometry);
  3230. if (index < 0) {
  3231. return false;
  3232. }
  3233. }
  3234. if (index !== this.geometries.length - 1) {
  3235. const lastGeometry = this.geometries[this.geometries.length - 1];
  3236. this.geometries[index] = lastGeometry;
  3237. if (this.geometriesByUniqueId) {
  3238. this.geometriesByUniqueId[lastGeometry.uniqueId] = index;
  3239. this.geometriesByUniqueId[geometry.uniqueId] = undefined;
  3240. }
  3241. }
  3242. this.geometries.pop();
  3243. //notify the collision coordinator
  3244. if (this.collisionCoordinator) {
  3245. this.collisionCoordinator.onGeometryDeleted(geometry);
  3246. }
  3247. this.onGeometryRemovedObservable.notifyObservers(geometry);
  3248. return true;
  3249. }
  3250. /**
  3251. * Gets the list of geometries attached to the scene
  3252. * @returns an array of Geometry
  3253. */
  3254. public getGeometries(): Geometry[] {
  3255. return this.geometries;
  3256. }
  3257. /**
  3258. * Gets the first added mesh found of a given ID
  3259. * @param id defines the id to search for
  3260. * @return the mesh found or null if not found at all
  3261. */
  3262. public getMeshByID(id: string): Nullable<AbstractMesh> {
  3263. for (var index = 0; index < this.meshes.length; index++) {
  3264. if (this.meshes[index].id === id) {
  3265. return this.meshes[index];
  3266. }
  3267. }
  3268. return null;
  3269. }
  3270. /**
  3271. * Gets a list of meshes using their id
  3272. * @param id defines the id to search for
  3273. * @returns a list of meshes
  3274. */
  3275. public getMeshesByID(id: string): Array<AbstractMesh> {
  3276. return this.meshes.filter(function(m) {
  3277. return m.id === id;
  3278. });
  3279. }
  3280. /**
  3281. * Gets the first added transform node found of a given ID
  3282. * @param id defines the id to search for
  3283. * @return the found transform node or null if not found at all.
  3284. */
  3285. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  3286. for (var index = 0; index < this.transformNodes.length; index++) {
  3287. if (this.transformNodes[index].id === id) {
  3288. return this.transformNodes[index];
  3289. }
  3290. }
  3291. return null;
  3292. }
  3293. /**
  3294. * Gets a list of transform nodes using their id
  3295. * @param id defines the id to search for
  3296. * @returns a list of transform nodes
  3297. */
  3298. public getTransformNodesByID(id: string): Array<TransformNode> {
  3299. return this.transformNodes.filter(function(m) {
  3300. return m.id === id;
  3301. });
  3302. }
  3303. /**
  3304. * Gets a mesh with its auto-generated unique id
  3305. * @param uniqueId defines the unique id to search for
  3306. * @return the found mesh or null if not found at all.
  3307. */
  3308. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  3309. for (var index = 0; index < this.meshes.length; index++) {
  3310. if (this.meshes[index].uniqueId === uniqueId) {
  3311. return this.meshes[index];
  3312. }
  3313. }
  3314. return null;
  3315. }
  3316. /**
  3317. * Gets a the last added mesh using a given id
  3318. * @param id defines the id to search for
  3319. * @return the found mesh or null if not found at all.
  3320. */
  3321. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  3322. for (var index = this.meshes.length - 1; index >= 0; index--) {
  3323. if (this.meshes[index].id === id) {
  3324. return this.meshes[index];
  3325. }
  3326. }
  3327. return null;
  3328. }
  3329. /**
  3330. * Gets a the last added node (Mesh, Camera, Light) using a given id
  3331. * @param id defines the id to search for
  3332. * @return the found node or null if not found at all
  3333. */
  3334. public getLastEntryByID(id: string): Nullable<Node> {
  3335. var index: number;
  3336. for (index = this.meshes.length - 1; index >= 0; index--) {
  3337. if (this.meshes[index].id === id) {
  3338. return this.meshes[index];
  3339. }
  3340. }
  3341. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  3342. if (this.transformNodes[index].id === id) {
  3343. return this.transformNodes[index];
  3344. }
  3345. }
  3346. for (index = this.cameras.length - 1; index >= 0; index--) {
  3347. if (this.cameras[index].id === id) {
  3348. return this.cameras[index];
  3349. }
  3350. }
  3351. for (index = this.lights.length - 1; index >= 0; index--) {
  3352. if (this.lights[index].id === id) {
  3353. return this.lights[index];
  3354. }
  3355. }
  3356. return null;
  3357. }
  3358. /**
  3359. * Gets a node (Mesh, Camera, Light) using a given id
  3360. * @param id defines the id to search for
  3361. * @return the found node or null if not found at all
  3362. */
  3363. public getNodeByID(id: string): Nullable<Node> {
  3364. const mesh = this.getMeshByID(id);
  3365. if (mesh) {
  3366. return mesh;
  3367. }
  3368. const transformNode = this.getTransformNodeByID(id);
  3369. if (transformNode) {
  3370. return transformNode;
  3371. }
  3372. const light = this.getLightByID(id);
  3373. if (light) {
  3374. return light;
  3375. }
  3376. const camera = this.getCameraByID(id);
  3377. if (camera) {
  3378. return camera;
  3379. }
  3380. const bone = this.getBoneByID(id);
  3381. if (bone) {
  3382. return bone;
  3383. }
  3384. return null;
  3385. }
  3386. /**
  3387. * Gets a node (Mesh, Camera, Light) using a given name
  3388. * @param name defines the name to search for
  3389. * @return the found node or null if not found at all.
  3390. */
  3391. public getNodeByName(name: string): Nullable<Node> {
  3392. const mesh = this.getMeshByName(name);
  3393. if (mesh) {
  3394. return mesh;
  3395. }
  3396. const transformNode = this.getTransformNodeByName(name);
  3397. if (transformNode) {
  3398. return transformNode;
  3399. }
  3400. const light = this.getLightByName(name);
  3401. if (light) {
  3402. return light;
  3403. }
  3404. const camera = this.getCameraByName(name);
  3405. if (camera) {
  3406. return camera;
  3407. }
  3408. const bone = this.getBoneByName(name);
  3409. if (bone) {
  3410. return bone;
  3411. }
  3412. return null;
  3413. }
  3414. /**
  3415. * Gets a mesh using a given name
  3416. * @param name defines the name to search for
  3417. * @return the found mesh or null if not found at all.
  3418. */
  3419. public getMeshByName(name: string): Nullable<AbstractMesh> {
  3420. for (var index = 0; index < this.meshes.length; index++) {
  3421. if (this.meshes[index].name === name) {
  3422. return this.meshes[index];
  3423. }
  3424. }
  3425. return null;
  3426. }
  3427. /**
  3428. * Gets a transform node using a given name
  3429. * @param name defines the name to search for
  3430. * @return the found transform node or null if not found at all.
  3431. */
  3432. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  3433. for (var index = 0; index < this.transformNodes.length; index++) {
  3434. if (this.transformNodes[index].name === name) {
  3435. return this.transformNodes[index];
  3436. }
  3437. }
  3438. return null;
  3439. }
  3440. /**
  3441. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  3442. * @param id defines the id to search for
  3443. * @return the found skeleton or null if not found at all.
  3444. */
  3445. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  3446. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  3447. if (this.skeletons[index].id === id) {
  3448. return this.skeletons[index];
  3449. }
  3450. }
  3451. return null;
  3452. }
  3453. /**
  3454. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  3455. * @param id defines the id to search for
  3456. * @return the found skeleton or null if not found at all.
  3457. */
  3458. public getSkeletonById(id: string): Nullable<Skeleton> {
  3459. for (var index = 0; index < this.skeletons.length; index++) {
  3460. if (this.skeletons[index].id === id) {
  3461. return this.skeletons[index];
  3462. }
  3463. }
  3464. return null;
  3465. }
  3466. /**
  3467. * Gets a skeleton using a given name
  3468. * @param name defines the name to search for
  3469. * @return the found skeleton or null if not found at all.
  3470. */
  3471. public getSkeletonByName(name: string): Nullable<Skeleton> {
  3472. for (var index = 0; index < this.skeletons.length; index++) {
  3473. if (this.skeletons[index].name === name) {
  3474. return this.skeletons[index];
  3475. }
  3476. }
  3477. return null;
  3478. }
  3479. /**
  3480. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  3481. * @param id defines the id to search for
  3482. * @return the found morph target manager or null if not found at all.
  3483. */
  3484. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  3485. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  3486. if (this.morphTargetManagers[index].uniqueId === id) {
  3487. return this.morphTargetManagers[index];
  3488. }
  3489. }
  3490. return null;
  3491. }
  3492. /**
  3493. * Gets a morph target using a given id (if many are found, this function will pick the first one)
  3494. * @param id defines the id to search for
  3495. * @return the found morph target or null if not found at all.
  3496. */
  3497. public getMorphTargetById(id: string): Nullable<MorphTarget> {
  3498. for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) {
  3499. const morphTargetManager = this.morphTargetManagers[managerIndex];
  3500. for (let index = 0; index < morphTargetManager.numTargets; ++index) {
  3501. const target = morphTargetManager.getTarget(index);
  3502. if (target.id === id) {
  3503. return target;
  3504. }
  3505. }
  3506. }
  3507. return null;
  3508. }
  3509. /**
  3510. * Gets a boolean indicating if the given mesh is active
  3511. * @param mesh defines the mesh to look for
  3512. * @returns true if the mesh is in the active list
  3513. */
  3514. public isActiveMesh(mesh: AbstractMesh): boolean {
  3515. return (this._activeMeshes.indexOf(mesh) !== -1);
  3516. }
  3517. /**
  3518. * Return a unique id as a string which can serve as an identifier for the scene
  3519. */
  3520. public get uid(): string {
  3521. if (!this._uid) {
  3522. this._uid = Tools.RandomId();
  3523. }
  3524. return this._uid;
  3525. }
  3526. /**
  3527. * Add an externaly attached data from its key.
  3528. * This method call will fail and return false, if such key already exists.
  3529. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3530. * @param key the unique key that identifies the data
  3531. * @param data the data object to associate to the key for this Engine instance
  3532. * @return true if no such key were already present and the data was added successfully, false otherwise
  3533. */
  3534. public addExternalData<T>(key: string, data: T): boolean {
  3535. if (!this._externalData) {
  3536. this._externalData = new StringDictionary<Object>();
  3537. }
  3538. return this._externalData.add(key, data);
  3539. }
  3540. /**
  3541. * Get an externaly attached data from its key
  3542. * @param key the unique key that identifies the data
  3543. * @return the associated data, if present (can be null), or undefined if not present
  3544. */
  3545. public getExternalData<T>(key: string): Nullable<T> {
  3546. if (!this._externalData) {
  3547. return null;
  3548. }
  3549. return <T>this._externalData.get(key);
  3550. }
  3551. /**
  3552. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3553. * @param key the unique key that identifies the data
  3554. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3555. * @return the associated data, can be null if the factory returned null.
  3556. */
  3557. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3558. if (!this._externalData) {
  3559. this._externalData = new StringDictionary<Object>();
  3560. }
  3561. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3562. }
  3563. /**
  3564. * Remove an externaly attached data from the Engine instance
  3565. * @param key the unique key that identifies the data
  3566. * @return true if the data was successfully removed, false if it doesn't exist
  3567. */
  3568. public removeExternalData(key: string): boolean {
  3569. return this._externalData.remove(key);
  3570. }
  3571. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  3572. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  3573. for (let step of this._evaluateSubMeshStage) {
  3574. step.action(mesh, subMesh);
  3575. }
  3576. const material = subMesh.getMaterial();
  3577. if (material !== null && material !== undefined) {
  3578. // Render targets
  3579. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  3580. if (this._processedMaterials.indexOf(material) === -1) {
  3581. this._processedMaterials.push(material);
  3582. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  3583. }
  3584. }
  3585. // Dispatch
  3586. this._activeIndices.addCount(subMesh.indexCount, false);
  3587. this._renderingManager.dispatch(subMesh, mesh, material);
  3588. }
  3589. }
  3590. }
  3591. /**
  3592. * Clear the processed materials smart array preventing retention point in material dispose.
  3593. */
  3594. public freeProcessedMaterials(): void {
  3595. this._processedMaterials.dispose();
  3596. }
  3597. private _preventFreeActiveMeshesAndRenderingGroups = false;
  3598. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  3599. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  3600. * when disposing several meshes in a row or a hierarchy of meshes.
  3601. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  3602. */
  3603. public get blockfreeActiveMeshesAndRenderingGroups(): boolean {
  3604. return this._preventFreeActiveMeshesAndRenderingGroups;
  3605. }
  3606. public set blockfreeActiveMeshesAndRenderingGroups(value: boolean) {
  3607. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  3608. return;
  3609. }
  3610. if (value) {
  3611. this.freeActiveMeshes();
  3612. this.freeRenderingGroups();
  3613. }
  3614. this._preventFreeActiveMeshesAndRenderingGroups = value;
  3615. }
  3616. /**
  3617. * Clear the active meshes smart array preventing retention point in mesh dispose.
  3618. */
  3619. public freeActiveMeshes(): void {
  3620. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  3621. return;
  3622. }
  3623. this._activeMeshes.dispose();
  3624. if (this.activeCamera && this.activeCamera._activeMeshes) {
  3625. this.activeCamera._activeMeshes.dispose();
  3626. }
  3627. if (this.activeCameras) {
  3628. for (let i = 0; i < this.activeCameras.length; i++) {
  3629. let activeCamera = this.activeCameras[i];
  3630. if (activeCamera && activeCamera._activeMeshes) {
  3631. activeCamera._activeMeshes.dispose();
  3632. }
  3633. }
  3634. }
  3635. }
  3636. /**
  3637. * Clear the info related to rendering groups preventing retention points during dispose.
  3638. */
  3639. public freeRenderingGroups(): void {
  3640. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  3641. return;
  3642. }
  3643. if (this._renderingManager) {
  3644. this._renderingManager.freeRenderingGroups();
  3645. }
  3646. if (this.textures) {
  3647. for (let i = 0; i < this.textures.length; i++) {
  3648. let texture = this.textures[i];
  3649. if (texture && (<RenderTargetTexture>texture).renderList) {
  3650. (<RenderTargetTexture>texture).freeRenderingGroups();
  3651. }
  3652. }
  3653. }
  3654. }
  3655. /** @hidden */
  3656. public _isInIntermediateRendering(): boolean {
  3657. return this._intermediateRendering;
  3658. }
  3659. /**
  3660. * Lambda returning the list of potentially active meshes.
  3661. */
  3662. public getActiveMeshCandidates: () => ISmartArrayLike<AbstractMesh>;
  3663. /**
  3664. * Lambda returning the list of potentially active sub meshes.
  3665. */
  3666. public getActiveSubMeshCandidates: (mesh: AbstractMesh) => ISmartArrayLike<SubMesh>;
  3667. /**
  3668. * Lambda returning the list of potentially intersecting sub meshes.
  3669. */
  3670. public getIntersectingSubMeshCandidates: (mesh: AbstractMesh, localRay: Ray) => ISmartArrayLike<SubMesh>;
  3671. /**
  3672. * Lambda returning the list of potentially colliding sub meshes.
  3673. */
  3674. public getCollidingSubMeshCandidates: (mesh: AbstractMesh, collider: Collider) => ISmartArrayLike<SubMesh>;
  3675. private _activeMeshesFrozen = false;
  3676. /**
  3677. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  3678. * @returns the current scene
  3679. */
  3680. public freezeActiveMeshes(): Scene {
  3681. if (!this.activeCamera) {
  3682. return this;
  3683. }
  3684. if (!this._frustumPlanes) {
  3685. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3686. }
  3687. this._evaluateActiveMeshes();
  3688. this._activeMeshesFrozen = true;
  3689. return this;
  3690. }
  3691. /**
  3692. * Use this function to restart evaluating active meshes on every frame
  3693. * @returns the current scene
  3694. */
  3695. public unfreezeActiveMeshes(): Scene {
  3696. this._activeMeshesFrozen = false;
  3697. return this;
  3698. }
  3699. private _evaluateActiveMeshes(): void {
  3700. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  3701. return;
  3702. }
  3703. if (!this.activeCamera) {
  3704. return;
  3705. }
  3706. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  3707. this.activeCamera._activeMeshes.reset();
  3708. this._activeMeshes.reset();
  3709. this._renderingManager.reset();
  3710. this._processedMaterials.reset();
  3711. this._activeParticleSystems.reset();
  3712. this._activeSkeletons.reset();
  3713. this._softwareSkinnedMeshes.reset();
  3714. for (let step of this._beforeEvaluateActiveMeshStage) {
  3715. step.action();
  3716. }
  3717. // Determine mesh candidates
  3718. const meshes = this.getActiveMeshCandidates();
  3719. // Check each mesh
  3720. const len = meshes.length;
  3721. for (let i = 0; i < len; i++) {
  3722. const mesh = meshes.data[i];
  3723. if (mesh.isBlocked) {
  3724. continue;
  3725. }
  3726. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  3727. if (!mesh.isReady() || !mesh.isEnabled()) {
  3728. continue;
  3729. }
  3730. mesh.computeWorldMatrix();
  3731. // Intersections
  3732. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(Constants.ACTION_OnIntersectionEnterTrigger, Constants.ACTION_OnIntersectionExitTrigger)) {
  3733. this._meshesForIntersections.pushNoDuplicate(mesh);
  3734. }
  3735. // Switch to current LOD
  3736. const meshLOD = mesh.getLOD(this.activeCamera);
  3737. if (meshLOD === undefined || meshLOD === null) {
  3738. continue;
  3739. }
  3740. mesh._preActivate();
  3741. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  3742. this._activeMeshes.push(mesh);
  3743. this.activeCamera._activeMeshes.push(mesh);
  3744. mesh._activate(this._renderId);
  3745. if (meshLOD !== mesh) {
  3746. meshLOD._activate(this._renderId);
  3747. }
  3748. this._activeMesh(mesh, meshLOD);
  3749. }
  3750. }
  3751. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  3752. // Particle systems
  3753. if (this.particlesEnabled) {
  3754. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  3755. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  3756. var particleSystem = this.particleSystems[particleIndex];
  3757. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  3758. continue;
  3759. }
  3760. let emitter = <any>particleSystem.emitter;
  3761. if (!emitter.position || emitter.isEnabled()) {
  3762. this._activeParticleSystems.push(particleSystem);
  3763. particleSystem.animate();
  3764. this._renderingManager.dispatchParticles(particleSystem);
  3765. }
  3766. }
  3767. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  3768. }
  3769. }
  3770. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  3771. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  3772. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  3773. mesh.skeleton.prepare();
  3774. }
  3775. if (!mesh.computeBonesUsingShaders) {
  3776. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  3777. }
  3778. }
  3779. for (let step of this._activeMeshStage) {
  3780. step.action(sourceMesh, mesh);
  3781. }
  3782. if (
  3783. mesh !== undefined && mesh !== null
  3784. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  3785. ) {
  3786. const subMeshes = this.getActiveSubMeshCandidates(mesh);
  3787. const len = subMeshes.length;
  3788. for (let i = 0; i < len; i++) {
  3789. const subMesh = subMeshes.data[i];
  3790. this._evaluateSubMesh(subMesh, mesh);
  3791. }
  3792. }
  3793. }
  3794. /**
  3795. * Update the transform matrix to update from the current active camera
  3796. * @param force defines a boolean used to force the update even if cache is up to date
  3797. */
  3798. public updateTransformMatrix(force?: boolean): void {
  3799. if (!this.activeCamera) {
  3800. return;
  3801. }
  3802. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  3803. }
  3804. /**
  3805. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  3806. * @param alternateCamera defines the camera to use
  3807. */
  3808. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  3809. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  3810. }
  3811. /** @hidden */
  3812. public _allowPostProcessClearColor = true;
  3813. private _renderForCamera(camera: Camera, rigParent?: Camera): void {
  3814. if (camera && camera._skipRendering) {
  3815. return;
  3816. }
  3817. var engine = this._engine;
  3818. this.activeCamera = camera;
  3819. if (!this.activeCamera) {
  3820. throw new Error("Active camera not set");
  3821. }
  3822. // Viewport
  3823. engine.setViewport(this.activeCamera.viewport);
  3824. // Camera
  3825. this.resetCachedMaterial();
  3826. this._renderId++;
  3827. this.updateTransformMatrix();
  3828. if (camera._alternateCamera) {
  3829. this.updateAlternateTransformMatrix(camera._alternateCamera);
  3830. this._alternateRendering = true;
  3831. }
  3832. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  3833. // Meshes
  3834. this._evaluateActiveMeshes();
  3835. // Software skinning
  3836. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  3837. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  3838. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  3839. }
  3840. // Render targets
  3841. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3842. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  3843. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  3844. }
  3845. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  3846. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  3847. }
  3848. // Collects render targets from external components.
  3849. for (let step of this._gatherActiveCameraRenderTargetsStage) {
  3850. step.action(this._renderTargets);
  3851. }
  3852. if (this.renderTargetsEnabled) {
  3853. this._intermediateRendering = true;
  3854. if (this._renderTargets.length > 0) {
  3855. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3856. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  3857. let renderTarget = this._renderTargets.data[renderIndex];
  3858. if (renderTarget._shouldRender()) {
  3859. this._renderId++;
  3860. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  3861. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  3862. }
  3863. }
  3864. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3865. this._renderId++;
  3866. }
  3867. for (let step of this._cameraDrawRenderTargetStage) {
  3868. step.action(this.activeCamera);
  3869. }
  3870. this._intermediateRendering = false;
  3871. if (this.activeCamera.outputRenderTarget) {
  3872. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  3873. if (internalTexture) {
  3874. engine.bindFramebuffer(internalTexture);
  3875. } else {
  3876. Logger.Error("Camera contains invalid customDefaultRenderTarget");
  3877. }
  3878. } else {
  3879. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  3880. }
  3881. }
  3882. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3883. // Prepare Frame
  3884. if (this.postProcessManager) {
  3885. this.postProcessManager._prepareFrame();
  3886. }
  3887. // Before Camera Draw
  3888. for (let step of this._beforeCameraDrawStage) {
  3889. step.action(this.activeCamera);
  3890. }
  3891. // Render
  3892. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  3893. this._renderingManager.render(null, null, true, true);
  3894. this.onAfterDrawPhaseObservable.notifyObservers(this);
  3895. // After Camera Draw
  3896. for (let step of this._afterCameraDrawStage) {
  3897. step.action(this.activeCamera);
  3898. }
  3899. // Finalize frame
  3900. if (this.postProcessManager) {
  3901. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  3902. }
  3903. // Reset some special arrays
  3904. this._renderTargets.reset();
  3905. this._alternateRendering = false;
  3906. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  3907. }
  3908. private _processSubCameras(camera: Camera): void {
  3909. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  3910. this._renderForCamera(camera);
  3911. return;
  3912. }
  3913. // rig cameras
  3914. for (var index = 0; index < camera._rigCameras.length; index++) {
  3915. this._renderForCamera(camera._rigCameras[index], camera);
  3916. }
  3917. this.activeCamera = camera;
  3918. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3919. }
  3920. private _checkIntersections(): void {
  3921. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  3922. var sourceMesh = this._meshesForIntersections.data[index];
  3923. if (!sourceMesh.actionManager) {
  3924. continue;
  3925. }
  3926. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  3927. var action = sourceMesh.actionManager.actions[actionIndex];
  3928. if (action.trigger === Constants.ACTION_OnIntersectionEnterTrigger || action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3929. var parameters = action.getTriggerParameter();
  3930. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  3931. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  3932. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  3933. if (areIntersecting && currentIntersectionInProgress === -1) {
  3934. if (action.trigger === Constants.ACTION_OnIntersectionEnterTrigger) {
  3935. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3936. sourceMesh._intersectionsInProgress.push(otherMesh);
  3937. } else if (action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3938. sourceMesh._intersectionsInProgress.push(otherMesh);
  3939. }
  3940. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  3941. //They intersected, and now they don't.
  3942. //is this trigger an exit trigger? execute an event.
  3943. if (action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3944. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3945. }
  3946. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  3947. if (!sourceMesh.actionManager.hasSpecificTrigger(Constants.ACTION_OnIntersectionExitTrigger, (parameter) => {
  3948. var parameterMesh = parameter instanceof AbstractMesh ? parameter : parameter.mesh;
  3949. return otherMesh === parameterMesh;
  3950. }) || action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3951. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  3952. }
  3953. }
  3954. }
  3955. }
  3956. }
  3957. }
  3958. /** @hidden */
  3959. public _advancePhysicsEngineStep(step: number) {
  3960. // Do nothing. Code will be replaced if physics engine component is referenced
  3961. }
  3962. /**
  3963. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  3964. */
  3965. public getDeterministicFrameTime: () => number = () => {
  3966. return 1000.0 / 60.0; // frame time in ms
  3967. }
  3968. /**
  3969. * Render the scene
  3970. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  3971. */
  3972. public render(updateCameras = true): void {
  3973. if (this.isDisposed) {
  3974. return;
  3975. }
  3976. this._frameId++;
  3977. // Register components that have been associated lately to the scene.
  3978. this._registerTransientComponents();
  3979. this._activeParticles.fetchNewFrame();
  3980. this._totalVertices.fetchNewFrame();
  3981. this._activeIndices.fetchNewFrame();
  3982. this._activeBones.fetchNewFrame();
  3983. this._meshesForIntersections.reset();
  3984. this.resetCachedMaterial();
  3985. this.onBeforeAnimationsObservable.notifyObservers(this);
  3986. // Actions
  3987. if (this.actionManager) {
  3988. this.actionManager.processTrigger(Constants.ACTION_OnEveryFrameTrigger);
  3989. }
  3990. if (this._engine.isDeterministicLockStep()) {
  3991. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  3992. var defaultFPS = (60.0 / 1000.0);
  3993. let defaultFrameTime = this.getDeterministicFrameTime();
  3994. let stepsTaken = 0;
  3995. var maxSubSteps = this._engine.getLockstepMaxSteps();
  3996. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  3997. internalSteps = Math.min(internalSteps, maxSubSteps);
  3998. do {
  3999. this.onBeforeStepObservable.notifyObservers(this);
  4000. // Animations
  4001. this._animationRatio = defaultFrameTime * defaultFPS;
  4002. this._animate();
  4003. this.onAfterAnimationsObservable.notifyObservers(this);
  4004. // Physics
  4005. this._advancePhysicsEngineStep(defaultFrameTime);
  4006. this.onAfterStepObservable.notifyObservers(this);
  4007. this._currentStepId++;
  4008. stepsTaken++;
  4009. deltaTime -= defaultFrameTime;
  4010. } while (deltaTime > 0 && stepsTaken < internalSteps);
  4011. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  4012. }
  4013. else {
  4014. // Animations
  4015. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  4016. this._animationRatio = deltaTime * (60.0 / 1000.0);
  4017. this._animate();
  4018. this.onAfterAnimationsObservable.notifyObservers(this);
  4019. // Physics
  4020. this._advancePhysicsEngineStep(deltaTime);
  4021. }
  4022. // Before camera update steps
  4023. for (let step of this._beforeCameraUpdateStage) {
  4024. step.action();
  4025. }
  4026. // Update Cameras
  4027. if (updateCameras) {
  4028. if (this.activeCameras.length > 0) {
  4029. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  4030. let camera = this.activeCameras[cameraIndex];
  4031. camera.update();
  4032. if (camera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  4033. // rig cameras
  4034. for (var index = 0; index < camera._rigCameras.length; index++) {
  4035. camera._rigCameras[index].update();
  4036. }
  4037. }
  4038. }
  4039. } else if (this.activeCamera) {
  4040. this.activeCamera.update();
  4041. if (this.activeCamera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  4042. // rig cameras
  4043. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  4044. this.activeCamera._rigCameras[index].update();
  4045. }
  4046. }
  4047. }
  4048. }
  4049. // Before render
  4050. this.onBeforeRenderObservable.notifyObservers(this);
  4051. // Customs render targets
  4052. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  4053. var engine = this.getEngine();
  4054. var currentActiveCamera = this.activeCamera;
  4055. if (this.renderTargetsEnabled) {
  4056. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  4057. this._intermediateRendering = true;
  4058. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  4059. var renderTarget = this.customRenderTargets[customIndex];
  4060. if (renderTarget._shouldRender()) {
  4061. this._renderId++;
  4062. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  4063. if (!this.activeCamera) {
  4064. throw new Error("Active camera not set");
  4065. }
  4066. // Viewport
  4067. engine.setViewport(this.activeCamera.viewport);
  4068. // Camera
  4069. this.updateTransformMatrix();
  4070. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  4071. }
  4072. }
  4073. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  4074. this._intermediateRendering = false;
  4075. this._renderId++;
  4076. }
  4077. // Restore back buffer
  4078. if (this.customRenderTargets.length > 0) {
  4079. engine.restoreDefaultFramebuffer();
  4080. }
  4081. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  4082. this.activeCamera = currentActiveCamera;
  4083. for (let step of this._beforeClearStage) {
  4084. step.action();
  4085. }
  4086. // Clear
  4087. if (this.autoClearDepthAndStencil || this.autoClear) {
  4088. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  4089. }
  4090. // Collects render targets from external components.
  4091. for (let step of this._gatherRenderTargetsStage) {
  4092. step.action(this._renderTargets);
  4093. }
  4094. // Multi-cameras?
  4095. if (this.activeCameras.length > 0) {
  4096. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  4097. if (cameraIndex > 0) {
  4098. this._engine.clear(null, false, true, true);
  4099. }
  4100. this._processSubCameras(this.activeCameras[cameraIndex]);
  4101. }
  4102. } else {
  4103. if (!this.activeCamera) {
  4104. throw new Error("No camera defined");
  4105. }
  4106. this._processSubCameras(this.activeCamera);
  4107. }
  4108. // Intersection checks
  4109. this._checkIntersections();
  4110. // Executes the after render stage actions.
  4111. for (let step of this._afterRenderStage) {
  4112. step.action();
  4113. }
  4114. // After render
  4115. if (this.afterRender) {
  4116. this.afterRender();
  4117. }
  4118. this.onAfterRenderObservable.notifyObservers(this);
  4119. // Cleaning
  4120. if (this._toBeDisposed.length) {
  4121. for (var index = 0; index < this._toBeDisposed.length; index++) {
  4122. var data = this._toBeDisposed[index];
  4123. if (data) {
  4124. data.dispose();
  4125. }
  4126. }
  4127. this._toBeDisposed = [];
  4128. }
  4129. if (this.dumpNextRenderTargets) {
  4130. this.dumpNextRenderTargets = false;
  4131. }
  4132. this._activeBones.addCount(0, true);
  4133. this._activeIndices.addCount(0, true);
  4134. this._activeParticles.addCount(0, true);
  4135. }
  4136. /**
  4137. * Freeze all materials
  4138. * A frozen material will not be updatable but should be faster to render
  4139. */
  4140. public freezeMaterials(): void {
  4141. for (var i = 0; i < this.materials.length; i++) {
  4142. this.materials[i].freeze();
  4143. }
  4144. }
  4145. /**
  4146. * Unfreeze all materials
  4147. * A frozen material will not be updatable but should be faster to render
  4148. */
  4149. public unfreezeMaterials(): void {
  4150. for (var i = 0; i < this.materials.length; i++) {
  4151. this.materials[i].unfreeze();
  4152. }
  4153. }
  4154. /**
  4155. * Releases all held ressources
  4156. */
  4157. public dispose(): void {
  4158. this.beforeRender = null;
  4159. this.afterRender = null;
  4160. this.skeletons = [];
  4161. this.morphTargetManagers = [];
  4162. this._transientComponents = [];
  4163. this._isReadyForMeshStage.clear();
  4164. this._beforeEvaluateActiveMeshStage.clear();
  4165. this._evaluateSubMeshStage.clear();
  4166. this._activeMeshStage.clear();
  4167. this._cameraDrawRenderTargetStage.clear();
  4168. this._beforeCameraDrawStage.clear();
  4169. this._beforeRenderTargetDrawStage.clear();
  4170. this._beforeRenderingGroupDrawStage.clear();
  4171. this._beforeRenderingMeshStage.clear();
  4172. this._afterRenderingMeshStage.clear();
  4173. this._afterRenderingGroupDrawStage.clear();
  4174. this._afterCameraDrawStage.clear();
  4175. this._afterRenderTargetDrawStage.clear();
  4176. this._afterRenderStage.clear();
  4177. this._beforeCameraUpdateStage.clear();
  4178. this._beforeClearStage.clear();
  4179. this._gatherRenderTargetsStage.clear();
  4180. this._gatherActiveCameraRenderTargetsStage.clear();
  4181. this._pointerMoveStage.clear();
  4182. this._pointerDownStage.clear();
  4183. this._pointerUpStage.clear();
  4184. for (let component of this._components) {
  4185. component.dispose();
  4186. }
  4187. this.importedMeshesFiles = new Array<string>();
  4188. this.stopAllAnimations();
  4189. this.resetCachedMaterial();
  4190. // Smart arrays
  4191. if (this.activeCamera) {
  4192. this.activeCamera._activeMeshes.dispose();
  4193. this.activeCamera = null;
  4194. }
  4195. this._activeMeshes.dispose();
  4196. this._renderingManager.dispose();
  4197. this._processedMaterials.dispose();
  4198. this._activeParticleSystems.dispose();
  4199. this._activeSkeletons.dispose();
  4200. this._softwareSkinnedMeshes.dispose();
  4201. this._renderTargets.dispose();
  4202. this._registeredForLateAnimationBindings.dispose();
  4203. this._meshesForIntersections.dispose();
  4204. this._toBeDisposed = [];
  4205. // Abort active requests
  4206. for (let request of this._activeRequests) {
  4207. request.abort();
  4208. }
  4209. // Events
  4210. this.onDisposeObservable.notifyObservers(this);
  4211. this.onDisposeObservable.clear();
  4212. this.onBeforeRenderObservable.clear();
  4213. this.onAfterRenderObservable.clear();
  4214. this.onBeforeRenderTargetsRenderObservable.clear();
  4215. this.onAfterRenderTargetsRenderObservable.clear();
  4216. this.onAfterStepObservable.clear();
  4217. this.onBeforeStepObservable.clear();
  4218. this.onBeforeActiveMeshesEvaluationObservable.clear();
  4219. this.onAfterActiveMeshesEvaluationObservable.clear();
  4220. this.onBeforeParticlesRenderingObservable.clear();
  4221. this.onAfterParticlesRenderingObservable.clear();
  4222. this.onBeforeDrawPhaseObservable.clear();
  4223. this.onAfterDrawPhaseObservable.clear();
  4224. this.onBeforeAnimationsObservable.clear();
  4225. this.onAfterAnimationsObservable.clear();
  4226. this.onDataLoadedObservable.clear();
  4227. this.onBeforeRenderingGroupObservable.clear();
  4228. this.onAfterRenderingGroupObservable.clear();
  4229. this.onMeshImportedObservable.clear();
  4230. this.onBeforeCameraRenderObservable.clear();
  4231. this.onAfterCameraRenderObservable.clear();
  4232. this.onReadyObservable.clear();
  4233. this.onNewCameraAddedObservable.clear();
  4234. this.onCameraRemovedObservable.clear();
  4235. this.onNewLightAddedObservable.clear();
  4236. this.onLightRemovedObservable.clear();
  4237. this.onNewGeometryAddedObservable.clear();
  4238. this.onGeometryRemovedObservable.clear();
  4239. this.onNewTransformNodeAddedObservable.clear();
  4240. this.onTransformNodeRemovedObservable.clear();
  4241. this.onNewMeshAddedObservable.clear();
  4242. this.onMeshRemovedObservable.clear();
  4243. this.onNewMaterialAddedObservable.clear();
  4244. this.onMaterialRemovedObservable.clear();
  4245. this.onNewTextureAddedObservable.clear();
  4246. this.onTextureRemovedObservable.clear();
  4247. this.onPrePointerObservable.clear();
  4248. this.onPointerObservable.clear();
  4249. this.onPreKeyboardObservable.clear();
  4250. this.onKeyboardObservable.clear();
  4251. this.onActiveCameraChanged.clear();
  4252. this.detachControl();
  4253. // Detach cameras
  4254. var canvas = this._engine.getRenderingCanvas();
  4255. if (canvas) {
  4256. var index;
  4257. for (index = 0; index < this.cameras.length; index++) {
  4258. this.cameras[index].detachControl(canvas);
  4259. }
  4260. }
  4261. // Release animation groups
  4262. while (this.animationGroups.length) {
  4263. this.animationGroups[0].dispose();
  4264. }
  4265. // Release lights
  4266. while (this.lights.length) {
  4267. this.lights[0].dispose();
  4268. }
  4269. // Release meshes
  4270. while (this.meshes.length) {
  4271. this.meshes[0].dispose(true);
  4272. }
  4273. while (this.transformNodes.length) {
  4274. this.removeTransformNode(this.transformNodes[0]);
  4275. }
  4276. // Release cameras
  4277. while (this.cameras.length) {
  4278. this.cameras[0].dispose();
  4279. }
  4280. // Release materials
  4281. if (this.defaultMaterial) {
  4282. this.defaultMaterial.dispose();
  4283. }
  4284. while (this.multiMaterials.length) {
  4285. this.multiMaterials[0].dispose();
  4286. }
  4287. while (this.materials.length) {
  4288. this.materials[0].dispose();
  4289. }
  4290. // Release particles
  4291. while (this.particleSystems.length) {
  4292. this.particleSystems[0].dispose();
  4293. }
  4294. // Release postProcesses
  4295. while (this.postProcesses.length) {
  4296. this.postProcesses[0].dispose();
  4297. }
  4298. // Release textures
  4299. while (this.textures.length) {
  4300. this.textures[0].dispose();
  4301. }
  4302. // Release UBO
  4303. this._sceneUbo.dispose();
  4304. if (this._alternateSceneUbo) {
  4305. this._alternateSceneUbo.dispose();
  4306. }
  4307. // Post-processes
  4308. this.postProcessManager.dispose();
  4309. // Remove from engine
  4310. index = this._engine.scenes.indexOf(this);
  4311. if (index > -1) {
  4312. this._engine.scenes.splice(index, 1);
  4313. }
  4314. this._engine.wipeCaches(true);
  4315. this._isDisposed = true;
  4316. }
  4317. /**
  4318. * Gets if the scene is already disposed
  4319. */
  4320. public get isDisposed(): boolean {
  4321. return this._isDisposed;
  4322. }
  4323. /**
  4324. * Call this function to reduce memory footprint of the scene.
  4325. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  4326. */
  4327. public clearCachedVertexData(): void {
  4328. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4329. var mesh = this.meshes[meshIndex];
  4330. var geometry = (<Mesh>mesh).geometry;
  4331. if (geometry) {
  4332. geometry._indices = [];
  4333. for (var vbName in geometry._vertexBuffers) {
  4334. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  4335. continue;
  4336. }
  4337. geometry._vertexBuffers[vbName]._buffer._data = null;
  4338. }
  4339. }
  4340. }
  4341. }
  4342. /**
  4343. * This function will remove the local cached buffer data from texture.
  4344. * It will save memory but will prevent the texture from being rebuilt
  4345. */
  4346. public cleanCachedTextureBuffer(): void {
  4347. for (var baseTexture of this.textures) {
  4348. let buffer = (<Texture>baseTexture)._buffer;
  4349. if (buffer) {
  4350. (<Texture>baseTexture)._buffer = null;
  4351. }
  4352. }
  4353. }
  4354. /**
  4355. * Get the world extend vectors with an optional filter
  4356. *
  4357. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  4358. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  4359. */
  4360. public getWorldExtends(filterPredicate?: (mesh: AbstractMesh) => boolean): { min: Vector3; max: Vector3 } {
  4361. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4362. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4363. filterPredicate = filterPredicate || (() => true);
  4364. this.meshes.filter(filterPredicate).forEach((mesh) => {
  4365. mesh.computeWorldMatrix(true);
  4366. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  4367. return;
  4368. }
  4369. let boundingInfo = mesh.getBoundingInfo();
  4370. var minBox = boundingInfo.boundingBox.minimumWorld;
  4371. var maxBox = boundingInfo.boundingBox.maximumWorld;
  4372. Tools.CheckExtends(minBox, min, max);
  4373. Tools.CheckExtends(maxBox, min, max);
  4374. });
  4375. return {
  4376. min: min,
  4377. max: max
  4378. };
  4379. }
  4380. // Picking
  4381. /**
  4382. * Creates a ray that can be used to pick in the scene
  4383. * @param x defines the x coordinate of the origin (on-screen)
  4384. * @param y defines the y coordinate of the origin (on-screen)
  4385. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4386. * @param camera defines the camera to use for the picking
  4387. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4388. * @returns a Ray
  4389. */
  4390. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  4391. let result = Ray.Zero();
  4392. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  4393. return result;
  4394. }
  4395. /**
  4396. * Creates a ray that can be used to pick in the scene
  4397. * @param x defines the x coordinate of the origin (on-screen)
  4398. * @param y defines the y coordinate of the origin (on-screen)
  4399. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4400. * @param result defines the ray where to store the picking ray
  4401. * @param camera defines the camera to use for the picking
  4402. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4403. * @returns the current scene
  4404. */
  4405. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  4406. var engine = this._engine;
  4407. if (!camera) {
  4408. if (!this.activeCamera) {
  4409. throw new Error("Active camera not set");
  4410. }
  4411. camera = this.activeCamera;
  4412. }
  4413. var cameraViewport = camera.viewport;
  4414. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4415. // Moving coordinates to local viewport world
  4416. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  4417. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  4418. result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.IdentityReadOnly, cameraViewSpace ? Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix());
  4419. return this;
  4420. }
  4421. /**
  4422. * Creates a ray that can be used to pick in the scene
  4423. * @param x defines the x coordinate of the origin (on-screen)
  4424. * @param y defines the y coordinate of the origin (on-screen)
  4425. * @param camera defines the camera to use for the picking
  4426. * @returns a Ray
  4427. */
  4428. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  4429. let result = Ray.Zero();
  4430. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  4431. return result;
  4432. }
  4433. /**
  4434. * Creates a ray that can be used to pick in the scene
  4435. * @param x defines the x coordinate of the origin (on-screen)
  4436. * @param y defines the y coordinate of the origin (on-screen)
  4437. * @param result defines the ray where to store the picking ray
  4438. * @param camera defines the camera to use for the picking
  4439. * @returns the current scene
  4440. */
  4441. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  4442. if (!PickingInfo) {
  4443. return this;
  4444. }
  4445. var engine = this._engine;
  4446. if (!camera) {
  4447. if (!this.activeCamera) {
  4448. throw new Error("Active camera not set");
  4449. }
  4450. camera = this.activeCamera;
  4451. }
  4452. var cameraViewport = camera.viewport;
  4453. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4454. var identity = Matrix.Identity();
  4455. // Moving coordinates to local viewport world
  4456. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  4457. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  4458. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  4459. return this;
  4460. }
  4461. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  4462. if (!PickingInfo) {
  4463. return null;
  4464. }
  4465. var pickingInfo = null;
  4466. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4467. var mesh = this.meshes[meshIndex];
  4468. if (predicate) {
  4469. if (!predicate(mesh)) {
  4470. continue;
  4471. }
  4472. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  4473. continue;
  4474. }
  4475. var world = mesh.getWorldMatrix();
  4476. var ray = rayFunction(world);
  4477. var result = mesh.intersects(ray, fastCheck);
  4478. if (!result || !result.hit) {
  4479. continue;
  4480. }
  4481. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  4482. continue;
  4483. }
  4484. pickingInfo = result;
  4485. if (fastCheck) {
  4486. break;
  4487. }
  4488. }
  4489. return pickingInfo || new PickingInfo();
  4490. }
  4491. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  4492. if (!PickingInfo) {
  4493. return null;
  4494. }
  4495. var pickingInfos = new Array<PickingInfo>();
  4496. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4497. var mesh = this.meshes[meshIndex];
  4498. if (predicate) {
  4499. if (!predicate(mesh)) {
  4500. continue;
  4501. }
  4502. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  4503. continue;
  4504. }
  4505. var world = mesh.getWorldMatrix();
  4506. var ray = rayFunction(world);
  4507. var result = mesh.intersects(ray, false);
  4508. if (!result || !result.hit) {
  4509. continue;
  4510. }
  4511. pickingInfos.push(result);
  4512. }
  4513. return pickingInfos;
  4514. }
  4515. private _tempPickingRay: Nullable<Ray> = Ray ? Ray.Zero() : null;
  4516. /** Launch a ray to try to pick a mesh in the scene
  4517. * @param x position on screen
  4518. * @param y position on screen
  4519. * @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
  4520. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  4521. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4522. * @returns a PickingInfo
  4523. */
  4524. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  4525. if (!PickingInfo) {
  4526. return null;
  4527. }
  4528. var result = this._internalPick((world) => {
  4529. this.createPickingRayToRef(x, y, world, this._tempPickingRay!, camera || null);
  4530. return this._tempPickingRay!;
  4531. }, predicate, fastCheck);
  4532. if (result) {
  4533. result.ray = this.createPickingRay(x, y, Matrix.Identity(), camera || null);
  4534. }
  4535. return result;
  4536. }
  4537. private _cachedRayForTransform: Ray;
  4538. /** Use the given ray to pick a mesh in the scene
  4539. * @param ray The ray to use to pick meshes
  4540. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  4541. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  4542. * @returns a PickingInfo
  4543. */
  4544. public pickWithRay(ray: Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  4545. var result = this._internalPick((world) => {
  4546. if (!this._pickWithRayInverseMatrix) {
  4547. this._pickWithRayInverseMatrix = Matrix.Identity();
  4548. }
  4549. world.invertToRef(this._pickWithRayInverseMatrix);
  4550. if (!this._cachedRayForTransform) {
  4551. this._cachedRayForTransform = Ray.Zero();
  4552. }
  4553. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  4554. return this._cachedRayForTransform;
  4555. }, predicate, fastCheck);
  4556. if (result) {
  4557. result.ray = ray;
  4558. }
  4559. return result;
  4560. }
  4561. /**
  4562. * Launch a ray to try to pick a mesh in the scene
  4563. * @param x X position on screen
  4564. * @param y Y position on screen
  4565. * @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
  4566. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4567. * @returns an array of PickingInfo
  4568. */
  4569. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): Nullable<PickingInfo[]> {
  4570. return this._internalMultiPick((world) => this.createPickingRay(x, y, world, camera || null), predicate);
  4571. }
  4572. /**
  4573. * Launch a ray to try to pick a mesh in the scene
  4574. * @param ray Ray to use
  4575. * @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
  4576. * @returns an array of PickingInfo
  4577. */
  4578. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  4579. return this._internalMultiPick((world) => {
  4580. if (!this._pickWithRayInverseMatrix) {
  4581. this._pickWithRayInverseMatrix = Matrix.Identity();
  4582. }
  4583. world.invertToRef(this._pickWithRayInverseMatrix);
  4584. if (!this._cachedRayForTransform) {
  4585. this._cachedRayForTransform = Ray.Zero();
  4586. }
  4587. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  4588. return this._cachedRayForTransform;
  4589. }, predicate);
  4590. }
  4591. /**
  4592. * Force the value of meshUnderPointer
  4593. * @param mesh defines the mesh to use
  4594. */
  4595. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  4596. if (this._pointerOverMesh === mesh) {
  4597. return;
  4598. }
  4599. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  4600. this._pointerOverMesh.actionManager.processTrigger(Constants.ACTION_OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4601. }
  4602. this._pointerOverMesh = mesh;
  4603. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  4604. this._pointerOverMesh.actionManager.processTrigger(Constants.ACTION_OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4605. }
  4606. }
  4607. /**
  4608. * Gets the mesh under the pointer
  4609. * @returns a Mesh or null if no mesh is under the pointer
  4610. */
  4611. public getPointerOverMesh(): Nullable<AbstractMesh> {
  4612. return this._pointerOverMesh;
  4613. }
  4614. // Misc.
  4615. /** @hidden */
  4616. public _rebuildGeometries(): void {
  4617. for (var geometry of this.geometries) {
  4618. geometry._rebuild();
  4619. }
  4620. for (var mesh of this.meshes) {
  4621. mesh._rebuild();
  4622. }
  4623. if (this.postProcessManager) {
  4624. this.postProcessManager._rebuild();
  4625. }
  4626. for (let component of this._components) {
  4627. component.rebuild();
  4628. }
  4629. for (var system of this.particleSystems) {
  4630. system.rebuild();
  4631. }
  4632. }
  4633. /** @hidden */
  4634. public _rebuildTextures(): void {
  4635. for (var texture of this.textures) {
  4636. texture._rebuild();
  4637. }
  4638. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  4639. }
  4640. // Tags
  4641. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  4642. if (tagsQuery === undefined) {
  4643. // returns the complete list (could be done with Tags.MatchesQuery but no need to have a for-loop here)
  4644. return list;
  4645. }
  4646. var listByTags = [];
  4647. forEach = forEach || ((item: any) => { return; });
  4648. for (var i in list) {
  4649. var item = list[i];
  4650. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  4651. listByTags.push(item);
  4652. forEach(item);
  4653. }
  4654. }
  4655. return listByTags;
  4656. }
  4657. /**
  4658. * Get a list of meshes by tags
  4659. * @param tagsQuery defines the tags query to use
  4660. * @param forEach defines a predicate used to filter results
  4661. * @returns an array of Mesh
  4662. */
  4663. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  4664. return this._getByTags(this.meshes, tagsQuery, forEach);
  4665. }
  4666. /**
  4667. * Get a list of cameras by tags
  4668. * @param tagsQuery defines the tags query to use
  4669. * @param forEach defines a predicate used to filter results
  4670. * @returns an array of Camera
  4671. */
  4672. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  4673. return this._getByTags(this.cameras, tagsQuery, forEach);
  4674. }
  4675. /**
  4676. * Get a list of lights by tags
  4677. * @param tagsQuery defines the tags query to use
  4678. * @param forEach defines a predicate used to filter results
  4679. * @returns an array of Light
  4680. */
  4681. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  4682. return this._getByTags(this.lights, tagsQuery, forEach);
  4683. }
  4684. /**
  4685. * Get a list of materials by tags
  4686. * @param tagsQuery defines the tags query to use
  4687. * @param forEach defines a predicate used to filter results
  4688. * @returns an array of Material
  4689. */
  4690. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  4691. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  4692. }
  4693. /**
  4694. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  4695. * This allowed control for front to back rendering or reversly depending of the special needs.
  4696. *
  4697. * @param renderingGroupId The rendering group id corresponding to its index
  4698. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  4699. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  4700. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  4701. */
  4702. public setRenderingOrder(renderingGroupId: number,
  4703. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4704. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4705. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  4706. this._renderingManager.setRenderingOrder(renderingGroupId,
  4707. opaqueSortCompareFn,
  4708. alphaTestSortCompareFn,
  4709. transparentSortCompareFn);
  4710. }
  4711. /**
  4712. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  4713. *
  4714. * @param renderingGroupId The rendering group id corresponding to its index
  4715. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  4716. * @param depth Automatically clears depth between groups if true and autoClear is true.
  4717. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  4718. */
  4719. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  4720. depth = true,
  4721. stencil = true): void {
  4722. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  4723. }
  4724. /**
  4725. * Gets the current auto clear configuration for one rendering group of the rendering
  4726. * manager.
  4727. * @param index the rendering group index to get the information for
  4728. * @returns The auto clear setup for the requested rendering group
  4729. */
  4730. public getAutoClearDepthStencilSetup(index: number): IRenderingManagerAutoClearSetup {
  4731. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  4732. }
  4733. private _blockMaterialDirtyMechanism = false;
  4734. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  4735. public get blockMaterialDirtyMechanism(): boolean {
  4736. return this._blockMaterialDirtyMechanism;
  4737. }
  4738. public set blockMaterialDirtyMechanism(value: boolean) {
  4739. if (this._blockMaterialDirtyMechanism === value) {
  4740. return;
  4741. }
  4742. this._blockMaterialDirtyMechanism = value;
  4743. if (!value) { // Do a complete update
  4744. this.markAllMaterialsAsDirty(Constants.MATERIAL_AllDirtyFlag);
  4745. }
  4746. }
  4747. /**
  4748. * Will flag all materials as dirty to trigger new shader compilation
  4749. * @param flag defines the flag used to specify which material part must be marked as dirty
  4750. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  4751. */
  4752. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  4753. if (this._blockMaterialDirtyMechanism) {
  4754. return;
  4755. }
  4756. for (var material of this.materials) {
  4757. if (predicate && !predicate(material)) {
  4758. continue;
  4759. }
  4760. material.markAsDirty(flag);
  4761. }
  4762. }
  4763. /** @hidden */
  4764. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, useOfflineSupport?: boolean, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  4765. let request = Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  4766. this._activeRequests.push(request);
  4767. request.onCompleteObservable.add((request) => {
  4768. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4769. });
  4770. return request;
  4771. }
  4772. /** @hidden */
  4773. public _loadFileAsync(url: string, useOfflineSupport?: boolean, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4774. return new Promise((resolve, reject) => {
  4775. this._loadFile(url, (data) => {
  4776. resolve(data);
  4777. }, undefined, useOfflineSupport, useArrayBuffer, (request, exception) => {
  4778. reject(exception);
  4779. });
  4780. });
  4781. }
  4782. }