scene.ts 183 KB

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