scene.ts 188 KB

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