scene.ts 169 KB

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