babylon.scene.ts 224 KB

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