babylon.scene.ts 221 KB

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