scene.ts 156 KB

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