scene.ts 164 KB

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