scene.ts 221 KB

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