babylon.scene.ts 223 KB

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