babylon.scene.ts 195 KB

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