babylon.scene.ts 246 KB

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